From 30da23fa7770cc8bac06f776522ddfa79df8b4a5 Mon Sep 17 00:00:00 2001 From: uniqueiniquity Date: Thu, 30 Nov 2017 10:22:41 -0800 Subject: [PATCH 01/75] Handle failure to properly resolve type reference directives --- src/compiler/checker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 405fd11f138..c797200bff2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -25000,10 +25000,11 @@ namespace ts { // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = createMap(); resolvedTypeReferenceDirectives.forEach((resolvedDirective, key) => { - if (!resolvedDirective) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { return; } const file = host.getSourceFile(resolvedDirective.resolvedFileName); + Debug.assert(!!file, `Resolved filename ${resolvedDirective.resolvedFileName} did not map to existing source file. Consider enabling --preserveSymlinks if appropriate`); // tslint:disable-line fileToDirective.set(file.path, key); }); } From 1fc6675a2973b2ad361ab3bf4c946bc48baeeb95 Mon Sep 17 00:00:00 2001 From: uniqueiniquity Date: Wed, 6 Dec 2017 14:40:59 -0800 Subject: [PATCH 02/75] Allow for undefined return from TypeCheckerHost.getSourceFile to correspond with implementation --- src/compiler/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index f6ca2f45d34..6ab0f5543ec 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2736,7 +2736,7 @@ namespace ts { getCompilerOptions(): CompilerOptions; getSourceFiles(): ReadonlyArray; - getSourceFile(fileName: string): SourceFile; + getSourceFile(fileName: string): SourceFile | undefined; getResolvedTypeReferenceDirectives(): ReadonlyMap; } From 46fa477c156f9771e8be4cb70eff3a1458cb7962 Mon Sep 17 00:00:00 2001 From: uniqueiniquity Date: Fri, 19 Jan 2018 16:22:09 -0800 Subject: [PATCH 03/75] Move assertion to realpath evaluation --- src/compiler/checker.ts | 1 - src/compiler/moduleNameResolver.ts | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c797200bff2..41e1ed99dc6 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -25004,7 +25004,6 @@ namespace ts { return; } const file = host.getSourceFile(resolvedDirective.resolvedFileName); - Debug.assert(!!file, `Resolved filename ${resolvedDirective.resolvedFileName} did not map to existing source file. Consider enabling --preserveSymlinks if appropriate`); // tslint:disable-line fileToDirective.set(file.path, key); }); } diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index f72876bd5fc..e0acf43eadf 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -782,6 +782,7 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real); } + Debug.assert(host.fileExists(real), `${path} linked to non-existing file ${real}`); // tslint:disable-line return real; } From 4a877897792ec3ec58ab06991d314af03dc37181 Mon Sep 17 00:00:00 2001 From: uniqueiniquity Date: Fri, 19 Jan 2018 16:40:52 -0800 Subject: [PATCH 04/75] Fix typo in message --- src/compiler/moduleNameResolver.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index e0acf43eadf..4f893302693 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -782,7 +782,7 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real); } - Debug.assert(host.fileExists(real), `${path} linked to non-existing file ${real}`); // tslint:disable-line + Debug.assert(host.fileExists(real), `${path} linked to nonexistent file ${real}`); // tslint:disable-line return real; } From d716e2134e911e7aafee89be1a52ca72d716565c Mon Sep 17 00:00:00 2001 From: Maarten Sijm Date: Thu, 1 Mar 2018 23:13:04 +0100 Subject: [PATCH 05/75] Fix #21617: Give detailed message on `for-of` of iterators without downlevelIteration --- src/compiler/checker.ts | 9 +++++-- src/compiler/diagnosticMessages.json | 8 ++++++ .../reference/ES5For-ofTypeCheck10.errors.txt | 4 +-- .../reference/ES5For-ofTypeCheck13.errors.txt | 10 ++++++++ .../reference/ES5For-ofTypeCheck13.js | 13 ++++++++++ .../reference/ES5For-ofTypeCheck13.symbols | 20 +++++++++++++++ .../reference/ES5For-ofTypeCheck13.types | 25 +++++++++++++++++++ .../reference/ES5For-ofTypeCheck14.errors.txt | 8 ++++++ .../reference/ES5For-ofTypeCheck14.js | 9 +++++++ .../reference/ES5For-ofTypeCheck14.symbols | 9 +++++++ .../reference/ES5For-ofTypeCheck14.types | 9 +++++++ .../for-ofStatements/ES5For-ofTypeCheck13.ts | 6 +++++ .../for-ofStatements/ES5For-ofTypeCheck14.ts | 4 +++ 13 files changed, 130 insertions(+), 4 deletions(-) create mode 100644 tests/baselines/reference/ES5For-ofTypeCheck13.errors.txt create mode 100644 tests/baselines/reference/ES5For-ofTypeCheck13.js create mode 100644 tests/baselines/reference/ES5For-ofTypeCheck13.symbols create mode 100644 tests/baselines/reference/ES5For-ofTypeCheck13.types create mode 100644 tests/baselines/reference/ES5For-ofTypeCheck14.errors.txt create mode 100644 tests/baselines/reference/ES5For-ofTypeCheck14.js create mode 100644 tests/baselines/reference/ES5For-ofTypeCheck14.symbols create mode 100644 tests/baselines/reference/ES5For-ofTypeCheck14.types create mode 100644 tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck13.ts create mode 100644 tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 587f7eb4837..087199f6288 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22316,13 +22316,18 @@ namespace ts { // 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. + const isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); const diagnostic = !allowStringInput || hasStringConstituent ? downlevelIteration ? Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : Diagnostics.Type_0_is_not_an_array_type + : isIterable + ? Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : Diagnostics.Type_0_is_not_an_array_type : downlevelIteration ? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + : isIterable + ? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; error(errorNode, diagnostic, typeToString(arrayType)); } return hasStringConstituent ? stringType : undefined; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index ced3699c6d4..364e99e0311 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1988,6 +1988,14 @@ "category": "Error", "code": 2567 }, + "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators.": { + "category": "Error", + "code": 2568 + }, + "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.": { + "category": "Error", + "code": 2569 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", diff --git a/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt b/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt index e608378d7f1..6bb1d505680 100644 --- a/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt +++ b/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(9,6): error TS2304: Cannot find name 'Symbol'. -tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,15): error TS2495: Type 'StringIterator' is not an array type or a string type. +tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,15): error TS2569: Type 'StringIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts (2 errors) ==== @@ -20,4 +20,4 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,1 for (var v of new StringIterator) { } ~~~~~~~~~~~~~~~~~~ -!!! error TS2495: Type 'StringIterator' is not an array type or a string type. \ No newline at end of file +!!! error TS2569: Type 'StringIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-ofTypeCheck13.errors.txt b/tests/baselines/reference/ES5For-ofTypeCheck13.errors.txt new file mode 100644 index 00000000000..b64781a4873 --- /dev/null +++ b/tests/baselines/reference/ES5For-ofTypeCheck13.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck13.ts(4,19): error TS2569: Type 'Set' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. + + +==== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck13.ts (1 errors) ==== + const strSet: Set = new Set() + strSet.add('Hello') + strSet.add('World') + for (const str of strSet) { } + ~~~~~~ +!!! error TS2569: Type 'Set' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-ofTypeCheck13.js b/tests/baselines/reference/ES5For-ofTypeCheck13.js new file mode 100644 index 00000000000..216aa57f97c --- /dev/null +++ b/tests/baselines/reference/ES5For-ofTypeCheck13.js @@ -0,0 +1,13 @@ +//// [ES5For-ofTypeCheck13.ts] +const strSet: Set = new Set() +strSet.add('Hello') +strSet.add('World') +for (const str of strSet) { } + +//// [ES5For-ofTypeCheck13.js] +var strSet = new Set(); +strSet.add('Hello'); +strSet.add('World'); +for (var _i = 0, strSet_1 = strSet; _i < strSet_1.length; _i++) { + var str = strSet_1[_i]; +} diff --git a/tests/baselines/reference/ES5For-ofTypeCheck13.symbols b/tests/baselines/reference/ES5For-ofTypeCheck13.symbols new file mode 100644 index 00000000000..14a1fe161a5 --- /dev/null +++ b/tests/baselines/reference/ES5For-ofTypeCheck13.symbols @@ -0,0 +1,20 @@ +=== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck13.ts === +const strSet: Set = new Set() +>strSet : Symbol(strSet, Decl(ES5For-ofTypeCheck13.ts, 0, 5)) +>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --)) +>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --)) + +strSet.add('Hello') +>strSet.add : Symbol(Set.add, Decl(lib.es2015.collection.d.ts, --, --)) +>strSet : Symbol(strSet, Decl(ES5For-ofTypeCheck13.ts, 0, 5)) +>add : Symbol(Set.add, Decl(lib.es2015.collection.d.ts, --, --)) + +strSet.add('World') +>strSet.add : Symbol(Set.add, Decl(lib.es2015.collection.d.ts, --, --)) +>strSet : Symbol(strSet, Decl(ES5For-ofTypeCheck13.ts, 0, 5)) +>add : Symbol(Set.add, Decl(lib.es2015.collection.d.ts, --, --)) + +for (const str of strSet) { } +>str : Symbol(str, Decl(ES5For-ofTypeCheck13.ts, 3, 10)) +>strSet : Symbol(strSet, Decl(ES5For-ofTypeCheck13.ts, 0, 5)) + diff --git a/tests/baselines/reference/ES5For-ofTypeCheck13.types b/tests/baselines/reference/ES5For-ofTypeCheck13.types new file mode 100644 index 00000000000..4812ae8d82c --- /dev/null +++ b/tests/baselines/reference/ES5For-ofTypeCheck13.types @@ -0,0 +1,25 @@ +=== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck13.ts === +const strSet: Set = new Set() +>strSet : Set +>Set : Set +>new Set() : Set +>Set : SetConstructor + +strSet.add('Hello') +>strSet.add('Hello') : Set +>strSet.add : (value: string) => Set +>strSet : Set +>add : (value: string) => Set +>'Hello' : "Hello" + +strSet.add('World') +>strSet.add('World') : Set +>strSet.add : (value: string) => Set +>strSet : Set +>add : (value: string) => Set +>'World' : "World" + +for (const str of strSet) { } +>str : any +>strSet : Set + diff --git a/tests/baselines/reference/ES5For-ofTypeCheck14.errors.txt b/tests/baselines/reference/ES5For-ofTypeCheck14.errors.txt new file mode 100644 index 00000000000..3a03491f110 --- /dev/null +++ b/tests/baselines/reference/ES5For-ofTypeCheck14.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts(2,17): error TS2568: Type 'Set' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators. + + +==== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts (1 errors) ==== + var union: string | Set + for (const e of union) { } + ~~~~~ +!!! error TS2568: Type 'Set' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators. \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-ofTypeCheck14.js b/tests/baselines/reference/ES5For-ofTypeCheck14.js new file mode 100644 index 00000000000..87e55c41a0e --- /dev/null +++ b/tests/baselines/reference/ES5For-ofTypeCheck14.js @@ -0,0 +1,9 @@ +//// [ES5For-ofTypeCheck14.ts] +var union: string | Set +for (const e of union) { } + +//// [ES5For-ofTypeCheck14.js] +var union; +for (var _i = 0, union_1 = union; _i < union_1.length; _i++) { + var e = union_1[_i]; +} diff --git a/tests/baselines/reference/ES5For-ofTypeCheck14.symbols b/tests/baselines/reference/ES5For-ofTypeCheck14.symbols new file mode 100644 index 00000000000..efa7d296d9d --- /dev/null +++ b/tests/baselines/reference/ES5For-ofTypeCheck14.symbols @@ -0,0 +1,9 @@ +=== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts === +var union: string | Set +>union : Symbol(union, Decl(ES5For-ofTypeCheck14.ts, 0, 3)) +>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --)) + +for (const e of union) { } +>e : Symbol(e, Decl(ES5For-ofTypeCheck14.ts, 1, 10)) +>union : Symbol(union, Decl(ES5For-ofTypeCheck14.ts, 0, 3)) + diff --git a/tests/baselines/reference/ES5For-ofTypeCheck14.types b/tests/baselines/reference/ES5For-ofTypeCheck14.types new file mode 100644 index 00000000000..03a822316ac --- /dev/null +++ b/tests/baselines/reference/ES5For-ofTypeCheck14.types @@ -0,0 +1,9 @@ +=== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts === +var union: string | Set +>union : string | Set +>Set : Set + +for (const e of union) { } +>e : string +>union : string | Set + diff --git a/tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck13.ts b/tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck13.ts new file mode 100644 index 00000000000..e6748b9373b --- /dev/null +++ b/tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck13.ts @@ -0,0 +1,6 @@ +//@target: ES5 +//@lib: ES6 +const strSet: Set = new Set() +strSet.add('Hello') +strSet.add('World') +for (const str of strSet) { } \ No newline at end of file diff --git a/tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts b/tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts new file mode 100644 index 00000000000..9474fcec5d9 --- /dev/null +++ b/tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts @@ -0,0 +1,4 @@ +//@target: ES5 +//@lib: ES6 +var union: string | Set +for (const e of union) { } \ No newline at end of file From e7a3d4b1923ebbb531a8a5ddaa3d85401369160d Mon Sep 17 00:00:00 2001 From: EcoleKeine Date: Wed, 14 Mar 2018 00:11:43 +0800 Subject: [PATCH 06/75] Some Constructor's signature missing null type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit according to ECMAScript® 2015 Language Specification - http://www.ecma-international.org/ecma-262/6.0 MapConstructor : 23.1.1.1 step6 WeakMapConstructor : 23.2.1.1 step6 SetConstructor : 23.3.1.1 step6 WeakSetConstructor : 23.4.1.1 step6 --- src/lib/es2015.collection.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/es2015.collection.d.ts b/src/lib/es2015.collection.d.ts index 74759107851..06a3473076f 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?: ReadonlyArray<[K, V]>): Map; + new (entries?: ReadonlyArray<[K, V]> | null): Map; readonly prototype: Map; } declare var Map: MapConstructor; @@ -31,7 +31,7 @@ interface WeakMap { interface WeakMapConstructor { new (): WeakMap; - new (entries?: ReadonlyArray<[K, V]>): WeakMap; + new (entries?: ReadonlyArray<[K, V]> | null): WeakMap; readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -47,7 +47,7 @@ interface Set { interface SetConstructor { new (): Set; - new (values?: ReadonlyArray): Set; + new (values?: ReadonlyArray | null): Set; readonly prototype: Set; } declare var Set: SetConstructor; @@ -66,7 +66,7 @@ interface WeakSet { interface WeakSetConstructor { new (): WeakSet; - new (values?: ReadonlyArray): WeakSet; + new (values?: ReadonlyArray | null): WeakSet; readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; From 66c690d40102c9a4b98d85b72ab4ac3467a19da4 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Sat, 10 Mar 2018 07:13:42 -0800 Subject: [PATCH 07/75] Better test to see when console clearing happens --- src/harness/unittests/tscWatchMode.ts | 74 +++++++++++++++-------- src/harness/virtualFileSystemWithWatch.ts | 9 +-- 2 files changed, 51 insertions(+), 32 deletions(-) diff --git a/src/harness/unittests/tscWatchMode.ts b/src/harness/unittests/tscWatchMode.ts index 47116cd5b01..b10c73d4a06 100644 --- a/src/harness/unittests/tscWatchMode.ts +++ b/src/harness/unittests/tscWatchMode.ts @@ -72,22 +72,31 @@ namespace ts.tscWatch { checkOutputDoesNotContain(host, expectedNonAffectedFiles); } + const elapsedRegex = /^Elapsed:: [0-9]+ms/; function checkOutputErrors( host: WatchedSystem, + logsBeforeWatchDiagnostic: string[] | undefined, preErrorsWatchDiagnostic: DiagnosticMessage | undefined, + logsBeforeErrors: string[] | undefined, errors: ReadonlyArray, + disableConsoleClears?: boolean | undefined, ...postErrorsWatchDiagnostics: DiagnosticMessage[] ) { + let screenClears = 0; const outputs = host.getOutput(); - const expectedOutputCount = (preErrorsWatchDiagnostic ? 1 : 0) + errors.length + postErrorsWatchDiagnostics.length; - assert.equal(outputs.length, expectedOutputCount); + const expectedOutputCount = (preErrorsWatchDiagnostic ? 1 : 0) + errors.length + postErrorsWatchDiagnostics.length + + (logsBeforeWatchDiagnostic ? logsBeforeWatchDiagnostic.length : 0) + (logsBeforeErrors ? logsBeforeErrors.length : 0); + assert.equal(outputs.length, expectedOutputCount, JSON.stringify(outputs)); let index = 0; + forEach(logsBeforeWatchDiagnostic, log => assertLog("logsBeforeWatchDiagnostic", log)); if (preErrorsWatchDiagnostic) { assertWatchDiagnostic(preErrorsWatchDiagnostic); } + forEach(logsBeforeErrors, log => assertLog("logBeforeError", log)); // Verify errors forEach(errors, assertDiagnostic); forEach(postErrorsWatchDiagnostics, assertWatchDiagnostic); + assert.equal(host.screenClears.length, screenClears, "Expected number of screen clears"); host.clearOutput(); function assertDiagnostic(diagnostic: Diagnostic) { @@ -96,8 +105,18 @@ namespace ts.tscWatch { index++; } + function assertLog(caption: string, expected: string) { + const actual = outputs[index]; + assert.equal(actual.replace(elapsedRegex, ""), expected.replace(elapsedRegex, ""), getOutputAtFailedMessage(caption, expected)); + index++; + } + function assertWatchDiagnostic(diagnosticMessage: DiagnosticMessage) { const expected = getWatchDiagnosticWithoutDate(diagnosticMessage); + if (!disableConsoleClears && diagnosticMessage.code !== Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + assert.equal(host.screenClears[screenClears], index, `Expected screen clear at this diagnostic: ${expected}`); + screenClears++; + } assert.isTrue(endsWith(outputs[index], expected), getOutputAtFailedMessage("Watch diagnostic", expected)); index++; } @@ -111,20 +130,20 @@ namespace ts.tscWatch { } } - function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray) { - checkOutputErrors(host, Diagnostics.Starting_compilation_in_watch_mode, errors, Diagnostics.Compilation_complete_Watching_for_file_changes); + function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + checkOutputErrors(host, logsBeforeWatchDiagnostic, Diagnostics.Starting_compilation_in_watch_mode, logsBeforeErrors, errors, disableConsoleClears, Diagnostics.Compilation_complete_Watching_for_file_changes); } function checkOutputErrorsInitialWithConfigErrors(host: WatchedSystem, errors: ReadonlyArray) { - checkOutputErrors(host, /*preErrorsWatchDiagnostic*/ undefined, errors, Diagnostics.Starting_compilation_in_watch_mode, Diagnostics.Compilation_complete_Watching_for_file_changes); + checkOutputErrors(host, /*logsBeforeWatchDiagnostic*/ undefined, /*preErrorsWatchDiagnostic*/ undefined, /*logsBeforeErrors*/ undefined, errors, /*disableConsoleClears*/ undefined, Diagnostics.Starting_compilation_in_watch_mode, Diagnostics.Compilation_complete_Watching_for_file_changes); } - function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray) { - checkOutputErrors(host, Diagnostics.File_change_detected_Starting_incremental_compilation, errors, Diagnostics.Compilation_complete_Watching_for_file_changes); + function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + checkOutputErrors(host, logsBeforeWatchDiagnostic, Diagnostics.File_change_detected_Starting_incremental_compilation, logsBeforeErrors, errors, disableConsoleClears, Diagnostics.Compilation_complete_Watching_for_file_changes); } function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray, expectedExitCode: ExitStatus) { - checkOutputErrors(host, Diagnostics.File_change_detected_Starting_incremental_compilation, errors); + checkOutputErrors(host, /*logsBeforeWatchDiagnostic*/ undefined, Diagnostics.File_change_detected_Starting_incremental_compilation, /*logsBeforeErrors*/ undefined, errors, /*disableConsoleClears*/ undefined); assert.equal(host.exitCode, expectedExitCode); } @@ -2161,30 +2180,33 @@ declare module "fs" { path: "f.ts", content: "" }; - const files = [file]; + const files = [file, libFile]; + const disableConsoleClear = options.diagnostics || options.extendedDiagnostics || options.preserveWatchOutput; const host = createWatchedSystem(files); - let clearCount: number | undefined; - checkConsoleClears(); - createWatchOfFilesAndCompilerOptions([file.path], host, options); - checkConsoleClears(); + checkOutputErrorsInitial(host, emptyArray, disableConsoleClear, options.extendedDiagnostics && [ + "Current directory: / CaseSensitiveFileNames: false\n" + ], options.extendedDiagnostics && [ + "Synchronizing program\n", + "CreatingProgramWith::\n", + " roots: [\"f.ts\"]\n", + " options: {\"extendedDiagnostics\":true}\n", + "FileWatcher:: Added:: WatchInfo: f.ts 250 \n", + "FileWatcher:: Added:: WatchInfo: /a/lib/lib.d.ts 250 \n" + ]); file.content = "//"; host.reloadFS(files); host.runQueuedTimeoutCallbacks(); - - checkConsoleClears(); - - function checkConsoleClears() { - if (clearCount === undefined || options.preserveWatchOutput) { - clearCount = 0; - } - else if (!options.diagnostics && !options.extendedDiagnostics) { - clearCount++; - } - host.checkScreenClears(clearCount); - return clearCount; - } + checkOutputErrorsIncremental(host, emptyArray, disableConsoleClear, options.extendedDiagnostics && [ + "FileWatcher:: Triggered with /f.ts1:: WatchInfo: f.ts 250 \n", + "Elapsed:: 0ms FileWatcher:: Triggered with /f.ts1:: WatchInfo: f.ts 250 \n" + ], options.extendedDiagnostics && [ + "Synchronizing program\n", + "CreatingProgramWith::\n", + " roots: [\"f.ts\"]\n", + " options: {\"extendedDiagnostics\":true}\n" + ]); } it("without --diagnostics or --extendedDiagnostics", () => { diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 8b62c210abb..e74eed39afe 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -288,7 +288,7 @@ interface Array {}` private toPath: (f: string) => Path; private timeoutCallbacks = new Callbacks(); private immediateCallbacks = new Callbacks(); - private screenClears = 0; + readonly screenClears: number[] = []; readonly watchedDirectories = createMultiMap(); readonly watchedDirectoriesRecursive = createMultiMap(); @@ -762,7 +762,7 @@ interface Array {}` } clearScreen(): void { - this.screenClears += 1; + this.screenClears.push(this.output.length); } checkTimeoutQueueLengthAndRun(expected: number) { @@ -802,10 +802,6 @@ interface Array {}` this.immediateCallbacks.unregister(timeoutId); } - checkScreenClears(expected: number): void { - assert.equal(this.screenClears, expected); - } - createDirectory(directoryName: string): void { const folder = this.toFolder(directoryName); @@ -839,6 +835,7 @@ interface Array {}` clearOutput() { clear(this.output); + this.screenClears.length = 0; } realpath(s: string): string { From 7329eb1ab1c007c947683e7b432725a912799f3a Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 15 Mar 2018 14:32:01 -0700 Subject: [PATCH 08/75] Make sure config file parsing errors are available through program Fixes #22570, #21940 --- src/compiler/builder.ts | 53 +++++++---- src/compiler/program.ts | 17 +++- src/compiler/tsc.ts | 11 +-- src/compiler/types.ts | 1 + src/compiler/watch.ts | 92 +++++++++++-------- src/harness/unittests/tscWatchMode.ts | 25 ++--- .../reference/api/tsserverlibrary.d.ts | 5 +- tests/baselines/reference/api/typescript.d.ts | 28 +++--- 8 files changed, 136 insertions(+), 96 deletions(-) diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index c2f816a4c71..cc506852252 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -218,29 +218,40 @@ namespace ts { newProgram: Program; host: BuilderProgramHost; oldProgram: BuilderProgram | undefined; + configFileParsingDiagnostics: ReadonlyArray; } - export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray, hostOrOptions: BuilderProgramHost | CompilerOptions, oldProgramOrHost?: CompilerHost | BuilderProgram, oldProgram?: BuilderProgram): BuilderCreationParameters { + export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderCreationParameters { let host: BuilderProgramHost; let newProgram: Program; - if (isArray(newProgramOrRootNames)) { - newProgram = createProgram(newProgramOrRootNames, hostOrOptions as CompilerOptions, oldProgramOrHost as CompilerHost, oldProgram && oldProgram.getProgram()); + let oldProgram: BuilderProgram; + if (newProgramOrRootNames === undefined) { + Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost as CompilerHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram as BuilderProgram; + Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram as BuilderProgram; + newProgram = createProgram(newProgramOrRootNames, hostOrOptions as CompilerOptions, oldProgramOrHost as CompilerHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); host = oldProgramOrHost as CompilerHost; } else { newProgram = newProgramOrRootNames; host = hostOrOptions as BuilderProgramHost; oldProgram = oldProgramOrHost as BuilderProgram; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram as ReadonlyArray; } - return { host, newProgram, oldProgram }; + return { host, newProgram, oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || emptyArray }; } export function createBuilderProgram(kind: BuilderProgramKind.SemanticDiagnosticsBuilderProgram, builderCreationParameters: BuilderCreationParameters): SemanticDiagnosticsBuilderProgram; export function createBuilderProgram(kind: BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, builderCreationParameters: BuilderCreationParameters): EmitAndSemanticDiagnosticsBuilderProgram; - export function createBuilderProgram(kind: BuilderProgramKind, { newProgram, host, oldProgram }: BuilderCreationParameters) { + export function createBuilderProgram(kind: BuilderProgramKind, { newProgram, host, oldProgram, configFileParsingDiagnostics }: BuilderCreationParameters) { // Return same program if underlying program doesnt change let oldState = oldProgram && oldProgram.getState(); - if (oldState && newProgram === oldState.program) { + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics !== newProgram.getConfigFileParsingDiagnostics()) { newProgram = undefined; oldState = undefined; return oldProgram; @@ -269,6 +280,7 @@ namespace ts { getSourceFiles: () => state.program.getSourceFiles(), getOptionsDiagnostics: cancellationToken => state.program.getOptionsDiagnostics(cancellationToken), getGlobalDiagnostics: cancellationToken => state.program.getGlobalDiagnostics(cancellationToken), + getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(), getSyntacticDiagnostics: (sourceFile, cancellationToken) => state.program.getSyntacticDiagnostics(sourceFile, cancellationToken), getSemanticDiagnostics, emit, @@ -471,6 +483,10 @@ namespace ts { * Get the diagnostics that dont belong to any file */ getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics from config file parsing + */ + getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Get the syntax diagnostics, for all source files if source file is not supplied */ @@ -533,29 +549,29 @@ namespace ts { /** * Create the builder to manage semantic diagnostics and cache them */ - export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray, hostOrOptions: BuilderProgramHost | CompilerOptions, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, oldProgram?: SemanticDiagnosticsBuilderProgram) { - return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray, hostOrOptions: BuilderProgramHost | CompilerOptions, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray) { + return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); } /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ - export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray, hostOrOptions: BuilderProgramHost | CompilerOptions, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram) { - return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray, hostOrOptions: BuilderProgramHost | CompilerOptions, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray) { + return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); } /** * Creates a builder thats just abstraction over program and can be used with watch */ - export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram): BuilderProgram; - export function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram): BuilderProgram; - export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray, hostOrOptions: BuilderProgramHost | CompilerOptions, oldProgramOrHost?: CompilerHost | BuilderProgram, oldProgram?: BuilderProgram): BuilderProgram { - const { newProgram: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram); + export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + export function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray, hostOrOptions: BuilderProgramHost | CompilerOptions, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram { + const { newProgram: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics); return { // Only return program, all other methods are not implemented getProgram: () => program, @@ -565,6 +581,7 @@ namespace ts { getSourceFiles: notImplemented, getOptionsDiagnostics: notImplemented, getGlobalDiagnostics: notImplemented, + getConfigFileParsingDiagnostics: notImplemented, getSyntacticDiagnostics: notImplemented, getSemanticDiagnostics: notImplemented, emit: notImplemented, diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 35772b2f040..d75c19b9f24 100755 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -198,6 +198,7 @@ namespace ts { export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] { const diagnostics = [ + ...program.getConfigFileParsingDiagnostics(), ...program.getOptionsDiagnostics(cancellationToken), ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), ...program.getGlobalDiagnostics(cancellationToken), @@ -454,6 +455,12 @@ namespace ts { } } + export function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray { + return configFileParseResult.options.configFile ? + configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + /** * Determined if source file needs to be re-created even if its text hasn't changed */ @@ -485,9 +492,10 @@ namespace ts { * @param options - The compiler options which should be used. * @param host - The host interacts with the underlying file system. * @param oldProgram - Reuses an old program structure. + * @param configFileParsingDiagnostics - error during config file parsing * @returns A 'Program' object. */ - export function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program { + export function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program { let program: Program; let files: SourceFile[] = []; let commonSourceDirectory: string; @@ -665,7 +673,8 @@ namespace ts { getSourceFileFromReference, sourceFileToPackageName, redirectTargetsSet, - isEmittedFile + isEmittedFile, + getConfigFileParsingDiagnostics }; verifyCompilerOptions(); @@ -1566,6 +1575,10 @@ namespace ts { return sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } + function getConfigFileParsingDiagnostics(): ReadonlyArray { + return configFileParsingDiagnostics || emptyArray; + } + function processRootFile(fileName: string, isDefaultLib: boolean) { processSourceFile(normalizePath(fileName), isDefaultLib, /*packageId*/ undefined); } diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 04725cebabe..09b64701988 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -117,7 +117,7 @@ namespace ts { createWatchOfConfigFile(configParseResult, commandLineOptions); } else { - performCompilation(configParseResult.fileNames, configParseResult.options); + performCompilation(configParseResult.fileNames, configParseResult.options, getConfigFileParsingDiagnostics(configParseResult)); } } else { @@ -139,11 +139,11 @@ namespace ts { } } - function performCompilation(rootFileNames: string[], compilerOptions: CompilerOptions) { + function performCompilation(rootFileNames: string[], compilerOptions: CompilerOptions, configFileParsingDiagnostics?: ReadonlyArray) { const compilerHost = createCompilerHost(compilerOptions); enableStatistics(compilerOptions); - const program = createProgram(rootFileNames, compilerOptions, compilerHost); + const program = createProgram(rootFileNames, compilerOptions, compilerHost, /*oldProgram*/ undefined, configFileParsingDiagnostics); const exitStatus = emitFilesAndReportErrors(program, reportDiagnostic, s => sys.write(s + sys.newLine)); reportStatistics(program); return sys.exit(exitStatus); @@ -169,10 +169,7 @@ namespace ts { function createWatchOfConfigFile(configParseResult: ParsedCommandLine, optionsToExtend: CompilerOptions) { const watchCompilerHost = createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); updateWatchCompilationHost(watchCompilerHost); - watchCompilerHost.rootFiles = configParseResult.fileNames; - watchCompilerHost.options = configParseResult.options; - watchCompilerHost.configFileSpecs = configParseResult.configFileSpecs; - watchCompilerHost.configFileWildCardDirectories = configParseResult.wildcardDirectories; + watchCompilerHost.configFileParsingResult = configParseResult; createWatchProgram(watchCompilerHost); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 2e7005d912e..461d94c9f2c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2662,6 +2662,7 @@ namespace ts { getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 2b9cc9cf694..ed5276e49a4 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -70,10 +70,8 @@ namespace ts { /** Parses config file using System interface */ export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, system: System, reportDiagnostic: DiagnosticReporter) { const host: ParseConfigFileHost = system; - host.onConfigFileDiagnostic = reportDiagnostic; host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(sys, reportDiagnostic, diagnostic); const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); - host.onConfigFileDiagnostic = undefined; host.onUnRecoverableConfigFileDiagnostic = undefined; return result; } @@ -98,13 +96,8 @@ namespace ts { } const result = parseJsonText(configFileName, configFileText); - result.parseDiagnostics.forEach(diagnostic => host.onConfigFileDiagnostic(diagnostic)); - const cwd = host.getCurrentDirectory(); - const configParseResult = parseJsonSourceFileConfigFileContent(result, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd)); - configParseResult.errors.forEach(diagnostic => host.onConfigFileDiagnostic(diagnostic)); - - return configParseResult; + return parseJsonSourceFileConfigFileContent(result, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd)); } /** @@ -118,6 +111,7 @@ namespace ts { getOptionsDiagnostics(): ReadonlyArray; getGlobalDiagnostics(): ReadonlyArray; getSemanticDiagnostics(): ReadonlyArray; + getConfigFileParsingDiagnostics(): ReadonlyArray; emit(): EmitResult; } @@ -126,16 +120,18 @@ namespace ts { */ export function emitFilesAndReportErrors(program: ProgramToEmitFilesAndReportErrors, reportDiagnostic: DiagnosticReporter, writeFileName?: (s: string) => void) { // First get and report any syntactic errors. - const diagnostics = program.getSyntacticDiagnostics().slice(); + const diagnostics = program.getConfigFileParsingDiagnostics().slice(); + const configFileParsingDiagnosticsLength = diagnostics.length; + addRange(diagnostics, program.getSyntacticDiagnostics()); let reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. - if (diagnostics.length === 0) { + if (diagnostics.length === configFileParsingDiagnosticsLength) { addRange(diagnostics, program.getOptionsDiagnostics()); addRange(diagnostics, program.getGlobalDiagnostics()); - if (diagnostics.length === 0) { + if (diagnostics.length === configFileParsingDiagnosticsLength) { reportSemanticDiagnostics = true; } } @@ -238,7 +234,6 @@ namespace ts { export function createWatchCompilerHostOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile { reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); const host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) as WatchCompilerHostOfConfigFile; - host.onConfigFileDiagnostic = reportDiagnostic; host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; @@ -259,7 +254,8 @@ namespace ts { namespace ts { export type DiagnosticReporter = (diagnostic: Diagnostic) => void; export type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; - export type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; + /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ + export type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; export interface WatchCompilerHost { /** * Used to create the program when need for program creation or recreation detected @@ -345,11 +341,6 @@ namespace ts { * Reports config file diagnostics */ export interface ConfigFileDiagnosticsReporter { - /** - * Reports the diagnostics in reading/writing or parsing of the config file - */ - onConfigFileDiagnostic: DiagnosticReporter; - /** * Reports unrecoverable error when parsing config file */ @@ -378,11 +369,8 @@ namespace ts { */ /*@internal*/ export interface WatchCompilerHostOfConfigFile extends WatchCompilerHost { - rootFiles?: string[]; - options?: CompilerOptions; optionsToExtend?: CompilerOptions; - configFileSpecs?: ConfigFileSpecs; - configFileWildCardDirectories?: MapLike; + configFileParsingResult?: ParsedCommandLine; } export interface Watch { @@ -460,7 +448,10 @@ namespace ts { const getCurrentDirectory = () => currentDirectory; const readFile: (path: string, encoding?: string) => string | undefined = (path, encoding) => host.readFile(path, encoding); const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, createProgram } = host; - let { rootFiles: rootFileNames, options: compilerOptions, configFileSpecs, configFileWildCardDirectories } = host; + let { rootFiles: rootFileNames, options: compilerOptions } = host; + let configFileSpecs: ConfigFileSpecs; + let configFileParsingDiagnostics: ReadonlyArray | undefined; + let hasChangedConfigFileParsingErrors = false; const cachedDirectoryStructureHost = configFileName && createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -473,13 +464,22 @@ namespace ts { fileExists: path => host.fileExists(path), readFile, getCurrentDirectory, - onConfigFileDiagnostic: host.onConfigFileDiagnostic, onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic }; // From tsc we want to get already parsed result and hence check for rootFileNames - if (configFileName && !rootFileNames) { - parseConfigFile(); + let newLine = updateNewLine(); + reportWatchDiagnostic(Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName) { + newLine = getNewLineCharacter(optionsToExtendForConfigFile, () => host.getNewLine()); + if (host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + } + else { + Debug.assert(!rootFileNames); + parseConfigFile(); + } + newLine = updateNewLine(); } const trace = host.trace && ((s: string) => { host.trace(s + newLine); }); @@ -489,7 +489,6 @@ namespace ts { const { watchFile, watchFilePath, watchDirectory: watchDirectoryWorker } = getWatchFactory(watchLogLevel, writeLog); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - let newLine = updateNewLine(); writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`); if (configFileName) { @@ -546,7 +545,6 @@ namespace ts { ((typeDirectiveNames, containingFile) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile)); const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; - reportWatchDiagnostic(Diagnostics.Starting_compilation_in_watch_mode); synchronizeProgram(); // Update the wild card directory watch @@ -578,6 +576,10 @@ namespace ts { // All resolutions are invalid if user provided resolutions const hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + hasChangedConfigFileParsingErrors = false; + } return builderProgram; } @@ -590,10 +592,11 @@ namespace ts { const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches @@ -630,7 +633,7 @@ namespace ts { } function updateNewLine() { - return getNewLineCharacter(compilerOptions, () => host.getNewLine()); + return getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, () => host.getNewLine()); } function toPath(fileName: string) { @@ -760,7 +763,7 @@ namespace ts { function reportWatchDiagnostic(message: DiagnosticMessage) { if (host.onWatchStatusChange) { - host.onWatchStatusChange(createCompilerDiagnostic(message), newLine, compilerOptions); + host.onWatchStatusChange(createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); } } @@ -801,8 +804,13 @@ namespace ts { function reloadFileNamesFromConfigFile() { const result = getFileNamesFromConfigSpecs(configFileSpecs, getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { - host.onConfigFileDiagnostic(getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (result.fileNames.length) { + configFileParsingDiagnostics = filter(configFileParsingDiagnostics, error => !isErrorNoInputFiles(error)); + hasChangedConfigFileParsingErrors = true; + } + else if (!configFileSpecs.filesSpecs && !some(configFileParsingDiagnostics, isErrorNoInputFiles)) { + configFileParsingDiagnostics = configFileParsingDiagnostics!.concat(getErrorForNoInputFiles(configFileSpecs, configFileName)); + hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -826,11 +834,15 @@ namespace ts { } function parseConfigFile() { - const configParseResult = getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); - rootFileNames = configParseResult.fileNames; - compilerOptions = configParseResult.options; - configFileSpecs = configParseResult.configFileSpecs; - configFileWildCardDirectories = configParseResult.wildcardDirectories; + setConfigFileParsingResult(getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); + } + + function setConfigFileParsingResult(configFileParseResult: ParsedCommandLine) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; + configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult); + hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName: string, eventKind: FileWatcherEventKind, path: Path) { @@ -876,10 +888,10 @@ namespace ts { } function watchConfigFileWildCardDirectories() { - if (configFileWildCardDirectories) { + if (configFileSpecs) { updateWatchingWildcardDirectories( watchedWildcardDirectories || (watchedWildcardDirectories = createMap()), - createMapFromTemplate(configFileWildCardDirectories), + createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory ); } diff --git a/src/harness/unittests/tscWatchMode.ts b/src/harness/unittests/tscWatchMode.ts index b10c73d4a06..bcc65f8bdd1 100644 --- a/src/harness/unittests/tscWatchMode.ts +++ b/src/harness/unittests/tscWatchMode.ts @@ -76,7 +76,7 @@ namespace ts.tscWatch { function checkOutputErrors( host: WatchedSystem, logsBeforeWatchDiagnostic: string[] | undefined, - preErrorsWatchDiagnostic: DiagnosticMessage | undefined, + preErrorsWatchDiagnostic: DiagnosticMessage, logsBeforeErrors: string[] | undefined, errors: ReadonlyArray, disableConsoleClears?: boolean | undefined, @@ -84,14 +84,12 @@ namespace ts.tscWatch { ) { let screenClears = 0; const outputs = host.getOutput(); - const expectedOutputCount = (preErrorsWatchDiagnostic ? 1 : 0) + errors.length + postErrorsWatchDiagnostics.length + + const expectedOutputCount = 1 + errors.length + postErrorsWatchDiagnostics.length + (logsBeforeWatchDiagnostic ? logsBeforeWatchDiagnostic.length : 0) + (logsBeforeErrors ? logsBeforeErrors.length : 0); assert.equal(outputs.length, expectedOutputCount, JSON.stringify(outputs)); let index = 0; forEach(logsBeforeWatchDiagnostic, log => assertLog("logsBeforeWatchDiagnostic", log)); - if (preErrorsWatchDiagnostic) { - assertWatchDiagnostic(preErrorsWatchDiagnostic); - } + assertWatchDiagnostic(preErrorsWatchDiagnostic); forEach(logsBeforeErrors, log => assertLog("logBeforeError", log)); // Verify errors forEach(errors, assertDiagnostic); @@ -130,20 +128,16 @@ namespace ts.tscWatch { } } - function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { - checkOutputErrors(host, logsBeforeWatchDiagnostic, Diagnostics.Starting_compilation_in_watch_mode, logsBeforeErrors, errors, disableConsoleClears, Diagnostics.Compilation_complete_Watching_for_file_changes); - } - - function checkOutputErrorsInitialWithConfigErrors(host: WatchedSystem, errors: ReadonlyArray) { - checkOutputErrors(host, /*logsBeforeWatchDiagnostic*/ undefined, /*preErrorsWatchDiagnostic*/ undefined, /*logsBeforeErrors*/ undefined, errors, /*disableConsoleClears*/ undefined, Diagnostics.Starting_compilation_in_watch_mode, Diagnostics.Compilation_complete_Watching_for_file_changes); + function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { + checkOutputErrors(host, /*logsBeforeWatchDiagnostic*/ undefined, Diagnostics.Starting_compilation_in_watch_mode, logsBeforeErrors, errors, disableConsoleClears, Diagnostics.Compilation_complete_Watching_for_file_changes); } function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors(host, logsBeforeWatchDiagnostic, Diagnostics.File_change_detected_Starting_incremental_compilation, logsBeforeErrors, errors, disableConsoleClears, Diagnostics.Compilation_complete_Watching_for_file_changes); } - function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray, expectedExitCode: ExitStatus) { - checkOutputErrors(host, /*logsBeforeWatchDiagnostic*/ undefined, Diagnostics.File_change_detected_Starting_incremental_compilation, /*logsBeforeErrors*/ undefined, errors, /*disableConsoleClears*/ undefined); + function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + checkOutputErrors(host, logsBeforeWatchDiagnostic, Diagnostics.File_change_detected_Starting_incremental_compilation, logsBeforeErrors, errors, disableConsoleClears); assert.equal(host.exitCode, expectedExitCode); } @@ -916,7 +910,7 @@ namespace ts.tscWatch { const host = createWatchedSystem([file, configFile, libFile]); const watch = createWatchOfConfigFile(configFile.path, host); - checkOutputErrorsInitialWithConfigErrors(host, [ + checkOutputErrorsInitial(host, [ getUnknownCompilerOption(watch(), configFile, "foo"), getUnknownCompilerOption(watch(), configFile, "allowJS") ]); @@ -2185,8 +2179,7 @@ declare module "fs" { const host = createWatchedSystem(files); createWatchOfFilesAndCompilerOptions([file.path], host, options); checkOutputErrorsInitial(host, emptyArray, disableConsoleClear, options.extendedDiagnostics && [ - "Current directory: / CaseSensitiveFileNames: false\n" - ], options.extendedDiagnostics && [ + "Current directory: / CaseSensitiveFileNames: false\n", "Synchronizing program\n", "CreatingProgramWith::\n", " roots: [\"f.ts\"]\n", diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 8b9e078716c..faaa2759d5c 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1685,6 +1685,7 @@ declare namespace ts { getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. */ @@ -3917,6 +3918,7 @@ declare namespace ts { function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' * that represent a compilation unit. @@ -3928,9 +3930,10 @@ declare namespace ts { * @param options - The compiler options which should be used. * @param host - The host interacts with the underlying file system. * @param oldProgram - Reuses an old program structure. + * @param configFileParsingDiagnostics - error during config file parsing * @returns A 'Program' object. */ - function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; } declare namespace ts { interface Node { diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 87204f489d8..d9bfbc13a40 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1685,6 +1685,7 @@ declare namespace ts { getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. */ @@ -3864,6 +3865,7 @@ declare namespace ts { function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' * that represent a compilation unit. @@ -3875,9 +3877,10 @@ declare namespace ts { * @param options - The compiler options which should be used. * @param host - The host interacts with the underlying file system. * @param oldProgram - Reuses an old program structure. + * @param configFileParsingDiagnostics - error during config file parsing * @returns A 'Program' object. */ - function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; } declare namespace ts { interface EmitOutput { @@ -3938,6 +3941,10 @@ declare namespace ts { * Get the diagnostics that dont belong to any file */ getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics from config file parsing + */ + getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Get the syntax diagnostics, for all source files if source file is not supplied */ @@ -3997,24 +4004,25 @@ declare namespace ts { /** * Create the builder to manage semantic diagnostics and cache them */ - function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ - function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram): BuilderProgram; + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } declare namespace ts { type DiagnosticReporter = (diagnostic: Diagnostic) => void; type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; - type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; + /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; interface WatchCompilerHost { /** * Used to create the program when need for program creation or recreation detected @@ -4078,10 +4086,6 @@ declare namespace ts { * Reports config file diagnostics */ interface ConfigFileDiagnosticsReporter { - /** - * Reports the diagnostics in reading/writing or parsing of the config file - */ - onConfigFileDiagnostic: DiagnosticReporter; /** * Reports unrecoverable error when parsing config file */ From 9b7e5e212fc80b2812dbc98e718bc18fb7b51ec9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Tue, 27 Mar 2018 17:37:19 +0800 Subject: [PATCH 09/75] fix type lookup rule --- src/compiler/checker.ts | 2 +- .../reference/functionReturnTypeQuery.js | 7 +++++++ .../reference/functionReturnTypeQuery.symbols | 19 +++++++++++++++++++ .../reference/functionReturnTypeQuery.types | 19 +++++++++++++++++++ .../reference/typeGuardFunctionErrors.symbols | 3 +++ .../reference/typeGuardFunctionErrors.types | 6 +++--- .../cases/compiler/functionReturnTypeQuery.ts | 4 ++++ 7 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 tests/baselines/reference/functionReturnTypeQuery.js create mode 100644 tests/baselines/reference/functionReturnTypeQuery.symbols create mode 100644 tests/baselines/reference/functionReturnTypeQuery.types create mode 100644 tests/cases/compiler/functionReturnTypeQuery.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5bf1f022869..b9cddb0a4e9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1234,7 +1234,7 @@ namespace ts { lastLocation.kind === SyntaxKind.Parameter || ( lastLocation === (location).type && - result.valueDeclaration.kind === SyntaxKind.Parameter + !!findAncestor(result.valueDeclaration, isParameter) ); } } diff --git a/tests/baselines/reference/functionReturnTypeQuery.js b/tests/baselines/reference/functionReturnTypeQuery.js new file mode 100644 index 00000000000..ee87f2bae21 --- /dev/null +++ b/tests/baselines/reference/functionReturnTypeQuery.js @@ -0,0 +1,7 @@ +//// [functionReturnTypeQuery.ts] +declare let foo: number; + +declare function test1(foo: string, bar: typeof foo): typeof foo; +declare function test2({foo}: {foo: string}, bar: typeof foo): typeof foo; + +//// [functionReturnTypeQuery.js] diff --git a/tests/baselines/reference/functionReturnTypeQuery.symbols b/tests/baselines/reference/functionReturnTypeQuery.symbols new file mode 100644 index 00000000000..1e439d6364b --- /dev/null +++ b/tests/baselines/reference/functionReturnTypeQuery.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/functionReturnTypeQuery.ts === +declare let foo: number; +>foo : Symbol(foo, Decl(functionReturnTypeQuery.ts, 0, 11)) + +declare function test1(foo: string, bar: typeof foo): typeof foo; +>test1 : Symbol(test1, Decl(functionReturnTypeQuery.ts, 0, 24)) +>foo : Symbol(foo, Decl(functionReturnTypeQuery.ts, 2, 23)) +>bar : Symbol(bar, Decl(functionReturnTypeQuery.ts, 2, 35)) +>foo : Symbol(foo, Decl(functionReturnTypeQuery.ts, 2, 23)) +>foo : Symbol(foo, Decl(functionReturnTypeQuery.ts, 2, 23)) + +declare function test2({foo}: {foo: string}, bar: typeof foo): typeof foo; +>test2 : Symbol(test2, Decl(functionReturnTypeQuery.ts, 2, 65)) +>foo : Symbol(foo, Decl(functionReturnTypeQuery.ts, 3, 24)) +>foo : Symbol(foo, Decl(functionReturnTypeQuery.ts, 3, 31)) +>bar : Symbol(bar, Decl(functionReturnTypeQuery.ts, 3, 44)) +>foo : Symbol(foo, Decl(functionReturnTypeQuery.ts, 3, 24)) +>foo : Symbol(foo, Decl(functionReturnTypeQuery.ts, 3, 24)) + diff --git a/tests/baselines/reference/functionReturnTypeQuery.types b/tests/baselines/reference/functionReturnTypeQuery.types new file mode 100644 index 00000000000..ac8a1df3894 --- /dev/null +++ b/tests/baselines/reference/functionReturnTypeQuery.types @@ -0,0 +1,19 @@ +=== tests/cases/compiler/functionReturnTypeQuery.ts === +declare let foo: number; +>foo : number + +declare function test1(foo: string, bar: typeof foo): typeof foo; +>test1 : (foo: string, bar: string) => string +>foo : string +>bar : string +>foo : string +>foo : string + +declare function test2({foo}: {foo: string}, bar: typeof foo): typeof foo; +>test2 : ({ foo }: { foo: string; }, bar: string) => string +>foo : string +>foo : string +>bar : string +>foo : string +>foo : string + diff --git a/tests/baselines/reference/typeGuardFunctionErrors.symbols b/tests/baselines/reference/typeGuardFunctionErrors.symbols index 841e986a95d..b51e84c754f 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.symbols +++ b/tests/baselines/reference/typeGuardFunctionErrors.symbols @@ -312,6 +312,7 @@ function b5({a, b, p1}, p2, p3): p1 is A { >p1 : Symbol(p1, Decl(typeGuardFunctionErrors.ts, 127, 18)) >p2 : Symbol(p2, Decl(typeGuardFunctionErrors.ts, 127, 23)) >p3 : Symbol(p3, Decl(typeGuardFunctionErrors.ts, 127, 27)) +>p1 : Symbol(p1, Decl(typeGuardFunctionErrors.ts, 127, 18)) >A : Symbol(A, Decl(typeGuardFunctionErrors.ts, 0, 0)) return true; @@ -324,6 +325,7 @@ function b6([a, b, p1], p2, p3): p1 is A { >p1 : Symbol(p1, Decl(typeGuardFunctionErrors.ts, 131, 18)) >p2 : Symbol(p2, Decl(typeGuardFunctionErrors.ts, 131, 23)) >p3 : Symbol(p3, Decl(typeGuardFunctionErrors.ts, 131, 27)) +>p1 : Symbol(p1, Decl(typeGuardFunctionErrors.ts, 131, 18)) >A : Symbol(A, Decl(typeGuardFunctionErrors.ts, 0, 0)) return true; @@ -337,6 +339,7 @@ function b7({a, b, c: {p1}}, p2, p3): p1 is A { >p1 : Symbol(p1, Decl(typeGuardFunctionErrors.ts, 135, 23)) >p2 : Symbol(p2, Decl(typeGuardFunctionErrors.ts, 135, 28)) >p3 : Symbol(p3, Decl(typeGuardFunctionErrors.ts, 135, 32)) +>p1 : Symbol(p1, Decl(typeGuardFunctionErrors.ts, 135, 23)) >A : Symbol(A, Decl(typeGuardFunctionErrors.ts, 0, 0)) return true; diff --git a/tests/baselines/reference/typeGuardFunctionErrors.types b/tests/baselines/reference/typeGuardFunctionErrors.types index 96d441d8b8d..472e81bae00 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.types +++ b/tests/baselines/reference/typeGuardFunctionErrors.types @@ -356,7 +356,7 @@ function b5({a, b, p1}, p2, p3): p1 is A { >p1 : any >p2 : any >p3 : any ->p1 : No type information available! +>p1 : any >A : A return true; @@ -370,7 +370,7 @@ function b6([a, b, p1], p2, p3): p1 is A { >p1 : any >p2 : any >p3 : any ->p1 : No type information available! +>p1 : any >A : A return true; @@ -385,7 +385,7 @@ function b7({a, b, c: {p1}}, p2, p3): p1 is A { >p1 : any >p2 : any >p3 : any ->p1 : No type information available! +>p1 : any >A : A return true; diff --git a/tests/cases/compiler/functionReturnTypeQuery.ts b/tests/cases/compiler/functionReturnTypeQuery.ts new file mode 100644 index 00000000000..2d644a2cc3d --- /dev/null +++ b/tests/cases/compiler/functionReturnTypeQuery.ts @@ -0,0 +1,4 @@ +declare let foo: number; + +declare function test1(foo: string, bar: typeof foo): typeof foo; +declare function test2({foo}: {foo: string}, bar: typeof foo): typeof foo; \ No newline at end of file From 4fa96056eaf038fa0796c2acb6631f3344603a1c Mon Sep 17 00:00:00 2001 From: Kevin Donnelly Date: Tue, 27 Mar 2018 09:45:25 -0500 Subject: [PATCH 10/75] Make T[never] = never instead of erroring or being any (#22787) * Add tests showing existing behavior for indexing types with never. * Make T[never] = never instead of erroring or being any. And update the baselines for the tests for this change. * Add test case for indexing an expression with never showing existing behavior. * Make indexing an object with never expression result in never. And update baseline to reflect new behavior. --- src/compiler/checker.ts | 3 + .../reference/indexingTypesWithNever.js | 121 ++++++ .../reference/indexingTypesWithNever.symbols | 389 +++++++++++++++++ .../reference/indexingTypesWithNever.types | 404 ++++++++++++++++++ .../cases/compiler/indexingTypesWithNever.ts | 111 +++++ 5 files changed, 1028 insertions(+) create mode 100644 tests/baselines/reference/indexingTypesWithNever.js create mode 100644 tests/baselines/reference/indexingTypesWithNever.symbols create mode 100644 tests/baselines/reference/indexingTypesWithNever.types create mode 100644 tests/cases/compiler/indexingTypesWithNever.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5bf1f022869..cc17e30e0e0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8151,6 +8151,9 @@ namespace ts { } return indexInfo.type; } + if (indexType.flags & TypeFlags.Never) { + return neverType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (getIndexTypeOfType(objectType, IndexKind.Number)) { diff --git a/tests/baselines/reference/indexingTypesWithNever.js b/tests/baselines/reference/indexingTypesWithNever.js new file mode 100644 index 00000000000..4e174fc4c9d --- /dev/null +++ b/tests/baselines/reference/indexingTypesWithNever.js @@ -0,0 +1,121 @@ +//// [indexingTypesWithNever.ts] +type TestObj = { + a: string; + b: number; +}; + +// Should be never but without an error +type Result1 = TestObj[never]; + +type EmptyObj = {}; + +// Should be never but without an error +type Result2 = EmptyObj[keyof EmptyObj]; + +declare function genericFn1(obj: T): T[never]; + +// Should be never +const result3 = genericFn1({ c: "ctest", d: "dtest" }); + +declare function genericFn2( + obj: T +): T[never]; + +// Should be never +const result4 = genericFn2({ e: "etest", f: "ftest" }); + +declare function genericFn3< + T extends { [K in keyof T]: T[K] }, + U extends keyof T, + V extends keyof T +>(obj: T, u: U, v: V): T[U & V]; + +// Should be never +const result5 = genericFn3({ g: "gtest", h: "htest" }, "g", "h"); // 'g' & 'h' will reduce to never + + +declare const obj: {a: string, b: number} +declare const key: never + +const result6 = obj[key] + +// Expanded examples from https://github.com/Microsoft/TypeScript/issues/21988 +type RequiredPropNames = { + [P in keyof T]-?: undefined extends T[P] ? never : P +}[keyof T]; + +type OptionalPropNames = { + [P in keyof T]-?: undefined extends T[P] ? P : never +}[keyof T]; + +type RequiredProps = { [P in RequiredPropNames]: T[P] }; +type OptionalProps = { [P in OptionalPropNames]?: T[P] }; + +type Match = [Exp] extends [Act] + ? ([Act] extends [Exp] ? "Match" : "Did not match 2") + : "Did not match 1"; + +type ExpectType = Match extends "Match" + ? ({} extends Exp ? Match, Required> : "Match") + : "Did not match"; + +type P3 = { a: string; b: number; c?: boolean }; +type P2 = { a: string; c?: boolean }; +type P1 = { c?: boolean }; +type P0 = {}; + +type P3Names = RequiredPropNames; // expect 'a' | 'b' +type P2Names = RequiredPropNames; // expect 'a' +type P1Names = RequiredPropNames; // expect never +type P0Names = RequiredPropNames; // expect never + +declare const p3NameTest: ExpectType<"a" | "b", P3Names>; +declare const p2NameTest: ExpectType<"a", P2Names>; +declare const p1NameTest: ExpectType; +declare const p0NameTest: ExpectType; + +type P3Props = RequiredProps; // expect { a: string; b: number } +type P2Props = RequiredProps; // expect { a: string; } +type P1Props = RequiredProps; // expect {} +type P0Props = RequiredProps; // expect {} + +declare const p3Test: ExpectType<{ a: string; b: number }, P3Props>; +declare const p2Test: ExpectType<{ a: string }, P2Props>; +declare const p1Test: ExpectType<{}, P1Props>; +declare const p0Test: ExpectType<{}, P0Props>; + +type O3 = { a?: string; b?: number; c: boolean }; +type O2 = { a?: string; c: boolean }; +type O1 = { c: boolean }; +type O0 = {}; + +type O3Names = OptionalPropNames; // expect 'a' | 'b' +type O2Names = OptionalPropNames; // expect 'a' +type O1Names = OptionalPropNames; // expect never +type O0Names = OptionalPropNames; // expect never + +declare const o3NameTest: ExpectType<"a" | "b", O3Names>; +declare const o2NameTest: ExpectType<"a", O2Names>; +declare const o1NameTest: ExpectType; +declare const o0NameTest: ExpectType; + +type O3Props = OptionalProps; // expect { a?: string | undefined; b?: number | undefined } +type O2Props = OptionalProps; // expect { a?: string | undefined; } +type O1Props = OptionalProps; // expect {} +type O0Props = OptionalProps; // expect {} + +declare const o3Test: ExpectType<{ a?: string; b?: number }, O3Props>; +declare const o2Test: ExpectType<{ a?: string }, O2Props>; +declare const o1Test: ExpectType<{}, O1Props>; +declare const o0Test: ExpectType<{}, O0Props>; + + +//// [indexingTypesWithNever.js] +"use strict"; +// Should be never +var result3 = genericFn1({ c: "ctest", d: "dtest" }); +// Should be never +var result4 = genericFn2({ e: "etest", f: "ftest" }); +// Should be never +var result5 = genericFn3({ g: "gtest", h: "htest" }, "g", "h"); // 'g' & 'h' will reduce to never +var result6 = obj[key]; diff --git a/tests/baselines/reference/indexingTypesWithNever.symbols b/tests/baselines/reference/indexingTypesWithNever.symbols new file mode 100644 index 00000000000..2b163d74a02 --- /dev/null +++ b/tests/baselines/reference/indexingTypesWithNever.symbols @@ -0,0 +1,389 @@ +=== tests/cases/compiler/indexingTypesWithNever.ts === +type TestObj = { +>TestObj : Symbol(TestObj, Decl(indexingTypesWithNever.ts, 0, 0)) + + a: string; +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 0, 16)) + + b: number; +>b : Symbol(b, Decl(indexingTypesWithNever.ts, 1, 12)) + +}; + +// Should be never but without an error +type Result1 = TestObj[never]; +>Result1 : Symbol(Result1, Decl(indexingTypesWithNever.ts, 3, 2)) +>TestObj : Symbol(TestObj, Decl(indexingTypesWithNever.ts, 0, 0)) + +type EmptyObj = {}; +>EmptyObj : Symbol(EmptyObj, Decl(indexingTypesWithNever.ts, 6, 30)) + +// Should be never but without an error +type Result2 = EmptyObj[keyof EmptyObj]; +>Result2 : Symbol(Result2, Decl(indexingTypesWithNever.ts, 8, 19)) +>EmptyObj : Symbol(EmptyObj, Decl(indexingTypesWithNever.ts, 6, 30)) +>EmptyObj : Symbol(EmptyObj, Decl(indexingTypesWithNever.ts, 6, 30)) + +declare function genericFn1(obj: T): T[never]; +>genericFn1 : Symbol(genericFn1, Decl(indexingTypesWithNever.ts, 11, 40)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 13, 28)) +>obj : Symbol(obj, Decl(indexingTypesWithNever.ts, 13, 31)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 13, 28)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 13, 28)) + +// Should be never +const result3 = genericFn1({ c: "ctest", d: "dtest" }); +>result3 : Symbol(result3, Decl(indexingTypesWithNever.ts, 16, 5)) +>genericFn1 : Symbol(genericFn1, Decl(indexingTypesWithNever.ts, 11, 40)) +>c : Symbol(c, Decl(indexingTypesWithNever.ts, 16, 28)) +>d : Symbol(d, Decl(indexingTypesWithNever.ts, 16, 40)) + +declare function genericFn2( +>genericFn2 : Symbol(genericFn2, Decl(indexingTypesWithNever.ts, 16, 55)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 18, 28)) +>ind : Symbol(ind, Decl(indexingTypesWithNever.ts, 18, 41)) + + obj: T +>obj : Symbol(obj, Decl(indexingTypesWithNever.ts, 18, 65)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 18, 28)) + +): T[never]; +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 18, 28)) + +// Should be never +const result4 = genericFn2({ e: "etest", f: "ftest" }); +>result4 : Symbol(result4, Decl(indexingTypesWithNever.ts, 23, 5)) +>genericFn2 : Symbol(genericFn2, Decl(indexingTypesWithNever.ts, 16, 55)) +>e : Symbol(e, Decl(indexingTypesWithNever.ts, 23, 28)) +>f : Symbol(f, Decl(indexingTypesWithNever.ts, 23, 40)) + +declare function genericFn3< +>genericFn3 : Symbol(genericFn3, Decl(indexingTypesWithNever.ts, 23, 55)) + + T extends { [K in keyof T]: T[K] }, +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 25, 28)) +>K : Symbol(K, Decl(indexingTypesWithNever.ts, 26, 15)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 25, 28)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 25, 28)) +>K : Symbol(K, Decl(indexingTypesWithNever.ts, 26, 15)) + + U extends keyof T, +>U : Symbol(U, Decl(indexingTypesWithNever.ts, 26, 37)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 25, 28)) + + V extends keyof T +>V : Symbol(V, Decl(indexingTypesWithNever.ts, 27, 20)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 25, 28)) + +>(obj: T, u: U, v: V): T[U & V]; +>obj : Symbol(obj, Decl(indexingTypesWithNever.ts, 29, 2)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 25, 28)) +>u : Symbol(u, Decl(indexingTypesWithNever.ts, 29, 9)) +>U : Symbol(U, Decl(indexingTypesWithNever.ts, 26, 37)) +>v : Symbol(v, Decl(indexingTypesWithNever.ts, 29, 15)) +>V : Symbol(V, Decl(indexingTypesWithNever.ts, 27, 20)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 25, 28)) +>U : Symbol(U, Decl(indexingTypesWithNever.ts, 26, 37)) +>V : Symbol(V, Decl(indexingTypesWithNever.ts, 27, 20)) + +// Should be never +const result5 = genericFn3({ g: "gtest", h: "htest" }, "g", "h"); // 'g' & 'h' will reduce to never +>result5 : Symbol(result5, Decl(indexingTypesWithNever.ts, 32, 5)) +>genericFn3 : Symbol(genericFn3, Decl(indexingTypesWithNever.ts, 23, 55)) +>g : Symbol(g, Decl(indexingTypesWithNever.ts, 32, 28)) +>h : Symbol(h, Decl(indexingTypesWithNever.ts, 32, 40)) + + +declare const obj: {a: string, b: number} +>obj : Symbol(obj, Decl(indexingTypesWithNever.ts, 35, 13)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 35, 20)) +>b : Symbol(b, Decl(indexingTypesWithNever.ts, 35, 30)) + +declare const key: never +>key : Symbol(key, Decl(indexingTypesWithNever.ts, 36, 13)) + +const result6 = obj[key] +>result6 : Symbol(result6, Decl(indexingTypesWithNever.ts, 38, 5)) +>obj : Symbol(obj, Decl(indexingTypesWithNever.ts, 35, 13)) +>key : Symbol(key, Decl(indexingTypesWithNever.ts, 36, 13)) + +// Expanded examples from https://github.com/Microsoft/TypeScript/issues/21988 +type RequiredPropNames = { +>RequiredPropNames : Symbol(RequiredPropNames, Decl(indexingTypesWithNever.ts, 38, 24)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 41, 23)) + + [P in keyof T]-?: undefined extends T[P] ? never : P +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 42, 3)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 41, 23)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 41, 23)) +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 42, 3)) +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 42, 3)) + +}[keyof T]; +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 41, 23)) + +type OptionalPropNames = { +>OptionalPropNames : Symbol(OptionalPropNames, Decl(indexingTypesWithNever.ts, 43, 11)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 45, 23)) + + [P in keyof T]-?: undefined extends T[P] ? P : never +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 46, 3)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 45, 23)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 45, 23)) +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 46, 3)) +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 46, 3)) + +}[keyof T]; +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 45, 23)) + +type RequiredProps = { [P in RequiredPropNames]: T[P] }; +>RequiredProps : Symbol(RequiredProps, Decl(indexingTypesWithNever.ts, 47, 11)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 49, 19)) +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 49, 27)) +>RequiredPropNames : Symbol(RequiredPropNames, Decl(indexingTypesWithNever.ts, 38, 24)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 49, 19)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 49, 19)) +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 49, 27)) + +type OptionalProps = { [P in OptionalPropNames]?: T[P] }; +>OptionalProps : Symbol(OptionalProps, Decl(indexingTypesWithNever.ts, 49, 62)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 50, 19)) +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 50, 27)) +>OptionalPropNames : Symbol(OptionalPropNames, Decl(indexingTypesWithNever.ts, 43, 11)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 50, 19)) +>T : Symbol(T, Decl(indexingTypesWithNever.ts, 50, 19)) +>P : Symbol(P, Decl(indexingTypesWithNever.ts, 50, 27)) + +type Match = [Exp] extends [Act] +>Match : Symbol(Match, Decl(indexingTypesWithNever.ts, 50, 63)) +>Exp : Symbol(Exp, Decl(indexingTypesWithNever.ts, 52, 11)) +>Act : Symbol(Act, Decl(indexingTypesWithNever.ts, 52, 15)) +>Exp : Symbol(Exp, Decl(indexingTypesWithNever.ts, 52, 11)) +>Act : Symbol(Act, Decl(indexingTypesWithNever.ts, 52, 15)) + + ? ([Act] extends [Exp] ? "Match" : "Did not match 2") +>Act : Symbol(Act, Decl(indexingTypesWithNever.ts, 52, 15)) +>Exp : Symbol(Exp, Decl(indexingTypesWithNever.ts, 52, 11)) + + : "Did not match 1"; + +type ExpectType = Match extends "Match" +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>Exp : Symbol(Exp, Decl(indexingTypesWithNever.ts, 56, 16)) +>Act : Symbol(Act, Decl(indexingTypesWithNever.ts, 56, 20)) +>Match : Symbol(Match, Decl(indexingTypesWithNever.ts, 50, 63)) +>Exp : Symbol(Exp, Decl(indexingTypesWithNever.ts, 56, 16)) +>Act : Symbol(Act, Decl(indexingTypesWithNever.ts, 56, 20)) + + ? ({} extends Exp ? Match, Required> : "Match") +>Exp : Symbol(Exp, Decl(indexingTypesWithNever.ts, 56, 16)) +>Match : Symbol(Match, Decl(indexingTypesWithNever.ts, 50, 63)) +>Required : Symbol(Required, Decl(lib.d.ts, --, --)) +>Exp : Symbol(Exp, Decl(indexingTypesWithNever.ts, 56, 16)) +>Required : Symbol(Required, Decl(lib.d.ts, --, --)) +>Act : Symbol(Act, Decl(indexingTypesWithNever.ts, 56, 20)) + + : "Did not match"; + +type P3 = { a: string; b: number; c?: boolean }; +>P3 : Symbol(P3, Decl(indexingTypesWithNever.ts, 58, 20)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 60, 11)) +>b : Symbol(b, Decl(indexingTypesWithNever.ts, 60, 22)) +>c : Symbol(c, Decl(indexingTypesWithNever.ts, 60, 33)) + +type P2 = { a: string; c?: boolean }; +>P2 : Symbol(P2, Decl(indexingTypesWithNever.ts, 60, 48)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 61, 11)) +>c : Symbol(c, Decl(indexingTypesWithNever.ts, 61, 22)) + +type P1 = { c?: boolean }; +>P1 : Symbol(P1, Decl(indexingTypesWithNever.ts, 61, 37)) +>c : Symbol(c, Decl(indexingTypesWithNever.ts, 62, 11)) + +type P0 = {}; +>P0 : Symbol(P0, Decl(indexingTypesWithNever.ts, 62, 26)) + +type P3Names = RequiredPropNames; // expect 'a' | 'b' +>P3Names : Symbol(P3Names, Decl(indexingTypesWithNever.ts, 63, 13)) +>RequiredPropNames : Symbol(RequiredPropNames, Decl(indexingTypesWithNever.ts, 38, 24)) +>P3 : Symbol(P3, Decl(indexingTypesWithNever.ts, 58, 20)) + +type P2Names = RequiredPropNames; // expect 'a' +>P2Names : Symbol(P2Names, Decl(indexingTypesWithNever.ts, 65, 37)) +>RequiredPropNames : Symbol(RequiredPropNames, Decl(indexingTypesWithNever.ts, 38, 24)) +>P2 : Symbol(P2, Decl(indexingTypesWithNever.ts, 60, 48)) + +type P1Names = RequiredPropNames; // expect never +>P1Names : Symbol(P1Names, Decl(indexingTypesWithNever.ts, 66, 37)) +>RequiredPropNames : Symbol(RequiredPropNames, Decl(indexingTypesWithNever.ts, 38, 24)) +>P1 : Symbol(P1, Decl(indexingTypesWithNever.ts, 61, 37)) + +type P0Names = RequiredPropNames; // expect never +>P0Names : Symbol(P0Names, Decl(indexingTypesWithNever.ts, 67, 37)) +>RequiredPropNames : Symbol(RequiredPropNames, Decl(indexingTypesWithNever.ts, 38, 24)) +>P0 : Symbol(P0, Decl(indexingTypesWithNever.ts, 62, 26)) + +declare const p3NameTest: ExpectType<"a" | "b", P3Names>; +>p3NameTest : Symbol(p3NameTest, Decl(indexingTypesWithNever.ts, 70, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>P3Names : Symbol(P3Names, Decl(indexingTypesWithNever.ts, 63, 13)) + +declare const p2NameTest: ExpectType<"a", P2Names>; +>p2NameTest : Symbol(p2NameTest, Decl(indexingTypesWithNever.ts, 71, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>P2Names : Symbol(P2Names, Decl(indexingTypesWithNever.ts, 65, 37)) + +declare const p1NameTest: ExpectType; +>p1NameTest : Symbol(p1NameTest, Decl(indexingTypesWithNever.ts, 72, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>P1Names : Symbol(P1Names, Decl(indexingTypesWithNever.ts, 66, 37)) + +declare const p0NameTest: ExpectType; +>p0NameTest : Symbol(p0NameTest, Decl(indexingTypesWithNever.ts, 73, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>P0Names : Symbol(P0Names, Decl(indexingTypesWithNever.ts, 67, 37)) + +type P3Props = RequiredProps; // expect { a: string; b: number } +>P3Props : Symbol(P3Props, Decl(indexingTypesWithNever.ts, 73, 53)) +>RequiredProps : Symbol(RequiredProps, Decl(indexingTypesWithNever.ts, 47, 11)) +>P3 : Symbol(P3, Decl(indexingTypesWithNever.ts, 58, 20)) + +type P2Props = RequiredProps; // expect { a: string; } +>P2Props : Symbol(P2Props, Decl(indexingTypesWithNever.ts, 75, 33)) +>RequiredProps : Symbol(RequiredProps, Decl(indexingTypesWithNever.ts, 47, 11)) +>P2 : Symbol(P2, Decl(indexingTypesWithNever.ts, 60, 48)) + +type P1Props = RequiredProps; // expect {} +>P1Props : Symbol(P1Props, Decl(indexingTypesWithNever.ts, 76, 33)) +>RequiredProps : Symbol(RequiredProps, Decl(indexingTypesWithNever.ts, 47, 11)) +>P1 : Symbol(P1, Decl(indexingTypesWithNever.ts, 61, 37)) + +type P0Props = RequiredProps; // expect {} +>P0Props : Symbol(P0Props, Decl(indexingTypesWithNever.ts, 77, 33)) +>RequiredProps : Symbol(RequiredProps, Decl(indexingTypesWithNever.ts, 47, 11)) +>P0 : Symbol(P0, Decl(indexingTypesWithNever.ts, 62, 26)) + +declare const p3Test: ExpectType<{ a: string; b: number }, P3Props>; +>p3Test : Symbol(p3Test, Decl(indexingTypesWithNever.ts, 80, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 80, 34)) +>b : Symbol(b, Decl(indexingTypesWithNever.ts, 80, 45)) +>P3Props : Symbol(P3Props, Decl(indexingTypesWithNever.ts, 73, 53)) + +declare const p2Test: ExpectType<{ a: string }, P2Props>; +>p2Test : Symbol(p2Test, Decl(indexingTypesWithNever.ts, 81, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 81, 34)) +>P2Props : Symbol(P2Props, Decl(indexingTypesWithNever.ts, 75, 33)) + +declare const p1Test: ExpectType<{}, P1Props>; +>p1Test : Symbol(p1Test, Decl(indexingTypesWithNever.ts, 82, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>P1Props : Symbol(P1Props, Decl(indexingTypesWithNever.ts, 76, 33)) + +declare const p0Test: ExpectType<{}, P0Props>; +>p0Test : Symbol(p0Test, Decl(indexingTypesWithNever.ts, 83, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>P0Props : Symbol(P0Props, Decl(indexingTypesWithNever.ts, 77, 33)) + +type O3 = { a?: string; b?: number; c: boolean }; +>O3 : Symbol(O3, Decl(indexingTypesWithNever.ts, 83, 46)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 85, 11)) +>b : Symbol(b, Decl(indexingTypesWithNever.ts, 85, 23)) +>c : Symbol(c, Decl(indexingTypesWithNever.ts, 85, 35)) + +type O2 = { a?: string; c: boolean }; +>O2 : Symbol(O2, Decl(indexingTypesWithNever.ts, 85, 49)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 86, 11)) +>c : Symbol(c, Decl(indexingTypesWithNever.ts, 86, 23)) + +type O1 = { c: boolean }; +>O1 : Symbol(O1, Decl(indexingTypesWithNever.ts, 86, 37)) +>c : Symbol(c, Decl(indexingTypesWithNever.ts, 87, 11)) + +type O0 = {}; +>O0 : Symbol(O0, Decl(indexingTypesWithNever.ts, 87, 25)) + +type O3Names = OptionalPropNames; // expect 'a' | 'b' +>O3Names : Symbol(O3Names, Decl(indexingTypesWithNever.ts, 88, 13)) +>OptionalPropNames : Symbol(OptionalPropNames, Decl(indexingTypesWithNever.ts, 43, 11)) +>O3 : Symbol(O3, Decl(indexingTypesWithNever.ts, 83, 46)) + +type O2Names = OptionalPropNames; // expect 'a' +>O2Names : Symbol(O2Names, Decl(indexingTypesWithNever.ts, 90, 37)) +>OptionalPropNames : Symbol(OptionalPropNames, Decl(indexingTypesWithNever.ts, 43, 11)) +>O2 : Symbol(O2, Decl(indexingTypesWithNever.ts, 85, 49)) + +type O1Names = OptionalPropNames; // expect never +>O1Names : Symbol(O1Names, Decl(indexingTypesWithNever.ts, 91, 37)) +>OptionalPropNames : Symbol(OptionalPropNames, Decl(indexingTypesWithNever.ts, 43, 11)) +>O1 : Symbol(O1, Decl(indexingTypesWithNever.ts, 86, 37)) + +type O0Names = OptionalPropNames; // expect never +>O0Names : Symbol(O0Names, Decl(indexingTypesWithNever.ts, 92, 37)) +>OptionalPropNames : Symbol(OptionalPropNames, Decl(indexingTypesWithNever.ts, 43, 11)) +>O0 : Symbol(O0, Decl(indexingTypesWithNever.ts, 87, 25)) + +declare const o3NameTest: ExpectType<"a" | "b", O3Names>; +>o3NameTest : Symbol(o3NameTest, Decl(indexingTypesWithNever.ts, 95, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>O3Names : Symbol(O3Names, Decl(indexingTypesWithNever.ts, 88, 13)) + +declare const o2NameTest: ExpectType<"a", O2Names>; +>o2NameTest : Symbol(o2NameTest, Decl(indexingTypesWithNever.ts, 96, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>O2Names : Symbol(O2Names, Decl(indexingTypesWithNever.ts, 90, 37)) + +declare const o1NameTest: ExpectType; +>o1NameTest : Symbol(o1NameTest, Decl(indexingTypesWithNever.ts, 97, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>O1Names : Symbol(O1Names, Decl(indexingTypesWithNever.ts, 91, 37)) + +declare const o0NameTest: ExpectType; +>o0NameTest : Symbol(o0NameTest, Decl(indexingTypesWithNever.ts, 98, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>O0Names : Symbol(O0Names, Decl(indexingTypesWithNever.ts, 92, 37)) + +type O3Props = OptionalProps; // expect { a?: string | undefined; b?: number | undefined } +>O3Props : Symbol(O3Props, Decl(indexingTypesWithNever.ts, 98, 53)) +>OptionalProps : Symbol(OptionalProps, Decl(indexingTypesWithNever.ts, 49, 62)) +>O3 : Symbol(O3, Decl(indexingTypesWithNever.ts, 83, 46)) + +type O2Props = OptionalProps; // expect { a?: string | undefined; } +>O2Props : Symbol(O2Props, Decl(indexingTypesWithNever.ts, 100, 33)) +>OptionalProps : Symbol(OptionalProps, Decl(indexingTypesWithNever.ts, 49, 62)) +>O2 : Symbol(O2, Decl(indexingTypesWithNever.ts, 85, 49)) + +type O1Props = OptionalProps; // expect {} +>O1Props : Symbol(O1Props, Decl(indexingTypesWithNever.ts, 101, 33)) +>OptionalProps : Symbol(OptionalProps, Decl(indexingTypesWithNever.ts, 49, 62)) +>O1 : Symbol(O1, Decl(indexingTypesWithNever.ts, 86, 37)) + +type O0Props = OptionalProps; // expect {} +>O0Props : Symbol(O0Props, Decl(indexingTypesWithNever.ts, 102, 33)) +>OptionalProps : Symbol(OptionalProps, Decl(indexingTypesWithNever.ts, 49, 62)) +>O0 : Symbol(O0, Decl(indexingTypesWithNever.ts, 87, 25)) + +declare const o3Test: ExpectType<{ a?: string; b?: number }, O3Props>; +>o3Test : Symbol(o3Test, Decl(indexingTypesWithNever.ts, 105, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 105, 34)) +>b : Symbol(b, Decl(indexingTypesWithNever.ts, 105, 46)) +>O3Props : Symbol(O3Props, Decl(indexingTypesWithNever.ts, 98, 53)) + +declare const o2Test: ExpectType<{ a?: string }, O2Props>; +>o2Test : Symbol(o2Test, Decl(indexingTypesWithNever.ts, 106, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>a : Symbol(a, Decl(indexingTypesWithNever.ts, 106, 34)) +>O2Props : Symbol(O2Props, Decl(indexingTypesWithNever.ts, 100, 33)) + +declare const o1Test: ExpectType<{}, O1Props>; +>o1Test : Symbol(o1Test, Decl(indexingTypesWithNever.ts, 107, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>O1Props : Symbol(O1Props, Decl(indexingTypesWithNever.ts, 101, 33)) + +declare const o0Test: ExpectType<{}, O0Props>; +>o0Test : Symbol(o0Test, Decl(indexingTypesWithNever.ts, 108, 13)) +>ExpectType : Symbol(ExpectType, Decl(indexingTypesWithNever.ts, 54, 22)) +>O0Props : Symbol(O0Props, Decl(indexingTypesWithNever.ts, 102, 33)) + diff --git a/tests/baselines/reference/indexingTypesWithNever.types b/tests/baselines/reference/indexingTypesWithNever.types new file mode 100644 index 00000000000..fb6b3904f3a --- /dev/null +++ b/tests/baselines/reference/indexingTypesWithNever.types @@ -0,0 +1,404 @@ +=== tests/cases/compiler/indexingTypesWithNever.ts === +type TestObj = { +>TestObj : TestObj + + a: string; +>a : string + + b: number; +>b : number + +}; + +// Should be never but without an error +type Result1 = TestObj[never]; +>Result1 : never +>TestObj : TestObj + +type EmptyObj = {}; +>EmptyObj : EmptyObj + +// Should be never but without an error +type Result2 = EmptyObj[keyof EmptyObj]; +>Result2 : never +>EmptyObj : EmptyObj +>EmptyObj : EmptyObj + +declare function genericFn1(obj: T): T[never]; +>genericFn1 : (obj: T) => T[never] +>T : T +>obj : T +>T : T +>T : T + +// Should be never +const result3 = genericFn1({ c: "ctest", d: "dtest" }); +>result3 : never +>genericFn1({ c: "ctest", d: "dtest" }) : never +>genericFn1 : (obj: T) => T[never] +>{ c: "ctest", d: "dtest" } : { c: string; d: string; } +>c : string +>"ctest" : "ctest" +>d : string +>"dtest" : "dtest" + +declare function genericFn2( +>genericFn2 : (obj: T) => T[never] +>T : T +>ind : string + + obj: T +>obj : T +>T : T + +): T[never]; +>T : T + +// Should be never +const result4 = genericFn2({ e: "etest", f: "ftest" }); +>result4 : never +>genericFn2({ e: "etest", f: "ftest" }) : never +>genericFn2 : (obj: T) => T[never] +>{ e: "etest", f: "ftest" } : { e: string; f: string; } +>e : string +>"etest" : "etest" +>f : string +>"ftest" : "ftest" + +declare function genericFn3< +>genericFn3 : (obj: T, u: U, v: V) => T[U & V] + + T extends { [K in keyof T]: T[K] }, +>T : T +>K : K +>T : T +>T : T +>K : K + + U extends keyof T, +>U : U +>T : T + + V extends keyof T +>V : V +>T : T + +>(obj: T, u: U, v: V): T[U & V]; +>obj : T +>T : T +>u : U +>U : U +>v : V +>V : V +>T : T +>U : U +>V : V + +// Should be never +const result5 = genericFn3({ g: "gtest", h: "htest" }, "g", "h"); // 'g' & 'h' will reduce to never +>result5 : any +>genericFn3({ g: "gtest", h: "htest" }, "g", "h") : any +>genericFn3 : (obj: T, u: U, v: V) => T[U & V] +>{ g: "gtest", h: "htest" } : { g: string; h: string; } +>g : string +>"gtest" : "gtest" +>h : string +>"htest" : "htest" +>"g" : "g" +>"h" : "h" + + +declare const obj: {a: string, b: number} +>obj : { a: string; b: number; } +>a : string +>b : number + +declare const key: never +>key : never + +const result6 = obj[key] +>result6 : never +>obj[key] : never +>obj : { a: string; b: number; } +>key : never + +// Expanded examples from https://github.com/Microsoft/TypeScript/issues/21988 +type RequiredPropNames = { +>RequiredPropNames : { [P in keyof T]-?: undefined extends T[P] ? never : P; }[keyof T] +>T : T + + [P in keyof T]-?: undefined extends T[P] ? never : P +>P : P +>T : T +>T : T +>P : P +>P : P + +}[keyof T]; +>T : T + +type OptionalPropNames = { +>OptionalPropNames : { [P in keyof T]-?: undefined extends T[P] ? P : never; }[keyof T] +>T : T + + [P in keyof T]-?: undefined extends T[P] ? P : never +>P : P +>T : T +>T : T +>P : P +>P : P + +}[keyof T]; +>T : T + +type RequiredProps = { [P in RequiredPropNames]: T[P] }; +>RequiredProps : RequiredProps +>T : T +>P : P +>RequiredPropNames : { [P in keyof T]-?: undefined extends T[P] ? never : P; }[keyof T] +>T : T +>T : T +>P : P + +type OptionalProps = { [P in OptionalPropNames]?: T[P] }; +>OptionalProps : OptionalProps +>T : T +>P : P +>OptionalPropNames : { [P in keyof T]-?: undefined extends T[P] ? P : never; }[keyof T] +>T : T +>T : T +>P : P + +type Match = [Exp] extends [Act] +>Match : Match +>Exp : Exp +>Act : Act +>Exp : Exp +>Act : Act + + ? ([Act] extends [Exp] ? "Match" : "Did not match 2") +>Act : Act +>Exp : Exp + + : "Did not match 1"; + +type ExpectType = Match extends "Match" +>ExpectType : ExpectType +>Exp : Exp +>Act : Act +>Match : Match +>Exp : Exp +>Act : Act + + ? ({} extends Exp ? Match, Required> : "Match") +>Exp : Exp +>Match : Match +>Required : Required +>Exp : Exp +>Required : Required +>Act : Act + + : "Did not match"; + +type P3 = { a: string; b: number; c?: boolean }; +>P3 : P3 +>a : string +>b : number +>c : boolean | undefined + +type P2 = { a: string; c?: boolean }; +>P2 : P2 +>a : string +>c : boolean | undefined + +type P1 = { c?: boolean }; +>P1 : P1 +>c : boolean | undefined + +type P0 = {}; +>P0 : P0 + +type P3Names = RequiredPropNames; // expect 'a' | 'b' +>P3Names : "a" | "b" +>RequiredPropNames : { [P in keyof T]-?: undefined extends T[P] ? never : P; }[keyof T] +>P3 : P3 + +type P2Names = RequiredPropNames; // expect 'a' +>P2Names : "a" +>RequiredPropNames : { [P in keyof T]-?: undefined extends T[P] ? never : P; }[keyof T] +>P2 : P2 + +type P1Names = RequiredPropNames; // expect never +>P1Names : never +>RequiredPropNames : { [P in keyof T]-?: undefined extends T[P] ? never : P; }[keyof T] +>P1 : P1 + +type P0Names = RequiredPropNames; // expect never +>P0Names : never +>RequiredPropNames : { [P in keyof T]-?: undefined extends T[P] ? never : P; }[keyof T] +>P0 : P0 + +declare const p3NameTest: ExpectType<"a" | "b", P3Names>; +>p3NameTest : "Match" +>ExpectType : ExpectType +>P3Names : "a" | "b" + +declare const p2NameTest: ExpectType<"a", P2Names>; +>p2NameTest : "Match" +>ExpectType : ExpectType +>P2Names : "a" + +declare const p1NameTest: ExpectType; +>p1NameTest : "Match" +>ExpectType : ExpectType +>P1Names : never + +declare const p0NameTest: ExpectType; +>p0NameTest : "Match" +>ExpectType : ExpectType +>P0Names : never + +type P3Props = RequiredProps; // expect { a: string; b: number } +>P3Props : RequiredProps +>RequiredProps : RequiredProps +>P3 : P3 + +type P2Props = RequiredProps; // expect { a: string; } +>P2Props : RequiredProps +>RequiredProps : RequiredProps +>P2 : P2 + +type P1Props = RequiredProps; // expect {} +>P1Props : RequiredProps +>RequiredProps : RequiredProps +>P1 : P1 + +type P0Props = RequiredProps; // expect {} +>P0Props : RequiredProps +>RequiredProps : RequiredProps +>P0 : P0 + +declare const p3Test: ExpectType<{ a: string; b: number }, P3Props>; +>p3Test : "Match" +>ExpectType : ExpectType +>a : string +>b : number +>P3Props : RequiredProps + +declare const p2Test: ExpectType<{ a: string }, P2Props>; +>p2Test : "Match" +>ExpectType : ExpectType +>a : string +>P2Props : RequiredProps + +declare const p1Test: ExpectType<{}, P1Props>; +>p1Test : "Match" +>ExpectType : ExpectType +>P1Props : RequiredProps + +declare const p0Test: ExpectType<{}, P0Props>; +>p0Test : "Match" +>ExpectType : ExpectType +>P0Props : RequiredProps + +type O3 = { a?: string; b?: number; c: boolean }; +>O3 : O3 +>a : string | undefined +>b : number | undefined +>c : boolean + +type O2 = { a?: string; c: boolean }; +>O2 : O2 +>a : string | undefined +>c : boolean + +type O1 = { c: boolean }; +>O1 : O1 +>c : boolean + +type O0 = {}; +>O0 : O0 + +type O3Names = OptionalPropNames; // expect 'a' | 'b' +>O3Names : "a" | "b" +>OptionalPropNames : { [P in keyof T]-?: undefined extends T[P] ? P : never; }[keyof T] +>O3 : O3 + +type O2Names = OptionalPropNames; // expect 'a' +>O2Names : "a" +>OptionalPropNames : { [P in keyof T]-?: undefined extends T[P] ? P : never; }[keyof T] +>O2 : O2 + +type O1Names = OptionalPropNames; // expect never +>O1Names : never +>OptionalPropNames : { [P in keyof T]-?: undefined extends T[P] ? P : never; }[keyof T] +>O1 : O1 + +type O0Names = OptionalPropNames; // expect never +>O0Names : never +>OptionalPropNames : { [P in keyof T]-?: undefined extends T[P] ? P : never; }[keyof T] +>O0 : O0 + +declare const o3NameTest: ExpectType<"a" | "b", O3Names>; +>o3NameTest : "Match" +>ExpectType : ExpectType +>O3Names : "a" | "b" + +declare const o2NameTest: ExpectType<"a", O2Names>; +>o2NameTest : "Match" +>ExpectType : ExpectType +>O2Names : "a" + +declare const o1NameTest: ExpectType; +>o1NameTest : "Match" +>ExpectType : ExpectType +>O1Names : never + +declare const o0NameTest: ExpectType; +>o0NameTest : "Match" +>ExpectType : ExpectType +>O0Names : never + +type O3Props = OptionalProps; // expect { a?: string | undefined; b?: number | undefined } +>O3Props : OptionalProps +>OptionalProps : OptionalProps +>O3 : O3 + +type O2Props = OptionalProps; // expect { a?: string | undefined; } +>O2Props : OptionalProps +>OptionalProps : OptionalProps +>O2 : O2 + +type O1Props = OptionalProps; // expect {} +>O1Props : OptionalProps +>OptionalProps : OptionalProps +>O1 : O1 + +type O0Props = OptionalProps; // expect {} +>O0Props : OptionalProps +>OptionalProps : OptionalProps +>O0 : O0 + +declare const o3Test: ExpectType<{ a?: string; b?: number }, O3Props>; +>o3Test : "Match" +>ExpectType : ExpectType +>a : string | undefined +>b : number | undefined +>O3Props : OptionalProps + +declare const o2Test: ExpectType<{ a?: string }, O2Props>; +>o2Test : "Match" +>ExpectType : ExpectType +>a : string | undefined +>O2Props : OptionalProps + +declare const o1Test: ExpectType<{}, O1Props>; +>o1Test : "Match" +>ExpectType : ExpectType +>O1Props : OptionalProps + +declare const o0Test: ExpectType<{}, O0Props>; +>o0Test : "Match" +>ExpectType : ExpectType +>O0Props : OptionalProps + diff --git a/tests/cases/compiler/indexingTypesWithNever.ts b/tests/cases/compiler/indexingTypesWithNever.ts new file mode 100644 index 00000000000..9044ded2ff4 --- /dev/null +++ b/tests/cases/compiler/indexingTypesWithNever.ts @@ -0,0 +1,111 @@ +// @strict: true + +type TestObj = { + a: string; + b: number; +}; + +// Should be never but without an error +type Result1 = TestObj[never]; + +type EmptyObj = {}; + +// Should be never but without an error +type Result2 = EmptyObj[keyof EmptyObj]; + +declare function genericFn1(obj: T): T[never]; + +// Should be never +const result3 = genericFn1({ c: "ctest", d: "dtest" }); + +declare function genericFn2( + obj: T +): T[never]; + +// Should be never +const result4 = genericFn2({ e: "etest", f: "ftest" }); + +declare function genericFn3< + T extends { [K in keyof T]: T[K] }, + U extends keyof T, + V extends keyof T +>(obj: T, u: U, v: V): T[U & V]; + +// Should be never +const result5 = genericFn3({ g: "gtest", h: "htest" }, "g", "h"); // 'g' & 'h' will reduce to never + + +declare const obj: {a: string, b: number} +declare const key: never + +const result6 = obj[key] + +// Expanded examples from https://github.com/Microsoft/TypeScript/issues/21988 +type RequiredPropNames = { + [P in keyof T]-?: undefined extends T[P] ? never : P +}[keyof T]; + +type OptionalPropNames = { + [P in keyof T]-?: undefined extends T[P] ? P : never +}[keyof T]; + +type RequiredProps = { [P in RequiredPropNames]: T[P] }; +type OptionalProps = { [P in OptionalPropNames]?: T[P] }; + +type Match = [Exp] extends [Act] + ? ([Act] extends [Exp] ? "Match" : "Did not match 2") + : "Did not match 1"; + +type ExpectType = Match extends "Match" + ? ({} extends Exp ? Match, Required> : "Match") + : "Did not match"; + +type P3 = { a: string; b: number; c?: boolean }; +type P2 = { a: string; c?: boolean }; +type P1 = { c?: boolean }; +type P0 = {}; + +type P3Names = RequiredPropNames; // expect 'a' | 'b' +type P2Names = RequiredPropNames; // expect 'a' +type P1Names = RequiredPropNames; // expect never +type P0Names = RequiredPropNames; // expect never + +declare const p3NameTest: ExpectType<"a" | "b", P3Names>; +declare const p2NameTest: ExpectType<"a", P2Names>; +declare const p1NameTest: ExpectType; +declare const p0NameTest: ExpectType; + +type P3Props = RequiredProps; // expect { a: string; b: number } +type P2Props = RequiredProps; // expect { a: string; } +type P1Props = RequiredProps; // expect {} +type P0Props = RequiredProps; // expect {} + +declare const p3Test: ExpectType<{ a: string; b: number }, P3Props>; +declare const p2Test: ExpectType<{ a: string }, P2Props>; +declare const p1Test: ExpectType<{}, P1Props>; +declare const p0Test: ExpectType<{}, P0Props>; + +type O3 = { a?: string; b?: number; c: boolean }; +type O2 = { a?: string; c: boolean }; +type O1 = { c: boolean }; +type O0 = {}; + +type O3Names = OptionalPropNames; // expect 'a' | 'b' +type O2Names = OptionalPropNames; // expect 'a' +type O1Names = OptionalPropNames; // expect never +type O0Names = OptionalPropNames; // expect never + +declare const o3NameTest: ExpectType<"a" | "b", O3Names>; +declare const o2NameTest: ExpectType<"a", O2Names>; +declare const o1NameTest: ExpectType; +declare const o0NameTest: ExpectType; + +type O3Props = OptionalProps; // expect { a?: string | undefined; b?: number | undefined } +type O2Props = OptionalProps; // expect { a?: string | undefined; } +type O1Props = OptionalProps; // expect {} +type O0Props = OptionalProps; // expect {} + +declare const o3Test: ExpectType<{ a?: string; b?: number }, O3Props>; +declare const o2Test: ExpectType<{ a?: string }, O2Props>; +declare const o1Test: ExpectType<{}, O1Props>; +declare const o0Test: ExpectType<{}, O0Props>; From ea6740fa9195bc38bbcdc52b9fc20415affc7a32 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 10:34:16 -0700 Subject: [PATCH 11/75] replaceNode: Always use non-adjusted end (#22519) * replaceNode: Always use non-adjusted end * Never adjust start position either * Fix excess property checks, remove unnecessary arguments * Make 'insertText' and 'newLineCharacter' private * Use replaceNode in one more place now that it doesn't affect comments * Update replaceNodeRange too * Always ask for ChangeNodeOptions --- src/services/codefixes/convertToEs6Module.ts | 2 +- .../codefixes/disableJsDiagnostics.ts | 25 ++----- .../fixExtendsInterfaceBecomesImplements.ts | 2 +- .../fixForgottenThisPropertyAccess.ts | 2 +- .../codefixes/fixInvalidImportSyntax.ts | 3 +- .../codefixes/fixStrictClassInitialization.ts | 27 ++++---- src/services/codefixes/fixUnusedIdentifier.ts | 2 +- src/services/codefixes/useDefaultImport.ts | 2 +- src/services/refactors/extractSymbol.ts | 8 +-- src/services/textChanges.ts | 67 ++++++++++++------- 10 files changed, 70 insertions(+), 70 deletions(-) diff --git a/src/services/codefixes/convertToEs6Module.ts b/src/services/codefixes/convertToEs6Module.ts index c998c6940c5..b39f22be177 100644 --- a/src/services/codefixes/convertToEs6Module.ts +++ b/src/services/codefixes/convertToEs6Module.ts @@ -257,7 +257,7 @@ namespace ts.codefix { changes.replaceNodeWithNodes(sourceFile, statement, newNodes); } else { - changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right)); } } diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index 57778d73526..8ee89ecbf25 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -27,7 +27,7 @@ namespace ts.codefix { fixId: undefined, }]; - if (isValidSuppressLocation(sourceFile, span.start)) { + if (isValidLocationToAddComment(sourceFile, span.start)) { fixes.unshift({ description: getLocaleSpecificMessage(Diagnostics.Ignore_this_error_message), changes: textChanges.ChangeTracker.with(context, t => makeChange(t, sourceFile, span.start)), @@ -41,37 +41,22 @@ namespace ts.codefix { getAllCodeActions: context => { const seenLines = createMap(); return codeFixAll(context, errorCodes, (changes, diag) => { - if (isValidSuppressLocation(diag.file!, diag.start!)) { + if (isValidLocationToAddComment(diag.file!, diag.start!)) { makeChange(changes, diag.file!, diag.start!, seenLines); } }); }, }); - function isValidSuppressLocation(sourceFile: SourceFile, position: number) { + export function isValidLocationToAddComment(sourceFile: SourceFile, position: number) { return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position); } function makeChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, seenLines?: Map) { const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position); - // Only need to add `// @ts-ignore` for a line once. - if (seenLines && !addToSeen(seenLines, lineNumber)) { - return; + if (!seenLines || addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } - - const lineStartPosition = getStartPositionOfLine(lineNumber, sourceFile); - const startPosition = 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. - // If so, we do not want to separate the node from its comment if we can. - // Otherwise, add an extra new line immediately before the error span. - const insertAtLineStart = isValidSuppressLocation(sourceFile, startPosition); - - const token = getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); - const clone = setStartsOnNewLine(getSynthesizedDeepClone(token), true); - addSyntheticLeadingComment(clone, SyntaxKind.SingleLineCommentTrivia, " @ts-ignore"); - changes.replaceNode(sourceFile, token, clone, { preserveLeadingWhitespace: true, prefix: insertAtLineStart ? undefined : changes.newLineCharacter }); } } diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index 9b775bef622..92d65299489 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -27,7 +27,7 @@ namespace ts.codefix { } function doChanges(changes: textChanges.ChangeTracker, sourceFile: SourceFile, extendsToken: Node, heritageClauses: ReadonlyArray): void { - changes.replaceNode(sourceFile, extendsToken, createToken(SyntaxKind.ImplementsKeyword), textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, extendsToken, createToken(SyntaxKind.ImplementsKeyword)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && diff --git a/src/services/codefixes/fixForgottenThisPropertyAccess.ts b/src/services/codefixes/fixForgottenThisPropertyAccess.ts index e71c06399c2..10933b031e5 100644 --- a/src/services/codefixes/fixForgottenThisPropertyAccess.ts +++ b/src/services/codefixes/fixForgottenThisPropertyAccess.ts @@ -30,6 +30,6 @@ namespace ts.codefix { } // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper suppressLeadingAndTrailingTrivia(token); - changes.replaceNode(sourceFile, token, createPropertyAccess(createThis(), token), textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, token, createPropertyAccess(createThis(), token)); } } diff --git a/src/services/codefixes/fixInvalidImportSyntax.ts b/src/services/codefixes/fixInvalidImportSyntax.ts index 0939475b835..fd66a9db37c 100644 --- a/src/services/codefixes/fixInvalidImportSyntax.ts +++ b/src/services/codefixes/fixInvalidImportSyntax.ts @@ -42,8 +42,7 @@ namespace ts.codefix { } function createAction(context: CodeFixContext, sourceFile: SourceFile, node: Node, replacement: Node): CodeAction { - // TODO: GH#21246 Should be able to use `replaceNode`, but be sure to preserve comments (see `codeFixCalledES2015Import11.ts`) - const changes = textChanges.ChangeTracker.with(context, t => t.replaceRange(sourceFile, { pos: node.getStart(), end: node.end }, replacement)); + const changes = textChanges.ChangeTracker.with(context, t => t.replaceNode(sourceFile, node, replacement)); return { description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), changes, diff --git a/src/services/codefixes/fixStrictClassInitialization.ts b/src/services/codefixes/fixStrictClassInitialization.ts index 1199e6a059d..a5420f2c181 100644 --- a/src/services/codefixes/fixStrictClassInitialization.ts +++ b/src/services/codefixes/fixStrictClassInitialization.ts @@ -10,27 +10,24 @@ namespace ts.codefix { const propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); if (!propertyDeclaration) return; - const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); const result = [ getActionForAddMissingUndefinedType(context, propertyDeclaration), - getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) ]; - append(result, getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter)); + append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); return result; }, fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: context => { - const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); - return codeFixAll(context, errorCodes, (changes, diag) => { const propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); if (!propertyDeclaration) return; switch (context.fixId) { case fixIdAddDefiniteAssignmentAssertions: - addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration, newLineCharacter); + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); break; case fixIdAddUndefinedType: addUndefinedType(changes, diag.file, propertyDeclaration); @@ -40,7 +37,7 @@ namespace ts.codefix { const initializer = getInitializer(checker, propertyDeclaration); if (!initializer) return; - addInitializer(changes, diag.file, propertyDeclaration, initializer, newLineCharacter); + addInitializer(changes, diag.file, propertyDeclaration, initializer); break; default: Debug.fail(JSON.stringify(context.fixId)); @@ -54,13 +51,13 @@ namespace ts.codefix { return isIdentifier(token) ? cast(token.parent, isPropertyDeclaration) : undefined; } - function getActionForAddMissingDefiniteAssignmentAssertion (context: CodeFixContext, propertyDeclaration: PropertyDeclaration, newLineCharacter: string): CodeFixAction { + function getActionForAddMissingDefiniteAssignmentAssertion (context: CodeFixContext, propertyDeclaration: PropertyDeclaration): CodeFixAction { const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_definite_assignment_assertion_to_property_0), [propertyDeclaration.getText()]); - const changes = textChanges.ChangeTracker.with(context, t => addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration, newLineCharacter)); + const changes = textChanges.ChangeTracker.with(context, t => addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration)); return { description, changes, fixId: fixIdAddDefiniteAssignmentAssertions }; } - function addDefiniteAssignmentAssertion(changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration, newLineCharacter: string): void { + function addDefiniteAssignmentAssertion(changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration): void { const property = updateProperty( propertyDeclaration, propertyDeclaration.decorators, @@ -70,7 +67,7 @@ namespace ts.codefix { propertyDeclaration.type, propertyDeclaration.initializer ); - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter }); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType (context: CodeFixContext, propertyDeclaration: PropertyDeclaration): CodeFixAction { @@ -85,17 +82,17 @@ namespace ts.codefix { changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, createUnionTypeNode(types)); } - function getActionForAddMissingInitializer (context: CodeFixContext, propertyDeclaration: PropertyDeclaration, newLineCharacter: string): CodeFixAction | undefined { + function getActionForAddMissingInitializer (context: CodeFixContext, propertyDeclaration: PropertyDeclaration): CodeFixAction | undefined { const checker = context.program.getTypeChecker(); const initializer = getInitializer(checker, propertyDeclaration); if (!initializer) return undefined; const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_initializer_to_property_0), [propertyDeclaration.name.getText()]); - const changes = textChanges.ChangeTracker.with(context, t => addInitializer(t, context.sourceFile, propertyDeclaration, initializer, newLineCharacter)); + const changes = textChanges.ChangeTracker.with(context, t => addInitializer(t, context.sourceFile, propertyDeclaration, initializer)); return { description, changes, fixId: fixIdAddInitializer }; } - function addInitializer (changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration, initializer: Expression, newLineCharacter: string): void { + function addInitializer (changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration, initializer: Expression): void { const property = updateProperty( propertyDeclaration, propertyDeclaration.decorators, @@ -105,7 +102,7 @@ namespace ts.codefix { propertyDeclaration.type, initializer ); - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter }); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker: TypeChecker, propertyDeclaration: PropertyDeclaration): Expression | undefined { diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index ef65e49fc27..3de5e7e36b0 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -165,7 +165,7 @@ namespace ts.codefix { // and trailing trivia will remain. suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction, textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, oldFunction, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); diff --git a/src/services/codefixes/useDefaultImport.ts b/src/services/codefixes/useDefaultImport.ts index 909601ab306..bd0797953b9 100644 --- a/src/services/codefixes/useDefaultImport.ts +++ b/src/services/codefixes/useDefaultImport.ts @@ -38,6 +38,6 @@ namespace ts.codefix { } function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, info: Info): void { - changes.replaceNode(sourceFile, info.importNode, makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier), textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, info.importNode, makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); } } diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 2d76ce1843c..7144265d11a 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -1053,7 +1053,7 @@ namespace ts.refactor.extractSymbol { changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume - changeTracker.replaceNode(context.file, node, localReference, textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else { const newVariableDeclaration = createVariableDeclaration(localNameText, variableType, initializer); @@ -1070,7 +1070,7 @@ namespace ts.refactor.extractSymbol { // Consume const localReference = createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else if (node.parent.kind === SyntaxKind.ExpressionStatement && scope === findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, @@ -1078,7 +1078,7 @@ namespace ts.refactor.extractSymbol { const newVariableStatement = createVariableStatement( /*modifiers*/ undefined, createVariableDeclarationList([newVariableDeclaration], NodeFlags.Const)); - changeTracker.replaceNode(context.file, node.parent, newVariableStatement, textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { const newVariableStatement = createVariableStatement( @@ -1101,7 +1101,7 @@ namespace ts.refactor.extractSymbol { } else { const localReference = createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } } } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 24ff0ba2812..a01eedfcb40 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -103,10 +103,11 @@ namespace ts.textChanges { enum ChangeKind { Remove, ReplaceWithSingleNode, - ReplaceWithMultipleNodes + ReplaceWithMultipleNodes, + Text, } - type Change = ReplaceWithSingleNode | ReplaceWithMultipleNodes | RemoveNode; + type Change = ReplaceWithSingleNode | ReplaceWithMultipleNodes | RemoveNode | ChangeText; interface BaseChange { readonly sourceFile: SourceFile; @@ -132,6 +133,15 @@ namespace ts.textChanges { readonly options?: InsertNodeOptions; } + interface ChangeText extends BaseChange { + readonly kind: ChangeKind.Text; + readonly text: string; + } + + function getAdjustedRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd): TextRange { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; + } + function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStart, position: Position) { if (options.useNonAdjustedStartPosition) { return node.getStart(sourceFile); @@ -212,7 +222,7 @@ namespace ts.textChanges { } /** Public for tests only. Other callers should use `ChangeTracker.with`. */ - constructor(public readonly newLineCharacter: string, private readonly formatContext: formatting.FormatContext) {} + constructor(private readonly newLineCharacter: string, private readonly formatContext: formatting.FormatContext) {} public deleteRange(sourceFile: SourceFile, range: TextRange) { this.changes.push({ kind: ChangeKind.Remove, sourceFile, range }); @@ -280,41 +290,30 @@ namespace ts.textChanges { return this; } - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions public replaceRange(sourceFile: SourceFile, range: TextRange, newNode: Node, options: InsertNodeOptions = {}) { this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile, range, options, node: newNode }); return this; } - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions - public replaceNode(sourceFile: SourceFile, oldNode: Node, newNode: Node, options: ChangeNodeOptions = {}) { - const pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - const end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRange(sourceFile, { pos, end }, newNode, options); + public replaceNode(sourceFile: SourceFile, oldNode: Node, newNode: Node, options: ChangeNodeOptions = useNonAdjustedPositions) { + return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); } - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions - public replaceNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, newNode: Node, options: ChangeNodeOptions = {}) { - const pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - const end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRange(sourceFile, { pos, end }, newNode, options); + public replaceNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, newNode: Node, options: ChangeNodeOptions = useNonAdjustedPositions) { + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); } - public replaceRangeWithNodes(sourceFile: SourceFile, range: TextRange, newNodes: ReadonlyArray, options: InsertNodeOptions = {}) { + private replaceRangeWithNodes(sourceFile: SourceFile, range: TextRange, newNodes: ReadonlyArray, options: InsertNodeOptions = {}) { this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile, range, options, nodes: newNodes }); return this; } public replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: ReadonlyArray, options: ChangeNodeOptions = useNonAdjustedPositions) { - const pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - const end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos, end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); } public replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: ReadonlyArray, options: ChangeNodeOptions = useNonAdjustedPositions) { - const pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - const end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos, end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); } private insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options: InsertNodeOptions = {}) { @@ -344,6 +343,23 @@ namespace ts.textChanges { this.replaceRange(sourceFile, { pos, end: pos }, createToken(modifier), { suffix: " " }); } + public insertCommentBeforeLine(sourceFile: SourceFile, lineNumber: number, position: number, commentText: string): void { + const lineStartPosition = getStartPositionOfLine(lineNumber, sourceFile); + const startPosition = getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + const insertAtLineStart = codefix.isValidLocationToAddComment(sourceFile, startPosition); + const token = getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); + const text = `${insertAtLineStart ? "" : this.newLineCharacter}${sourceFile.text.slice(lineStartPosition, startPosition)}//${commentText}${this.newLineCharacter}`; + this.insertText(sourceFile, token.getStart(sourceFile), text); + } + + private insertText(sourceFile: SourceFile, pos: number, text: string): void { + this.changes.push({ kind: ChangeKind.Text, sourceFile, range: { pos, end: pos }, text }); + } + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ public insertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): void { const end = (isFunctionLike(node) @@ -393,7 +409,7 @@ namespace ts.textChanges { } private replaceConstructorBody(sourceFile: SourceFile, ctr: ConstructorDeclaration, statements: ReadonlyArray): void { - this.replaceNode(sourceFile, ctr.body, createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + this.replaceNode(sourceFile, ctr.body, createBlock(statements, /*multiLine*/ true)); } public insertNodeAtEndOfScope(sourceFile: SourceFile, scope: Node, newNode: Node): void { @@ -608,7 +624,7 @@ namespace ts.textChanges { 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 }); + this.replaceNode(sourceFile, cls, newCls); }); } @@ -647,6 +663,9 @@ namespace ts.textChanges { if (change.kind === ChangeKind.Remove) { return ""; } + if (change.kind === ChangeKind.Text) { + return change.text; + } const { options = {}, range: { pos } } = change; const format = (n: Node) => getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); @@ -659,7 +678,7 @@ namespace ts.textChanges { } /** Note: this may mutate `nodeIn`. */ - function getFormattedTextOfNode(nodeIn: Node, sourceFile: SourceFile, pos: number, options: ChangeNodeOptions, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText): string { + function getFormattedTextOfNode(nodeIn: Node, sourceFile: SourceFile, pos: number, options: InsertNodeOptions, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText): string { const { node, text } = getNonformattedText(nodeIn, sourceFile, newLineCharacter); if (validate) validate(node, text); const { options: formatOptions } = formatContext; From 85f11cc5e45c4d70f99e70b28ca4039dc4f48859 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 10:57:42 -0700 Subject: [PATCH 12/75] textChanges: Use replaceRange in more places (#22904) --- src/compiler/utilities.ts | 6 +++++ src/services/textChanges.ts | 51 +++++++------------------------------ 2 files changed, 15 insertions(+), 42 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index c9d8b6af5c0..7030b3baaa8 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4070,6 +4070,12 @@ namespace ts { return { start, length }; } + /* @internal */ + export function createTextRange(pos: number, end: number = pos): TextRange { + Debug.assert(end >= pos); + return { pos, end }; + } + export function createTextSpanFromBounds(start: number, end: number) { return createTextSpan(start, end - start); } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index a01eedfcb40..2c466cc01ee 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -317,8 +317,7 @@ namespace ts.textChanges { } 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; + this.replaceRange(sourceFile, createTextRange(pos), newNode, options); } private insertNodesAt(sourceFile: SourceFile, pos: number, newNodes: ReadonlyArray, options: InsertNodeOptions = {}): void { @@ -446,17 +445,11 @@ namespace ts.textChanges { // 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) !== CharacterCodes.semicolon) { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile, - options: {}, - range: { pos: after.end, end: after.end }, - node: createToken(SyntaxKind.SemicolonToken) - }); + this.replaceRange(sourceFile, createTextRange(after.end), createToken(SyntaxKind.SemicolonToken)); } } const endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, { pos: endPosition, end: endPosition }, newNode, this.getInsertNodeAfterOptions(after)); + return this.replaceRange(sourceFile, createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); } private getInsertNodeAfterOptions(node: Node): InsertNodeOptions { @@ -540,17 +533,9 @@ namespace ts.textChanges { startPos = getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile, - range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, - node: newNode, - options: { - prefix, - // write separator and leading trivia of the next element as suffix - suffix: `${tokenToString(nextToken.kind)}${sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile))}` - } - }); + // write separator and leading trivia of the next element as suffix + const suffix = `${tokenToString(nextToken.kind)}${sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile))}`; + this.replaceRange(sourceFile, createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix, suffix }); } } else { @@ -584,13 +569,7 @@ namespace ts.textChanges { } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile, - range: { pos: end, end }, - node: createToken(separator), - options: {} - }); + this.replaceRange(sourceFile, createTextRange(end), createToken(separator)); // use the same indentation as 'after' item const indentation = formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -598,22 +577,10 @@ namespace ts.textChanges { if (insertPos !== end && isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile, - range: { pos: insertPos, end: insertPos }, - node: newNode, - options: { indentation, prefix: this.newLineCharacter } - }); + this.replaceRange(sourceFile, createTextRange(insertPos), newNode, { indentation, prefix: this.newLineCharacter }); } else { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile, - range: { pos: end, end }, - node: newNode, - options: { prefix: `${tokenToString(separator)} ` } - }); + this.replaceRange(sourceFile, createTextRange(end), newNode, { prefix: `${tokenToString(separator)} ` }); } } return this; From e9e1d0d70b36c80cbef3d414de145a895550c3e5 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 11:50:34 -0700 Subject: [PATCH 13/75] textChanges: Use InsertNodeOptions instead of ChangeNodeOptions where possible (#22903) --- src/services/textChanges.ts | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 2c466cc01ee..a02f91904d1 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -374,7 +374,7 @@ namespace ts.textChanges { this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); } - private getOptionsForInsertNodeBefore(before: Node, doubleNewlines: boolean): ChangeNodeOptions { + private getOptionsForInsertNodeBefore(before: Node, doubleNewlines: boolean): InsertNodeOptions { if (isStatement(before) || isClassElement(before)) { return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; } @@ -645,20 +645,17 @@ namespace ts.textChanges { } /** Note: this may mutate `nodeIn`. */ - function getFormattedTextOfNode(nodeIn: Node, sourceFile: SourceFile, pos: number, options: InsertNodeOptions, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText): string { + function getFormattedTextOfNode(nodeIn: Node, sourceFile: SourceFile, pos: number, { indentation, prefix, delta }: InsertNodeOptions, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText): string { const { node, text } = getNonformattedText(nodeIn, sourceFile, newLineCharacter); if (validate) validate(node, text); const { options: formatOptions } = formatContext; const initialIndentation = - options.indentation !== undefined - ? options.indentation - : formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, options.prefix === newLineCharacter || getLineStartPositionForPosition(pos, sourceFile) === pos); - const delta = - options.delta !== undefined - ? options.delta - : formatting.SmartIndenter.shouldIndentChildNode(nodeIn) - ? (formatOptions.indentSize || 0) - : 0; + indentation !== undefined + ? indentation + : formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = formatting.SmartIndenter.shouldIndentChildNode(nodeIn) ? (formatOptions.indentSize || 0) : 0; + } const file: SourceFileLike = { text, getLineAndCharacterOfPosition(pos) { return getLineAndCharacterOfPosition(this, pos); } }; const changes = formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); return applyChanges(text, changes); From 2bd66b329206556d36555f7eb06c23c1ce9c58cf Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 11:50:48 -0700 Subject: [PATCH 14/75] textChanges: Add insertCommentBeforeLine method (#22902) --- src/services/codefixes/disableJsDiagnostics.ts | 8 ++------ src/services/textChanges.ts | 6 +++++- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index 8ee89ecbf25..2d82a198ce9 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -27,7 +27,7 @@ namespace ts.codefix { fixId: undefined, }]; - if (isValidLocationToAddComment(sourceFile, span.start)) { + if (textChanges.isValidLocationToAddComment(sourceFile, span.start)) { fixes.unshift({ description: getLocaleSpecificMessage(Diagnostics.Ignore_this_error_message), changes: textChanges.ChangeTracker.with(context, t => makeChange(t, sourceFile, span.start)), @@ -41,17 +41,13 @@ namespace ts.codefix { getAllCodeActions: context => { const seenLines = createMap(); return codeFixAll(context, errorCodes, (changes, diag) => { - if (isValidLocationToAddComment(diag.file!, diag.start!)) { + if (textChanges.isValidLocationToAddComment(diag.file!, diag.start!)) { makeChange(changes, diag.file!, diag.start!, seenLines); } }); }, }); - export function isValidLocationToAddComment(sourceFile: SourceFile, position: number) { - return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position); - } - function makeChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, seenLines?: Map) { const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position); // Only need to add `// @ts-ignore` for a line once. diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index a02f91904d1..05c218b2241 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -349,7 +349,7 @@ namespace ts.textChanges { // We need to make sure that we are not in the middle of a string literal or a comment. // If so, we do not want to separate the node from its comment if we can. // Otherwise, add an extra new line immediately before the error span. - const insertAtLineStart = codefix.isValidLocationToAddComment(sourceFile, startPosition); + const insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); const token = getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); const text = `${insertAtLineStart ? "" : this.newLineCharacter}${sourceFile.text.slice(lineStartPosition, startPosition)}//${commentText}${this.newLineCharacter}`; this.insertText(sourceFile, token.getStart(sourceFile), text); @@ -879,4 +879,8 @@ namespace ts.textChanges { } } } + + export function isValidLocationToAddComment(sourceFile: SourceFile, position: number) { + return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position); + } } From 61aad4c7b8502096a4b0ee06552defc9b8569ae2 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 27 Mar 2018 12:24:37 -0700 Subject: [PATCH 15/75] Handle toplevel this-assignment (#22913) Do nothing now. Someday we might handle it correctly. --- src/compiler/binder.ts | 4 +++ .../reference/topLevelThisAssignment.js | 18 +++++++++++++ .../reference/topLevelThisAssignment.symbols | 10 ++++++++ .../reference/topLevelThisAssignment.types | 25 +++++++++++++++++++ .../salsa/topLevelThisAssignment.ts | 10 ++++++++ 5 files changed, 67 insertions(+) create mode 100644 tests/baselines/reference/topLevelThisAssignment.js create mode 100644 tests/baselines/reference/topLevelThisAssignment.symbols create mode 100644 tests/baselines/reference/topLevelThisAssignment.types create mode 100644 tests/cases/conformance/salsa/topLevelThisAssignment.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 2b66e92cdc3..c7d258bb1d9 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2362,6 +2362,10 @@ namespace ts { const symbolTable = hasModifier(thisContainer, ModifierFlags.Static) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, SymbolFlags.Property, SymbolFlags.None, /*isReplaceableByMethod*/ true); break; + case SyntaxKind.SourceFile: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; default: Debug.fail(Debug.showSyntaxKind(thisContainer)); diff --git a/tests/baselines/reference/topLevelThisAssignment.js b/tests/baselines/reference/topLevelThisAssignment.js new file mode 100644 index 00000000000..c87fad289f7 --- /dev/null +++ b/tests/baselines/reference/topLevelThisAssignment.js @@ -0,0 +1,18 @@ +//// [tests/cases/conformance/salsa/topLevelThisAssignment.ts] //// + +//// [a.js] +this.a = 10; +this.a; +a; + +//// [b.js] +this.a; +a; + + +//// [output.js] +this.a = 10; +this.a; +a; +this.a; +a; diff --git a/tests/baselines/reference/topLevelThisAssignment.symbols b/tests/baselines/reference/topLevelThisAssignment.symbols new file mode 100644 index 00000000000..e9b94983bf2 --- /dev/null +++ b/tests/baselines/reference/topLevelThisAssignment.symbols @@ -0,0 +1,10 @@ +=== tests/cases/conformance/salsa/a.js === +this.a = 10; +No type information for this code.this.a; +No type information for this code.a; +No type information for this code. +No type information for this code.=== tests/cases/conformance/salsa/b.js === +this.a; +No type information for this code.a; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/topLevelThisAssignment.types b/tests/baselines/reference/topLevelThisAssignment.types new file mode 100644 index 00000000000..024c360f8cc --- /dev/null +++ b/tests/baselines/reference/topLevelThisAssignment.types @@ -0,0 +1,25 @@ +=== tests/cases/conformance/salsa/a.js === +this.a = 10; +>this.a = 10 : 10 +>this.a : any +>this : any +>a : any +>10 : 10 + +this.a; +>this.a : any +>this : any +>a : any + +a; +>a : any + +=== tests/cases/conformance/salsa/b.js === +this.a; +>this.a : any +>this : any +>a : any + +a; +>a : any + diff --git a/tests/cases/conformance/salsa/topLevelThisAssignment.ts b/tests/cases/conformance/salsa/topLevelThisAssignment.ts new file mode 100644 index 00000000000..162bed0c30f --- /dev/null +++ b/tests/cases/conformance/salsa/topLevelThisAssignment.ts @@ -0,0 +1,10 @@ +// @out: output.js +// @allowJs: true +// @Filename: a.js +this.a = 10; +this.a; +a; + +// @Filename: b.js +this.a; +a; From ccd6a010e0218fc9d585ac4dec2a5c42ecdaf734 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 12:56:30 -0700 Subject: [PATCH 16/75] completions: Use keywordForNode helper instead of .getText() (#22751) --- src/services/completions.ts | 59 +++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 32 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index a51452ac879..d7eb2e2d277 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1380,10 +1380,10 @@ namespace ts.Completions { } // Previous token may have been a keyword that was converted to an identifier. - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": + switch (keywordForNode(previousToken)) { + case SyntaxKind.PublicKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.PrivateKeyword: return true; } } @@ -1547,8 +1547,8 @@ namespace ts.Completions { const classElement = contextToken.parent; const classElementModifierFlags = (isClassElement(classElement) ? getModifierFlags(classElement) : ModifierFlags.None) - // If this is context token is not something we are editing now, consider if this would lead to be modifier - | (isIdentifier(contextToken) && !isCurrentlyEditingNode(contextToken) ? modifierToFlag(contextToken.originalKeywordKind) : ModifierFlags.None); + // If this context token is not something we are editing now, consider if this would lead to be modifier + | (!isCurrentlyEditingNode(contextToken) ? modifierToFlag(keywordForNode(contextToken)) : ModifierFlags.None); // No member list for private methods if (classElementModifierFlags & ModifierFlags.Private) return GlobalsSearch.Success; @@ -1808,8 +1808,7 @@ namespace ts.Completions { // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here - if (isClassMemberCompletionKeywordText(contextToken.getText()) && - isFromObjectTypeDeclaration(contextToken)) { + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; } @@ -1819,29 +1818,29 @@ namespace ts.Completions { // - its name of the parameter and not being edited // eg. constructor(a |<- this shouldnt show completion if (!isIdentifier(contextToken) || - isConstructorParameterCompletionKeywordText(contextToken.getText()) || + isConstructorParameterCompletionKeyword(keywordForNode(contextToken)) || isCurrentlyEditingNode(contextToken)) { return false; } } // Previous token may have been a keyword that was converted to an identifier. - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": + switch (keywordForNode(contextToken)) { + case SyntaxKind.AbstractKeyword: + case SyntaxKind.AsyncKeyword: + case SyntaxKind.ClassKeyword: + case SyntaxKind.ConstKeyword: + case SyntaxKind.DeclareKeyword: + case SyntaxKind.EnumKeyword: + case SyntaxKind.FunctionKeyword: + case SyntaxKind.InterfaceKeyword: + case SyntaxKind.LetKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.PublicKeyword: + case SyntaxKind.StaticKeyword: + case SyntaxKind.VarKeyword: + case SyntaxKind.YieldKeyword: return true; } @@ -2027,7 +2026,7 @@ namespace ts.Completions { } function isCurrentlyEditingNode(node: Node): boolean { - return node.getStart() <= position && position <= node.getEnd(); + return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } @@ -2128,8 +2127,8 @@ namespace ts.Completions { } } - function isClassMemberCompletionKeywordText(text: string) { - return isClassMemberCompletionKeyword(stringToToken(text)); + function keywordForNode(node: Node): SyntaxKind { + return isIdentifier(node) ? node.originalKeywordKind || SyntaxKind.Unknown : node.kind; } function isConstructorParameterCompletionKeyword(kind: SyntaxKind) { @@ -2142,10 +2141,6 @@ namespace ts.Completions { } } - function isConstructorParameterCompletionKeywordText(text: string) { - return isConstructorParameterCompletionKeyword(stringToToken(text)); - } - function isFunctionLikeBodyCompletionKeyword(kind: SyntaxKind) { switch (kind) { case SyntaxKind.PublicKeyword: From 21cd68dd04ff62238d05a9ca2832d61bfc83201a Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 13:05:41 -0700 Subject: [PATCH 17/75] Test for isNewIdentifierLocation, and make true for type with index signature (#22910) --- src/harness/fourslash.ts | 4 ++-- src/services/completions.ts | 2 ++ tests/cases/fourslash/completionForStringLiteral7.ts | 8 +++++--- ...mpletionListInClosedObjectTypeLiteralInSignature04.ts | 8 +------- tests/cases/fourslash/completionListInImportClause05.ts | 2 +- tests/cases/fourslash/completionListInImportClause06.ts | 2 +- ...letionListInUnclosedObjectTypeLiteralInSignature04.ts | 2 +- .../cases/fourslash/completionListInvalidMemberNames.ts | 3 ++- .../completionListWithModulesInsideModuleScope.ts | 4 ++-- tests/cases/fourslash/completionsInterfaceElement.ts | 2 +- tests/cases/fourslash/completionsJsPropertyAssignment.ts | 3 ++- tests/cases/fourslash/completionsJsdocTypeTagCast.ts | 2 +- tests/cases/fourslash/completionsPaths.ts | 9 +++++---- tests/cases/fourslash/completionsPaths_pathMapping.ts | 4 ++-- .../completionsPaths_pathMapping_parentDirectory.ts | 2 +- .../completionsPaths_pathMapping_relativePath.ts | 2 +- .../fourslash/completionsPaths_pathMapping_topLevel.ts | 2 +- .../completionsStringLiteral_fromTypeConstraint.ts | 3 ++- tests/cases/fourslash/completionsUnion.ts | 3 ++- 19 files changed, 35 insertions(+), 32 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index f209cafb8a1..7f36e326f57 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -840,8 +840,8 @@ namespace FourSlash { this.raiseError(`No completions at position '${this.currentCaretPosition}'.`); } - if (options && options.isNewIdentifierLocation !== undefined && actualCompletions.isNewIdentifierLocation !== options.isNewIdentifierLocation) { - this.raiseError(`Expected 'isNewIdentifierLocation' to be ${options.isNewIdentifierLocation}, got ${actualCompletions.isNewIdentifierLocation}`); + if (actualCompletions.isNewIdentifierLocation !== (options && options.isNewIdentifierLocation || false)) { + this.raiseError(`Expected 'isNewIdentifierLocation' to be ${options && options.isNewIdentifierLocation}, got ${actualCompletions.isNewIdentifierLocation}`); } const actual = actualCompletions.entries; diff --git a/src/services/completions.ts b/src/services/completions.ts index d7eb2e2d277..c30a302dc09 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1031,6 +1031,8 @@ namespace ts.Completions { } function addTypeProperties(type: Type): void { + isNewIdentifierLocation = !!type.getStringIndexType() || !!type.getNumberIndexType(); + if (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 diff --git a/tests/cases/fourslash/completionForStringLiteral7.ts b/tests/cases/fourslash/completionForStringLiteral7.ts index b2d250ac3fd..6b7bead2a66 100644 --- a/tests/cases/fourslash/completionForStringLiteral7.ts +++ b/tests/cases/fourslash/completionForStringLiteral7.ts @@ -5,6 +5,8 @@ ////function f(x: T, ...args: U[]) { }; ////f("/*1*/", "/*2*/", "/*3*/"); -verify.completionsAt("1", ["foo", "bar"]); -verify.completionsAt("2", ["oof", "rab"]); -verify.completionsAt("3", ["oof", "rab"]); +// TODO: GH#22907 +const options = { isNewIdentifierLocation: true }; +verify.completionsAt("1", ["foo", "bar"], options); +verify.completionsAt("2", ["oof", "rab"], options); +verify.completionsAt("3", ["oof", "rab"], options); diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts index 14ae0e155d8..8674124f05f 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts @@ -7,10 +7,4 @@ //// ////declare function foo(obj: I): { /*1*/ } -goTo.marker("1"); - -verify.not.completionListContains("I"); -verify.not.completionListContains("TString"); -verify.not.completionListContains("TNumber"); -verify.not.completionListContains("foo"); -verify.not.completionListContains("obj"); +verify.completionsAt("1", ["readonly"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInImportClause05.ts b/tests/cases/fourslash/completionListInImportClause05.ts index f7b5244d5a4..2b5d66621dd 100644 --- a/tests/cases/fourslash/completionListInImportClause05.ts +++ b/tests/cases/fourslash/completionListInImportClause05.ts @@ -17,4 +17,4 @@ verify.completionsAt("1", [ { name: "@a/b", replacementSpan }, { name: "@c/d", replacementSpan }, { name: "@e/f", replacementSpan }, -]); +], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInImportClause06.ts b/tests/cases/fourslash/completionListInImportClause06.ts index f6cfefa437f..9336803f7f9 100644 --- a/tests/cases/fourslash/completionListInImportClause06.ts +++ b/tests/cases/fourslash/completionListInImportClause06.ts @@ -14,4 +14,4 @@ // Confirm that entries are de-dup'd. verify.completionsAt("1", [ { name: "@a/b", replacementSpan: test.ranges()[0] }, -]); +], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature04.ts b/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature04.ts index d6746803ab8..5a9731ca0e3 100644 --- a/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature04.ts +++ b/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature04.ts @@ -7,4 +7,4 @@ //// ////declare function foo(obj: I): { /*1*/ -verify.completionsAt("1", ["readonly"]); +verify.completionsAt("1", ["readonly"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInvalidMemberNames.ts b/tests/cases/fourslash/completionListInvalidMemberNames.ts index 3dc54274e83..291ea945b29 100644 --- a/tests/cases/fourslash/completionListInvalidMemberNames.ts +++ b/tests/cases/fourslash/completionListInvalidMemberNames.ts @@ -14,7 +14,8 @@ ////x[|./*a*/|]; ////x["/*b*/"]; -verify.completionsAt("b", ["foo ", "bar", "break", "any", "#", "$", "b", "1b"]); +// TODO: GH#22907 +verify.completionsAt("b", ["foo ", "bar", "break", "any", "#", "$", "b", "1b"], { isNewIdentifierLocation: true }); const replacementSpan = test.ranges()[0]; verify.completionsAt("a", [ diff --git a/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts b/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts index d13141c38cb..682ef9b453e 100644 --- a/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts +++ b/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts @@ -311,7 +311,7 @@ goToMarkAndGeneralVerify('class', { isClassScope: true }); //verify.not.completionListContains('ceVar'); // from interface in mod1 -verify.completionsAt("interface", ["readonly"]); +verify.completionsAt("interface", ["readonly"], { isNewIdentifierLocation: true }); // from namespace in mod1 verifyNamespaceInMod1('namespace'); @@ -348,7 +348,7 @@ verify.not.completionListContains('ceFunc'); verify.not.completionListContains('ceVar'); // from exported interface in mod1 -verify.completionsAt("exportedInterface", ["readonly"]); +verify.completionsAt("exportedInterface", ["readonly"], { isNewIdentifierLocation: true }); // from exported namespace in mod1 verifyExportedNamespace('exportedNamespace'); diff --git a/tests/cases/fourslash/completionsInterfaceElement.ts b/tests/cases/fourslash/completionsInterfaceElement.ts index fe7d55db794..cbf15581dc0 100644 --- a/tests/cases/fourslash/completionsInterfaceElement.ts +++ b/tests/cases/fourslash/completionsInterfaceElement.ts @@ -14,5 +14,5 @@ ////interface EndOfFile { f; /*e*/ for (const marker of test.markerNames()) { - verify.completionsAt(marker, ["readonly"]); + verify.completionsAt(marker, ["readonly"], { isNewIdentifierLocation: true }); } diff --git a/tests/cases/fourslash/completionsJsPropertyAssignment.ts b/tests/cases/fourslash/completionsJsPropertyAssignment.ts index c7e8a9ad268..fa758188ea9 100644 --- a/tests/cases/fourslash/completionsJsPropertyAssignment.ts +++ b/tests/cases/fourslash/completionsJsPropertyAssignment.ts @@ -7,4 +7,5 @@ ////const x = { p: "x" }; ////x.p = "/**/"; -verify.completionsAt("", ["x", "y"]); +// TODO: GH#22907 +verify.completionsAt("", ["x", "y"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsJsdocTypeTagCast.ts b/tests/cases/fourslash/completionsJsdocTypeTagCast.ts index 822069feb53..8cd78103e34 100644 --- a/tests/cases/fourslash/completionsJsdocTypeTagCast.ts +++ b/tests/cases/fourslash/completionsJsdocTypeTagCast.ts @@ -4,4 +4,4 @@ // @Filename: /a.js ////const x = /** @type {{ s: string }} */ ({ /**/ }); -verify.completionsAt("", ["s", "x"]); +verify.completionsAt("", ["s", "x"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths.ts b/tests/cases/fourslash/completionsPaths.ts index 6bb2fb38706..9b485d60ac3 100644 --- a/tests/cases/fourslash/completionsPaths.ts +++ b/tests/cases/fourslash/completionsPaths.ts @@ -24,7 +24,8 @@ ////const foo = require(`x/[|/*4*/|]`); const [r0, r1, r2, r3] = test.ranges(); -verify.completionsAt("1", [{ name: "y", replacementSpan: r0 }, { name: "x", replacementSpan: r0 }]); -verify.completionsAt("2", [{ name: "bar", replacementSpan: r1 }, { name: "foo", replacementSpan: r1 }]); -verify.completionsAt("3", [{ name: "bar", replacementSpan: r2 }, { name: "foo", replacementSpan: r2 }]); -verify.completionsAt("4", [{ name: "bar", replacementSpan: r3 }, { name: "foo", replacementSpan: r3 }]); +const options = { isNewIdentifierLocation: true }; +verify.completionsAt("1", [{ name: "y", replacementSpan: r0 }, { name: "x", replacementSpan: r0 }], options); +verify.completionsAt("2", [{ name: "bar", replacementSpan: r1 }, { name: "foo", replacementSpan: r1 }], options); +verify.completionsAt("3", [{ name: "bar", replacementSpan: r2 }, { name: "foo", replacementSpan: r2 }], options); +verify.completionsAt("4", [{ name: "bar", replacementSpan: r3 }, { name: "foo", replacementSpan: r3 }], options); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping.ts b/tests/cases/fourslash/completionsPaths_pathMapping.ts index 1c222545ae6..200c6d25569 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping.ts @@ -21,5 +21,5 @@ ////} const [r0, r1] = test.ranges(); -verify.completionsAt("0", ["a", "b", "dir"].map(name => ({ name, replacementSpan: r0 }))); -verify.completionsAt("1", ["x"].map(name => ({ name, replacementSpan: r1 }))); +verify.completionsAt("0", ["a", "b", "dir"].map(name => ({ name, replacementSpan: r0 })), { isNewIdentifierLocation: true }); +verify.completionsAt("1", ["x"].map(name => ({ name, replacementSpan: r1 })), { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts b/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts index 7dcd6e3adb1..6736256cc0f 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts @@ -17,4 +17,4 @@ ////} const [replacementSpan] = test.ranges(); -verify.completionsAt("", [{ name: "x", replacementSpan }]); +verify.completionsAt("", [{ name: "x", replacementSpan }], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts b/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts index c24d3690298..659d3352755 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts @@ -20,4 +20,4 @@ ////} const [replacementSpan] = test.ranges(); -verify.completionsAt("", ["a", "b"].map(name => ({ name, replacementSpan }))); +verify.completionsAt("", ["a", "b"].map(name => ({ name, replacementSpan })), { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts b/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts index 963851f5bc6..b99d6be4ca9 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts @@ -14,4 +14,4 @@ ////} const [replacementSpan] = test.ranges(); -verify.completionsAt("", ["src", "foo/"].map(name => ({ name, replacementSpan }))); +verify.completionsAt("", ["src", "foo/"].map(name => ({ name, replacementSpan })), { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts b/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts index cb3f1a31fe2..18941eb35ea 100644 --- a/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts +++ b/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts @@ -3,4 +3,5 @@ ////interface Foo { foo: string; bar: string; } ////type T = Pick; -verify.completionsAt("", ["foo", "bar"]); +// TODO: GH#22907 +verify.completionsAt("", ["foo", "bar"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsUnion.ts b/tests/cases/fourslash/completionsUnion.ts index d9d1d3c792f..4ee701dddbe 100644 --- a/tests/cases/fourslash/completionsUnion.ts +++ b/tests/cases/fourslash/completionsUnion.ts @@ -7,4 +7,5 @@ // We specifically filter out any array-like types. // Private members will be excluded by `createUnionOrIntersectionProperty`. -verify.completionsAt("", ["x"]); +// TODO: GH#22907 +verify.completionsAt("", ["x"], { isNewIdentifierLocation: true }); From 0a2c160dd1b7fa55cb859ddf0085d790e53287fd Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 13:35:48 -0700 Subject: [PATCH 18/75] Debug.failBadSyntaxKind should always be defined and return 'never' (#22091) --- src/compiler/visitor.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 9fccb9ea996..3d3f9fea6ba 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -1546,11 +1546,11 @@ namespace ts { export namespace Debug { let isDebugInfoEnabled = false; - export const failBadSyntaxKind = shouldAssert(AssertionLevel.Normal) - ? (node: Node, message?: string): never => fail( + export function failBadSyntaxKind(node: Node, message?: string): never { + return fail( `${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`, - failBadSyntaxKind) - : noop as () => never; // TODO: GH#22091 + failBadSyntaxKind); + } export const assertEachNode = shouldAssert(AssertionLevel.Normal) ? (nodes: Node[], test: (node: Node) => boolean, message?: string): void => assert( From 6ef4d7774a35cc6ec90033b9d3ffe3bc4b17aecd Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 15:15:50 -0700 Subject: [PATCH 19/75] Always test replacementSpan, and don't provide if it would just be an identifier (#22918) --- src/harness/fourslash.ts | 13 +-- src/services/pathCompletions.ts | 85 +++++++++---------- .../completionForStringLiteralExport.ts | 20 ++--- .../completionForStringLiteralImport1.ts | 21 ++--- .../completionForStringLiteralImport2.ts | 15 +--- ...etionForStringLiteralNonrelativeImport1.ts | 31 ++----- ...etionForStringLiteralNonrelativeImport8.ts | 33 +++---- ...letionForStringLiteralWithDynamicImport.ts | 17 ++-- .../completionListInImportClause05.ts | 9 +- .../completionListInImportClause06.ts | 6 +- tests/cases/fourslash/completionsPaths.ts | 15 ++-- .../fourslash/completionsPaths_pathMapping.ts | 8 +- ...etionsPaths_pathMapping_parentDirectory.ts | 5 +- ...mpletionsPaths_pathMapping_relativePath.ts | 5 +- .../completionsPaths_pathMapping_topLevel.ts | 5 +- tests/cases/fourslash/fourslash.ts | 6 +- ...ashRefPathCompletionBackandForwardSlash.ts | 29 +++---- .../tripleSlashRefPathCompletionHiddenFile.ts | 9 +- .../tripleSlashRefPathCompletionNarrowing.ts | 23 +++-- ...ipleSlashRefPathCompletionRelativePaths.ts | 55 +++--------- 20 files changed, 152 insertions(+), 258 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 7f36e326f57..4e1c44ae01c 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -832,7 +832,12 @@ namespace FourSlash { } } - public verifyCompletionsAt(markerName: string, expected: ReadonlyArray, options?: FourSlashInterface.CompletionsAtOptions) { + public verifyCompletionsAt(markerName: string | ReadonlyArray, expected: ReadonlyArray, options?: FourSlashInterface.CompletionsAtOptions) { + if (typeof markerName !== "string") { + for (const m of markerName) this.verifyCompletionsAt(m, expected, options); + return; + } + this.goToMarker(markerName); const actualCompletions = this.getCompletionListAtCaret(options); @@ -3182,9 +3187,7 @@ Actual: ${stringify(fullActual)}`); eq(item.hasAction, hasAction, "hasAction"); eq(item.isRecommended, options && options.isRecommended, "isRecommended"); eq(item.insertText, options && options.insertText, "insertText"); - if (options && options.replacementSpan) { // TODO: GH#21679 - eq(item.replacementSpan, options && options.replacementSpan && ts.createTextSpanFromRange(options.replacementSpan), "replacementSpan"); - } + eq(item.replacementSpan, options && options.replacementSpan && ts.createTextSpanFromRange(options.replacementSpan), "replacementSpan"); } private findFile(indexOrName: string | number) { @@ -3988,7 +3991,7 @@ namespace FourSlashInterface { super(state); } - public completionsAt(markerName: string, completions: ReadonlyArray, options?: CompletionsAtOptions) { + public completionsAt(markerName: string | ReadonlyArray, completions: ReadonlyArray, options?: CompletionsAtOptions) { this.state.verifyCompletionsAt(markerName, completions, options); } diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index cdf940cdc79..976449efee5 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -5,33 +5,40 @@ namespace ts.Completions.PathCompletions { readonly kind: ScriptElementKind.scriptElement | ScriptElementKind.directory | ScriptElementKind.externalModuleName; } export interface PathCompletion extends NameAndKind { - readonly span: TextSpan; - } - function createPathCompletion(name: string, kind: PathCompletion["kind"], span: TextSpan): PathCompletion { - return { name, kind, span }; + readonly span: TextSpan | undefined; } - export function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): PathCompletion[] { + function nameAndKind(name: string, kind: NameAndKind["kind"]): NameAndKind { + return { name, kind }; + } + function addReplacementSpans(text: string, textStart: number, names: ReadonlyArray): ReadonlyArray { + const span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(({ name, kind }): PathCompletion => ({ name, kind, span })); + } + + export function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker)); + } + + function getStringLiteralCompletionsFromModuleNamesWorker(node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { const literalValue = normalizeSlashes(node.text); const scriptPath = node.getSourceFile().path; const scriptDirectory = getDirectoryPath(scriptPath); - const span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || isRootedDiskPath(literalValue)) { const extensions = getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs( - compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); + compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment( - literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); } } else { // Check for node modules - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } @@ -54,15 +61,15 @@ namespace ts.Completions.PathCompletions { compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptPath: string, extensions: ReadonlyArray, includeExtensions: boolean, span: TextSpan, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude?: string): PathCompletion[] { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptPath: string, extensions: ReadonlyArray, includeExtensions: boolean, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude?: string): NameAndKind[] { const basePath = compilerOptions.project || host.getCurrentDirectory(); const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); - const result: PathCompletion[] = []; + const result: NameAndKind[] = []; for (const baseDirectory of baseDirectories) { - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, host, exclude, result); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); } return result; @@ -71,7 +78,7 @@ namespace ts.Completions.PathCompletions { /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment: string, scriptPath: string, extensions: ReadonlyArray, includeExtensions: boolean, span: TextSpan, host: LanguageServiceHost, exclude?: string, result: PathCompletion[] = []): PathCompletion[] { + function getCompletionEntriesForDirectoryFragment(fragment: string, scriptPath: string, extensions: ReadonlyArray, includeExtensions: boolean, host: LanguageServiceHost, exclude?: string, result: NameAndKind[] = []): NameAndKind[] { if (fragment === undefined) { fragment = ""; } @@ -120,7 +127,7 @@ namespace ts.Completions.PathCompletions { } forEachKey(foundFiles, foundFile => { - result.push(createPathCompletion(foundFile, ScriptElementKind.scriptElement, span)); + result.push(nameAndKind(foundFile, ScriptElementKind.scriptElement)); }); } @@ -131,7 +138,7 @@ namespace ts.Completions.PathCompletions { for (const directory of directories) { const directoryName = getBaseFileName(normalizePath(directory)); - result.push(createPathCompletion(directoryName, ScriptElementKind.directory, span)); + result.push(nameAndKind(directoryName, ScriptElementKind.directory)); } } } @@ -146,16 +153,16 @@ namespace ts.Completions.PathCompletions { * 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: string, scriptPath: string, span: TextSpan, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): PathCompletion[] { + function getCompletionEntriesForNonRelativeModules(fragment: string, scriptPath: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): NameAndKind[] { const { baseUrl, paths } = compilerOptions; - const result: PathCompletion[] = []; + const result: NameAndKind[] = []; const fileExtensions = getSupportedExtensions(compilerOptions); if (baseUrl) { const projectDir = compilerOptions.project || host.getCurrentDirectory(); const absolute = isRootedDiskPath(baseUrl) ? baseUrl : combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); for (const path in paths) { const patterns = paths[path]; @@ -163,7 +170,7 @@ namespace ts.Completions.PathCompletions { for (const { name, kind } 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 === name)) { - result.push(createPathCompletion(name, kind, span)); + result.push(nameAndKind(name, kind)); } } } @@ -174,15 +181,15 @@ namespace ts.Completions.PathCompletions { forEachAncestorDirectory(scriptPath, ancestor => { const nodeModules = combinePaths(ancestor, "node_modules"); if (host.directoryExists(nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); } }); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); for (const moduleName of enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host)) { - result.push(createPathCompletion(moduleName, ScriptElementKind.externalModuleName, span)); + result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName)); } return result; @@ -296,7 +303,7 @@ namespace ts.Completions.PathCompletions { return deduplicate(nonRelativeModuleNames, equateStringsCaseSensitive, compareStringsCaseSensitive); } - export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): PathCompletion[] | undefined { + export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): ReadonlyArray | undefined { const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); const range = commentRanges && find(commentRanges, commentRange => position >= commentRange.pos && position <= commentRange.end); @@ -311,23 +318,13 @@ namespace ts.Completions.PathCompletions { const [, prefix, kind, toComplete] = match; const scriptPath = getDirectoryPath(sourceFile.path); - switch (kind) { - case "path": { - // Give completions for a relative path - const span = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span, host, sourceFile.path); - } - case "types": { - // Give completions based on the typings available - const span = createTextSpan(range.pos + prefix.length, match[0].length - prefix.length); - return getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span); - } - default: - return undefined; - } + const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) + : undefined; + return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); } - function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, span: TextSpan, result: PathCompletion[] = []): PathCompletion[] { + function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, result: NameAndKind[] = []): NameAndKind[] { // Check for typings specified in compiler options const seen = createMap(); if (options.types) { @@ -375,7 +372,7 @@ namespace ts.Completions.PathCompletions { function pushResult(moduleName: string) { if (!seen.has(moduleName)) { - result.push(createPathCompletion(moduleName, ScriptElementKind.externalModuleName, span)); + result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName)); seen.set(moduleName, true); } } @@ -445,10 +442,12 @@ namespace ts.Completions.PathCompletions { } // Replace everything after the last directory seperator that appears - function getDirectoryFragmentTextSpan(text: string, textStart: number): TextSpan { - const index = text.lastIndexOf(directorySeparator); + function getDirectoryFragmentTextSpan(text: string, textStart: number): TextSpan | undefined { + const index = Math.max(text.lastIndexOf(directorySeparator), text.lastIndexOf("\\")); const offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; + // If the range is an identifier, span is unnecessary. + const length = text.length - offset; + return length === 0 || isIdentifierText(text.substr(offset, length), ScriptTarget.ESNext) ? undefined : createTextSpan(textStart + offset, length); } // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) diff --git a/tests/cases/fourslash/completionForStringLiteralExport.ts b/tests/cases/fourslash/completionForStringLiteralExport.ts index 649148bb15d..9239f6173fa 100644 --- a/tests/cases/fourslash/completionForStringLiteralExport.ts +++ b/tests/cases/fourslash/completionForStringLiteralExport.ts @@ -7,7 +7,7 @@ // @Filename: test.ts //// export * from "./some/*0*/ //// export * from "./sub/some/*1*/"; -//// export * from "some-/*2*/"; +//// export * from "[|some-/*2*/|]"; //// export * from "..//*3*/"; //// export {} from ".//*4*/"; @@ -21,17 +21,7 @@ // @Filename: my_typings/some-module/index.d.ts //// export var x = 9; -goTo.marker("0"); -verify.completionListContains("someFile1"); - -goTo.marker("1"); -verify.completionListContains("someFile2"); - -goTo.marker("2"); -verify.completionListContains("some-module"); - -goTo.marker("3"); -verify.completionListContains("fourslash"); - -goTo.marker("4"); -verify.completionListContains("someFile1"); +verify.completionsAt(["0", "4"], ["someFile1", "sub", "my_typings"], { isNewIdentifierLocation: true }); +verify.completionsAt("1", ["someFile2"], { isNewIdentifierLocation: true }); +verify.completionsAt("2", [{ name: "some-module", replacementSpan: test.ranges()[0] }], { isNewIdentifierLocation: true }); +verify.completionsAt("3", ["fourslash"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralImport1.ts b/tests/cases/fourslash/completionForStringLiteralImport1.ts index 4cdee889538..c0c20eb3df8 100644 --- a/tests/cases/fourslash/completionForStringLiteralImport1.ts +++ b/tests/cases/fourslash/completionForStringLiteralImport1.ts @@ -5,10 +5,10 @@ // @typeRoots: my_typings // @Filename: test.ts -//// import * as foo0 from "./[|some|]/*0*/ -//// import * as foo1 from "./sub/[|some|]/*1*/ +//// import * as foo0 from "./some/*0*/ +//// import * as foo1 from "./sub/some/*1*/ //// import * as foo2 from "[|some-|]/*2*/" -//// import * as foo3 from "../[||]/*3*/"; +//// import * as foo3 from "..//*3*/"; // @Filename: someFile1.ts @@ -20,14 +20,7 @@ // @Filename: my_typings/some-module/index.d.ts //// export var x = 9; -goTo.marker("0"); -verify.completionListContains("someFile1", undefined, undefined, undefined, 0); - -goTo.marker("1"); -verify.completionListContains("someFile2", undefined, undefined, undefined, 1); - -goTo.marker("2"); -verify.completionListContains("some-module", undefined, undefined, undefined, 2); - -goTo.marker("3"); -verify.completionListContains("fourslash", undefined, undefined, undefined, 3); \ No newline at end of file +verify.completionsAt("0", ["someFile1", "sub", "my_typings"], { isNewIdentifierLocation: true }); +verify.completionsAt("1", ["someFile2"], { isNewIdentifierLocation: true }); +verify.completionsAt("2", [{ name: "some-module", replacementSpan: test.ranges()[0] }], { isNewIdentifierLocation: true }); +verify.completionsAt("3", ["fourslash"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralImport2.ts b/tests/cases/fourslash/completionForStringLiteralImport2.ts index 25de3d2240a..6c73becedc5 100644 --- a/tests/cases/fourslash/completionForStringLiteralImport2.ts +++ b/tests/cases/fourslash/completionForStringLiteralImport2.ts @@ -20,14 +20,7 @@ // @Filename: my_typings/some-module/index.d.ts //// export var x = 9; -goTo.marker("0"); -verify.completionListContains("someFile.ts", undefined, undefined, undefined, 0); - -goTo.marker("1"); -verify.completionListContains("some-module", undefined, undefined, undefined, 1); - -goTo.marker("2"); -verify.completionListContains("someOtherFile.ts", undefined, undefined, undefined, 2); - -goTo.marker("3"); -verify.completionListContains("some-module", undefined, undefined, undefined, 3); \ No newline at end of file +verify.completionsAt("0", ["someFile.ts", "sub", "my_typings"], { isNewIdentifierLocation: true }); +verify.completionsAt("1", ["some-module"], { isNewIdentifierLocation: true }); +verify.completionsAt("2", ["someOtherFile.ts"], { isNewIdentifierLocation: true }); +verify.completionsAt("3", ["some-module"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport1.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport1.ts index c0e5ebbcd90..ad45719caea 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport1.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport1.ts @@ -5,15 +5,15 @@ // @Filename: tests/test0.ts //// import * as foo1 from "f/*import_as0*/ //// import * as foo2 from "fake-module//*import_as1*/ -//// import * as foo3 from "fake-module/*import_as2*/ +//// import * as foo3 from "[|fake-module/*import_as2*/|] //// import foo4 = require("f/*import_equals0*/ //// import foo5 = require("fake-module//*import_equals1*/ -//// import foo6 = require("fake-module/*import_equals2*/ +//// import foo6 = require("[|fake-module/*import_equals2*/|] //// var foo7 = require("f/*require0*/ //// var foo8 = require("fake-module//*require1*/ -//// var foo9 = require("fake-module/*require2*/ +//// var foo9 = require("[|fake-module/*require2*/|] // @Filename: package.json //// { "dependencies": { "fake-module": "latest" }, "devDependencies": { "fake-module-dev": "latest" } } @@ -41,23 +41,8 @@ // @Filename: node_modules/unlisted-module/index.ts //// /*unlisted-module*/ -const kinds = ["import_as", "import_equals", "require"]; - -for (const kind of kinds) { - goTo.marker(kind + "0"); - verify.completionListContains("fake-module"); - verify.completionListContains("fake-module-dev"); - verify.not.completionListItemsCountIsGreaterThan(2); - - goTo.marker(kind + "1"); - verify.completionListContains("index"); - verify.completionListContains("ts"); - verify.completionListContains("dts"); - verify.completionListContains("tsx"); - verify.not.completionListItemsCountIsGreaterThan(4); - - goTo.marker(kind + "2"); - verify.completionListContains("fake-module"); - verify.completionListContains("fake-module-dev"); - verify.not.completionListItemsCountIsGreaterThan(2); -} \ No newline at end of file +["import_as", "import_equals", "require"].forEach((kind, i) => { + verify.completionsAt(`${kind}0`, ["fake-module", "fake-module-dev"], { isNewIdentifierLocation: true }); + verify.completionsAt(`${kind}1`, ["dts", "index", "ts", "tsx"], { isNewIdentifierLocation: true }); + verify.completionsAt(`${kind}2`, ["fake-module", "fake-module-dev"].map(name => ({ name, replacementSpan: test.ranges()[i] })), { isNewIdentifierLocation: true }); +}); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport8.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport8.ts index 603e8d1104d..9a0b34ab7fb 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport8.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport8.ts @@ -18,17 +18,17 @@ // @Filename: tests/test0.ts -//// import * as foo1 from "0/*import_as0*/ -//// import foo2 = require("0/*import_equals0*/ -//// var foo3 = require("0/*require0*/ +//// import * as foo1 from "f/*import_as0*/ +//// import foo2 = require("f/*import_equals0*/ +//// var foo3 = require("f/*require0*/ -//// import * as foo1 from "1/*import_as1*/ -//// import foo2 = require("1/*import_equals1*/ -//// var foo3 = require("1/*require1*/ +//// import * as foo1 from "f/*import_as1*/ +//// import foo2 = require("f/*import_equals1*/ +//// var foo3 = require("f/*require1*/ -//// import * as foo1 from "2/*import_as2*/ -//// import foo2 = require("2/*import_equals2*/ -//// var foo3 = require("2/*require2*/ +//// import * as foo1 from "f/*import_as2*/ +//// import foo2 = require("f/*import_equals2*/ +//// var foo3 = require("f/*require2*/ // @Filename: modules/prefix/00test/suffix.ts @@ -40,16 +40,5 @@ // @Filename: modules/2test/suffix-only.ts //// export var z = 5; - -const kinds = ["import_as", "import_equals", "require"]; - -for (const kind of kinds) { - goTo.marker(kind + "0"); - verify.completionListContains("0test"); - - goTo.marker(kind + "1"); - verify.completionListContains("1test"); - - goTo.marker(kind + "2"); - verify.completionListContains("2test"); -} +const markers = ts.flatMap(["import_as", "import_equals", "require"], a => [`${a}0`, `${a}1`, `${a}2`]); +verify.completionsAt(markers, ["prefix", "prefix-only", "2test", "0test", "1test"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralWithDynamicImport.ts b/tests/cases/fourslash/completionForStringLiteralWithDynamicImport.ts index 8e823991c0b..3343eb38749 100644 --- a/tests/cases/fourslash/completionForStringLiteralWithDynamicImport.ts +++ b/tests/cases/fourslash/completionForStringLiteralWithDynamicImport.ts @@ -7,7 +7,7 @@ // @Filename: test.ts //// const a = import("./some/*0*/ //// const a = import("./sub/some/*1*/"); -//// const a = import("some-/*2*/"); +//// const a = import("[|some-/*2*/|]"); //// const a = import("..//*3*/"); @@ -20,14 +20,7 @@ // @Filename: my_typings/some-module/index.d.ts //// export var x = 9; -goTo.marker("0"); -verify.completionListContains("someFile1"); - -goTo.marker("1"); -verify.completionListContains("someFile2"); - -goTo.marker("2"); -verify.completionListContains("some-module"); - -goTo.marker("3"); -verify.completionListContains("fourslash"); +verify.completionsAt("0", ["someFile1", "sub", "my_typings"], { isNewIdentifierLocation: true }); +verify.completionsAt("1", ["someFile2"], { isNewIdentifierLocation: true }); +verify.completionsAt("2", [{ name: "some-module", replacementSpan: test.ranges()[0] }], { isNewIdentifierLocation: true }); +verify.completionsAt("3", ["fourslash"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInImportClause05.ts b/tests/cases/fourslash/completionListInImportClause05.ts index 2b5d66621dd..40eda68bb82 100644 --- a/tests/cases/fourslash/completionListInImportClause05.ts +++ b/tests/cases/fourslash/completionListInImportClause05.ts @@ -1,7 +1,7 @@ /// // @Filename: app.ts -////import * as A from "[|/*1*/|]"; +////import * as A from "/*1*/"; // @Filename: /node_modules/@types/a__b/index.d.ts ////declare module "@e/f" { function fun(): string; } @@ -12,9 +12,4 @@ // NOTE: The node_modules folder is in "/", rather than ".", because it requires // less scaffolding to mock. In particular, "/" is where we look for type roots. -const [replacementSpan] = test.ranges(); -verify.completionsAt("1", [ - { name: "@a/b", replacementSpan }, - { name: "@c/d", replacementSpan }, - { name: "@e/f", replacementSpan }, -], { isNewIdentifierLocation: true }); +verify.completionsAt("1", ["@a/b", "@c/d", "@e/f"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInImportClause06.ts b/tests/cases/fourslash/completionListInImportClause06.ts index 9336803f7f9..3dfcea3cdbf 100644 --- a/tests/cases/fourslash/completionListInImportClause06.ts +++ b/tests/cases/fourslash/completionListInImportClause06.ts @@ -3,7 +3,7 @@ // @typeRoots: T1,T2 // @Filename: app.ts -////import * as A from "[|/*1*/|]"; +////import * as A from "/*1*/"; // @Filename: T1/a__b/index.d.ts ////export declare let x: number; @@ -12,6 +12,4 @@ ////export declare let x: number; // Confirm that entries are de-dup'd. -verify.completionsAt("1", [ - { name: "@a/b", replacementSpan: test.ranges()[0] }, -], { isNewIdentifierLocation: true }); +verify.completionsAt("1", ["@a/b"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths.ts b/tests/cases/fourslash/completionsPaths.ts index 9b485d60ac3..47e4918b410 100644 --- a/tests/cases/fourslash/completionsPaths.ts +++ b/tests/cases/fourslash/completionsPaths.ts @@ -12,20 +12,17 @@ ////not read // @Filename: /src/a.ts -////import {} from "[|/*1*/|]"; +////import {} from "/*1*/"; // @Filename: /src/folder/b.ts -////import {} from "x/[|/*2*/|]"; +////import {} from "x//*2*/"; // @Filename: /src/folder/c.ts -////const foo = require("x/[|/*3*/|]"); +////const foo = require("x//*3*/"); // @Filename: /src/folder/4.ts -////const foo = require(`x/[|/*4*/|]`); +////const foo = require(`x//*4*/`); const [r0, r1, r2, r3] = test.ranges(); -const options = { isNewIdentifierLocation: true }; -verify.completionsAt("1", [{ name: "y", replacementSpan: r0 }, { name: "x", replacementSpan: r0 }], options); -verify.completionsAt("2", [{ name: "bar", replacementSpan: r1 }, { name: "foo", replacementSpan: r1 }], options); -verify.completionsAt("3", [{ name: "bar", replacementSpan: r2 }, { name: "foo", replacementSpan: r2 }], options); -verify.completionsAt("4", [{ name: "bar", replacementSpan: r3 }, { name: "foo", replacementSpan: r3 }], options); +verify.completionsAt("1", ["y", "x"], { isNewIdentifierLocation: true }); +verify.completionsAt(["2", "3", "4"], ["bar", "foo"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping.ts b/tests/cases/fourslash/completionsPaths_pathMapping.ts index 200c6d25569..c6c879dc97e 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping.ts @@ -7,8 +7,8 @@ /////export const x = 0; // @Filename: /src/a.ts -////import {} from "foo/[|/*0*/|]"; -////import {} from "foo/dir/[|/*1*/|]"; +////import {} from "foo//*0*/"; +////import {} from "foo/dir//*1*/"; // @Filename: /tsconfig.json ////{ @@ -21,5 +21,5 @@ ////} const [r0, r1] = test.ranges(); -verify.completionsAt("0", ["a", "b", "dir"].map(name => ({ name, replacementSpan: r0 })), { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["x"].map(name => ({ name, replacementSpan: r1 })), { isNewIdentifierLocation: true }); +verify.completionsAt("0", ["a", "b", "dir"], { isNewIdentifierLocation: true }); +verify.completionsAt("1", ["x"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts b/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts index 6736256cc0f..71d07052318 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts @@ -1,7 +1,7 @@ /// // @Filename: /src/a.ts -////import { } from "foo/[|/**/|]"; +////import { } from "foo//**/"; // @Filename: /oof/x.ts ////export const x = 0; @@ -16,5 +16,4 @@ //// } ////} -const [replacementSpan] = test.ranges(); -verify.completionsAt("", [{ name: "x", replacementSpan }], { isNewIdentifierLocation: true }); +verify.completionsAt("", ["x"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts b/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts index 659d3352755..a9af29cd6e7 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts @@ -7,7 +7,7 @@ ////export const x = 0; // @Filename: /x/a.ts -////import { } from "foo/[|/**/|]"; +////import { } from "foo//**/"; // @Filename: /x/tsconfig.json ////{ @@ -19,5 +19,4 @@ //// } ////} -const [replacementSpan] = test.ranges(); -verify.completionsAt("", ["a", "b"].map(name => ({ name, replacementSpan })), { isNewIdentifierLocation: true }); +verify.completionsAt("", ["a", "b"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts b/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts index b99d6be4ca9..449ff3f65bd 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts @@ -1,7 +1,7 @@ /// // @Filename: /x/src/a.ts -////import {} from "[|/**/|]"; +////import {} from "/**/"; // @Filename: /x/tsconfig.json ////{ @@ -13,5 +13,4 @@ //// } ////} -const [replacementSpan] = test.ranges(); -verify.completionsAt("", ["src", "foo/"].map(name => ({ name, replacementSpan })), { isNewIdentifierLocation: true }); +verify.completionsAt("", ["src", "foo/"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 14d89cc418f..60ccbf8963a 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -71,6 +71,10 @@ declare module ts { } } +declare namespace ts { + function flatMap(array: ReadonlyArray, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[]; +} + declare namespace FourSlashInterface { interface Marker { fileName: string; @@ -196,7 +200,7 @@ declare namespace FourSlashInterface { class verify extends verifyNegatable { assertHasRanges(ranges: Range[]): void; caretAtMarker(markerName?: string): void; - completionsAt(markerName: string, completions: ReadonlyArray, options?: CompletionsAtOptions): void; + completionsAt(markerName: string | ReadonlyArray, completions: ReadonlyArray, options?: CompletionsAtOptions): void; completionsAndDetailsAt( markerName: string, completions: { diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts index 2ec394e1dc8..e25521ed812 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts @@ -15,37 +15,37 @@ //// /// ({ name, replacementSpan: test.ranges()[offset / 4] })), { isNewIdentifierLocation: true }); } diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionHiddenFile.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionHiddenFile.ts index fffd310bfeb..2f5792b580d 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionHiddenFile.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionHiddenFile.ts @@ -9,12 +9,9 @@ // @Filename: test.ts //// /// ({ name, replacementSpan: test.ranges()[idx] })), { isNewIdentifierLocation: true }); +} diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionRelativePaths.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionRelativePaths.ts index ba6af8735f8..a67310d0349 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionRelativePaths.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionRelativePaths.ts @@ -17,8 +17,8 @@ // @Filename: d1/d2/test.ts //// /// ({ name, replacementSpan: test.ranges()[0] })), { isNewIdentifierLocation: true }); +verify.completionsAt("3", ["h.ts", "d3"].map(name => ({ name, replacementSpan: test.ranges()[1] })), { isNewIdentifierLocation: true }); -function workingDirCompletions() { - for (let m = 0; m < 5; ++m) { - goTo.marker("" + m); - verify.completionListContains("h.ts"); - verify.completionListContains("d3"); - verify.not.completionListItemsCountIsGreaterThan(2); - } -} +// parent dir completions +verify.completionsAt(["5", "6"], ["g.ts", "d2"], { isNewIdentifierLocation: true }); +verify.completionsAt("7", ["f.ts", "d1"], { isNewIdentifierLocation: true }); -function parentDirCompletions() { - - for (let m of ["5", "6"]) { - goTo.marker(m); - verify.completionListContains("g.ts"); - verify.completionListContains("d2"); - verify.not.completionListItemsCountIsGreaterThan(2); - } - - goTo.marker("7"); - verify.completionListContains("f.ts"); - verify.completionListContains("d1"); - verify.not.completionListItemsCountIsGreaterThan(2); -} - -function childDirCompletions() { - - for (let m of ["8", "9"]) { - goTo.marker(m); - verify.completionListContains("i.ts"); - verify.completionListContains("d4"); - verify.not.completionListItemsCountIsGreaterThan(2); - } - - for (let m of ["10", "11"]) { - goTo.marker(m); - verify.completionListContains("j.ts"); - verify.not.completionListItemsCountIsGreaterThan(1); - } -} \ No newline at end of file +// child dir completions +verify.completionsAt(["8", "9"], ["i.ts", "d4"], { isNewIdentifierLocation: true }); +verify.completionsAt(["10", "11"], ["j.ts"], { isNewIdentifierLocation: true }); From 1db769d566f81316372cadd6f7b872b1f2efed94 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 27 Mar 2018 15:16:56 -0700 Subject: [PATCH 20/75] Transform setter bodies if they contain es2015 (#22931) --- src/compiler/transformers/es2015.ts | 19 ++++++++---------- ...s5SetterparameterDestructuringNotElided.js | 16 +++++++++++++++ ...terparameterDestructuringNotElided.symbols | 17 ++++++++++++++++ ...etterparameterDestructuringNotElided.types | 20 +++++++++++++++++++ ...s5SetterparameterDestructuringNotElided.ts | 7 +++++++ 5 files changed, 68 insertions(+), 11 deletions(-) create mode 100644 tests/baselines/reference/es5SetterparameterDestructuringNotElided.js create mode 100644 tests/baselines/reference/es5SetterparameterDestructuringNotElided.symbols create mode 100644 tests/baselines/reference/es5SetterparameterDestructuringNotElided.types create mode 100644 tests/cases/compiler/es5SetterparameterDestructuringNotElided.ts diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 53b2152bd05..f9cb9ac87a8 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -1922,7 +1922,7 @@ namespace ts { return block; } - function visitFunctionBodyDownLevel(node: FunctionDeclaration | FunctionExpression) { + function visitFunctionBodyDownLevel(node: FunctionDeclaration | FunctionExpression | AccessorDeclaration) { const updated = visitFunctionBody(node.body, functionBodyVisitor, context); return updateBlock( updated, @@ -3196,18 +3196,15 @@ namespace ts { convertedLoopState = undefined; const ancestorFacts = enterSubtree(HierarchyFacts.FunctionExcludes, HierarchyFacts.FunctionIncludes); let updated: AccessorDeclaration; - if (node.transformFlags & TransformFlags.ContainsCapturedLexicalThis) { - const parameters = visitParameterList(node.parameters, visitor, context); - const body = transformFunctionBody(node); - if (node.kind === SyntaxKind.GetAccessor) { - updated = updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); - } - else { - updated = updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); - } + const parameters = visitParameterList(node.parameters, visitor, context); + const body = node.transformFlags & (TransformFlags.ContainsCapturedLexicalThis | TransformFlags.ContainsES2015) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === SyntaxKind.GetAccessor) { + updated = updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { - updated = visitEachChild(node, visitor, context); + updated = updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, HierarchyFacts.PropagateNewTargetMask, HierarchyFacts.None); convertedLoopState = savedConvertedLoopState; diff --git a/tests/baselines/reference/es5SetterparameterDestructuringNotElided.js b/tests/baselines/reference/es5SetterparameterDestructuringNotElided.js new file mode 100644 index 00000000000..4fcc7cc3888 --- /dev/null +++ b/tests/baselines/reference/es5SetterparameterDestructuringNotElided.js @@ -0,0 +1,16 @@ +//// [es5SetterparameterDestructuringNotElided.ts] +const foo = { + set foo([start, end]: [any, any]) { + void start; + void end; + }, +}; + +//// [es5SetterparameterDestructuringNotElided.js] +var foo = { + set foo(_a) { + var start = _a[0], end = _a[1]; + void start; + void end; + }, +}; diff --git a/tests/baselines/reference/es5SetterparameterDestructuringNotElided.symbols b/tests/baselines/reference/es5SetterparameterDestructuringNotElided.symbols new file mode 100644 index 00000000000..e5abe49aa03 --- /dev/null +++ b/tests/baselines/reference/es5SetterparameterDestructuringNotElided.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/es5SetterparameterDestructuringNotElided.ts === +const foo = { +>foo : Symbol(foo, Decl(es5SetterparameterDestructuringNotElided.ts, 0, 5)) + + set foo([start, end]: [any, any]) { +>foo : Symbol(foo, Decl(es5SetterparameterDestructuringNotElided.ts, 0, 13)) +>start : Symbol(start, Decl(es5SetterparameterDestructuringNotElided.ts, 1, 13)) +>end : Symbol(end, Decl(es5SetterparameterDestructuringNotElided.ts, 1, 19)) + + void start; +>start : Symbol(start, Decl(es5SetterparameterDestructuringNotElided.ts, 1, 13)) + + void end; +>end : Symbol(end, Decl(es5SetterparameterDestructuringNotElided.ts, 1, 19)) + + }, +}; diff --git a/tests/baselines/reference/es5SetterparameterDestructuringNotElided.types b/tests/baselines/reference/es5SetterparameterDestructuringNotElided.types new file mode 100644 index 00000000000..ae58debaebc --- /dev/null +++ b/tests/baselines/reference/es5SetterparameterDestructuringNotElided.types @@ -0,0 +1,20 @@ +=== tests/cases/compiler/es5SetterparameterDestructuringNotElided.ts === +const foo = { +>foo : { foo: [any, any]; } +>{ set foo([start, end]: [any, any]) { void start; void end; },} : { foo: [any, any]; } + + set foo([start, end]: [any, any]) { +>foo : [any, any] +>start : any +>end : any + + void start; +>void start : undefined +>start : any + + void end; +>void end : undefined +>end : any + + }, +}; diff --git a/tests/cases/compiler/es5SetterparameterDestructuringNotElided.ts b/tests/cases/compiler/es5SetterparameterDestructuringNotElided.ts new file mode 100644 index 00000000000..dd6587e9654 --- /dev/null +++ b/tests/cases/compiler/es5SetterparameterDestructuringNotElided.ts @@ -0,0 +1,7 @@ +// @target: es5 +const foo = { + set foo([start, end]: [any, any]) { + void start; + void end; + }, +}; \ No newline at end of file From 47d768ceb327393f927ec0ef9683a4ec5772a75e Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 15:36:05 -0700 Subject: [PATCH 21/75] Anything after Debug.failBadSyntaxKind is dead code (#22922) --- src/compiler/transformers/es2015.ts | 3 +-- src/compiler/transformers/generators.ts | 3 +-- src/compiler/transformers/jsx.ts | 5 ++--- src/compiler/transformers/ts.ts | 13 ++++--------- 4 files changed, 8 insertions(+), 16 deletions(-) diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index f9cb9ac87a8..17c02052e60 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -1510,8 +1510,7 @@ namespace ts { break; default: - Debug.failBadSyntaxKind(node); - break; + return Debug.failBadSyntaxKind(node); } const captureNewTargetStatement = createVariableStatement( diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 1a4c82020c7..82d8bc513f0 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -430,8 +430,7 @@ namespace ts { return visitFunctionExpression(node); default: - Debug.failBadSyntaxKind(node); - return visitEachChild(node, visitor, context); + return Debug.failBadSyntaxKind(node); } } diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index 25e1ae02ef8..07dc8f74db4 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -72,8 +72,7 @@ namespace ts { return visitJsxFragment(node, /*isChild*/ true); default: - Debug.failBadSyntaxKind(node); - return undefined; + return Debug.failBadSyntaxKind(node); } } @@ -182,7 +181,7 @@ namespace ts { return visitJsxExpression(node); } else { - Debug.failBadSyntaxKind(node); + return Debug.failBadSyntaxKind(node); } } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index ecde841bedd..f22d8f02870 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -324,8 +324,7 @@ namespace ts { return node; default: - Debug.failBadSyntaxKind(node); - return undefined; + return Debug.failBadSyntaxKind(node); } } @@ -531,8 +530,7 @@ namespace ts { return visitImportEqualsDeclaration(node); default: - Debug.failBadSyntaxKind(node); - return visitEachChild(node, visitor, context); + return Debug.failBadSyntaxKind(node); } } @@ -1870,10 +1868,8 @@ namespace ts { return createIdentifier("Boolean"); default: - Debug.failBadSyntaxKind((node).literal); - break; + return Debug.failBadSyntaxKind((node).literal); } - break; case SyntaxKind.NumberKeyword: return createIdentifier("Number"); @@ -1900,8 +1896,7 @@ namespace ts { break; default: - Debug.failBadSyntaxKind(node); - break; + return Debug.failBadSyntaxKind(node); } return createIdentifier("Object"); From 07a890dbbbcd60232c309aa2bf9d993b0c33bbc5 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 16:38:39 -0700 Subject: [PATCH 22/75] Reuse getBinaryOperatorPrecedence (#22844) * Reuse getBinaryOperatorPrecedence * Code review * Consistently sort cases in ascending order --- src/compiler/parser.ts | 51 +-------- src/compiler/utilities.ts | 210 +++++++++++++++++++------------------- 2 files changed, 107 insertions(+), 154 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 6e3ccdb5998..b5c780de934 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -3600,7 +3600,7 @@ namespace ts { // reScanGreaterToken so that we merge token sequences like > and = into >= reScanGreaterToken(); - const newPrecedence = getBinaryOperatorPrecedence(); + const newPrecedence = getBinaryOperatorPrecedence(token()); // Check the precedence to see if we should "take" this operator // - For left associative operator (all operator but **), consume the operator, @@ -3662,52 +3662,7 @@ namespace ts { return false; } - return getBinaryOperatorPrecedence() > 0; - } - - function getBinaryOperatorPrecedence(): number { - switch (token()) { - case SyntaxKind.BarBarToken: - return 1; - case SyntaxKind.AmpersandAmpersandToken: - return 2; - case SyntaxKind.BarToken: - return 3; - case SyntaxKind.CaretToken: - return 4; - case SyntaxKind.AmpersandToken: - return 5; - case SyntaxKind.EqualsEqualsToken: - case SyntaxKind.ExclamationEqualsToken: - case SyntaxKind.EqualsEqualsEqualsToken: - case SyntaxKind.ExclamationEqualsEqualsToken: - return 6; - case SyntaxKind.LessThanToken: - case SyntaxKind.GreaterThanToken: - case SyntaxKind.LessThanEqualsToken: - case SyntaxKind.GreaterThanEqualsToken: - case SyntaxKind.InstanceOfKeyword: - case SyntaxKind.InKeyword: - case SyntaxKind.AsKeyword: - return 7; - case SyntaxKind.LessThanLessThanToken: - case SyntaxKind.GreaterThanGreaterThanToken: - case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: - return 8; - case SyntaxKind.PlusToken: - case SyntaxKind.MinusToken: - return 9; - case SyntaxKind.AsteriskToken: - case SyntaxKind.SlashToken: - case SyntaxKind.PercentToken: - return 10; - case SyntaxKind.AsteriskAsteriskToken: - return 11; - } - - // -1 is lower than all other precedences. Returning it will cause binary expression - // parsing to stop. - return -1; + return getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left: Expression, operatorToken: BinaryOperatorToken, right: Expression): BinaryExpression { @@ -3795,7 +3750,7 @@ namespace ts { if (isUpdateExpression()) { const updateExpression = parseUpdateExpression(); return token() === SyntaxKind.AsteriskAsteriskToken ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 7030b3baaa8..fa49837fa84 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2414,6 +2414,63 @@ namespace ts { export function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean) { switch (nodeKind) { + case SyntaxKind.CommaListExpression: + return 0; + + case SyntaxKind.SpreadElement: + return 1; + + case SyntaxKind.YieldExpression: + return 2; + + case SyntaxKind.ConditionalExpression: + return 4; + + case SyntaxKind.BinaryExpression: + switch (operatorKind) { + case SyntaxKind.CommaToken: + return 0; + + case SyntaxKind.EqualsToken: + case SyntaxKind.PlusEqualsToken: + case SyntaxKind.MinusEqualsToken: + case SyntaxKind.AsteriskAsteriskEqualsToken: + case SyntaxKind.AsteriskEqualsToken: + case SyntaxKind.SlashEqualsToken: + case SyntaxKind.PercentEqualsToken: + case SyntaxKind.LessThanLessThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanEqualsToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + case SyntaxKind.AmpersandEqualsToken: + case SyntaxKind.CaretEqualsToken: + case SyntaxKind.BarEqualsToken: + return 3; + + default: + return getBinaryOperatorPrecedence(operatorKind); + } + + case SyntaxKind.PrefixUnaryExpression: + case SyntaxKind.TypeOfExpression: + case SyntaxKind.VoidExpression: + case SyntaxKind.DeleteExpression: + case SyntaxKind.AwaitExpression: + return 16; + + case SyntaxKind.PostfixUnaryExpression: + return 17; + + case SyntaxKind.CallExpression: + return 18; + + case SyntaxKind.NewExpression: + return hasArguments ? 19 : 18; + + case SyntaxKind.TaggedTemplateExpression: + case SyntaxKind.PropertyAccessExpression: + case SyntaxKind.ElementAccessExpression: + return 19; + case SyntaxKind.ThisKeyword: case SyntaxKind.SuperKeyword: case SyntaxKind.Identifier: @@ -2435,118 +2492,59 @@ namespace ts { case SyntaxKind.TemplateExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.OmittedExpression: - return 19; - - case SyntaxKind.TaggedTemplateExpression: - case SyntaxKind.PropertyAccessExpression: - case SyntaxKind.ElementAccessExpression: - return 18; - - case SyntaxKind.NewExpression: - return hasArguments ? 18 : 17; - - case SyntaxKind.CallExpression: - return 17; - - case SyntaxKind.PostfixUnaryExpression: - return 16; - - case SyntaxKind.PrefixUnaryExpression: - case SyntaxKind.TypeOfExpression: - case SyntaxKind.VoidExpression: - case SyntaxKind.DeleteExpression: - case SyntaxKind.AwaitExpression: - return 15; - - case SyntaxKind.BinaryExpression: - switch (operatorKind) { - case SyntaxKind.ExclamationToken: - case SyntaxKind.TildeToken: - return 15; - - case SyntaxKind.AsteriskAsteriskToken: - case SyntaxKind.AsteriskToken: - case SyntaxKind.SlashToken: - case SyntaxKind.PercentToken: - return 14; - - case SyntaxKind.PlusToken: - case SyntaxKind.MinusToken: - return 13; - - case SyntaxKind.LessThanLessThanToken: - case SyntaxKind.GreaterThanGreaterThanToken: - case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: - return 12; - - case SyntaxKind.LessThanToken: - case SyntaxKind.LessThanEqualsToken: - case SyntaxKind.GreaterThanToken: - case SyntaxKind.GreaterThanEqualsToken: - case SyntaxKind.InKeyword: - case SyntaxKind.InstanceOfKeyword: - return 11; - - case SyntaxKind.EqualsEqualsToken: - case SyntaxKind.EqualsEqualsEqualsToken: - case SyntaxKind.ExclamationEqualsToken: - case SyntaxKind.ExclamationEqualsEqualsToken: - return 10; - - case SyntaxKind.AmpersandToken: - return 9; - - case SyntaxKind.CaretToken: - return 8; - - case SyntaxKind.BarToken: - return 7; - - case SyntaxKind.AmpersandAmpersandToken: - return 6; - - case SyntaxKind.BarBarToken: - return 5; - - case SyntaxKind.EqualsToken: - case SyntaxKind.PlusEqualsToken: - case SyntaxKind.MinusEqualsToken: - case SyntaxKind.AsteriskAsteriskEqualsToken: - case SyntaxKind.AsteriskEqualsToken: - case SyntaxKind.SlashEqualsToken: - case SyntaxKind.PercentEqualsToken: - case SyntaxKind.LessThanLessThanEqualsToken: - case SyntaxKind.GreaterThanGreaterThanEqualsToken: - case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: - case SyntaxKind.AmpersandEqualsToken: - case SyntaxKind.CaretEqualsToken: - case SyntaxKind.BarEqualsToken: - return 3; - - case SyntaxKind.CommaToken: - return 0; - - default: - return -1; - } - - case SyntaxKind.ConditionalExpression: - return 4; - - case SyntaxKind.YieldExpression: - return 2; - - case SyntaxKind.SpreadElement: - return 1; - - case SyntaxKind.CommaListExpression: - return 0; + return 20; default: return -1; } } + /* @internal */ + export function getBinaryOperatorPrecedence(kind: SyntaxKind): number { + switch (kind) { + case SyntaxKind.BarBarToken: + return 5; + case SyntaxKind.AmpersandAmpersandToken: + return 6; + case SyntaxKind.BarToken: + return 7; + case SyntaxKind.CaretToken: + return 8; + case SyntaxKind.AmpersandToken: + return 9; + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsEqualsToken: + case SyntaxKind.ExclamationEqualsEqualsToken: + return 10; + case SyntaxKind.LessThanToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.LessThanEqualsToken: + case SyntaxKind.GreaterThanEqualsToken: + case SyntaxKind.InstanceOfKeyword: + case SyntaxKind.InKeyword: + case SyntaxKind.AsKeyword: + return 11; + case SyntaxKind.LessThanLessThanToken: + case SyntaxKind.GreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + return 12; + case SyntaxKind.PlusToken: + case SyntaxKind.MinusToken: + return 13; + case SyntaxKind.AsteriskToken: + case SyntaxKind.SlashToken: + case SyntaxKind.PercentToken: + return 14; + case SyntaxKind.AsteriskAsteriskToken: + return 15; + } + + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + export function createDiagnosticCollection(): DiagnosticCollection { let nonFileDiagnostics = [] as SortedArray; const filesWithDiagnostics = [] as SortedArray; From b9f48c1d5d5da30549985dfab96bf6bd50ddb472 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 17:01:31 -0700 Subject: [PATCH 23/75] refactorConvertToEs6Module: Preserve quote style of imports (#22929) --- src/services/codefixes/convertToEs6Module.ts | 25 +++++++++---------- ...torConvertToEs6Module_import_sideEffect.ts | 2 +- ...factorConvertToEs6Module_preserveQuotes.ts | 10 ++++++++ 3 files changed, 23 insertions(+), 14 deletions(-) create mode 100644 tests/cases/fourslash/refactorConvertToEs6Module_preserveQuotes.ts diff --git a/src/services/codefixes/convertToEs6Module.ts b/src/services/codefixes/convertToEs6Module.ts index b39f22be177..23444af22ff 100644 --- a/src/services/codefixes/convertToEs6Module.ts +++ b/src/services/codefixes/convertToEs6Module.ts @@ -20,8 +20,7 @@ namespace ts.codefix { function fixImportOfModuleExports(importingFile: SourceFile, exportingFile: SourceFile, changes: textChanges.ChangeTracker) { for (const moduleSpecifier of importingFile.imports) { - const { text } = moduleSpecifier; - const imported = getResolvedModule(importingFile, text); + const imported = getResolvedModule(importingFile, moduleSpecifier.text); if (!imported || imported.resolvedFileName !== exportingFile.fileName) { continue; } @@ -29,7 +28,7 @@ namespace ts.codefix { const importNode = importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case SyntaxKind.ImportEqualsDeclaration: - changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, text)); + changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); break; case SyntaxKind.CallExpression: if (isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -111,7 +110,7 @@ namespace ts.codefix { case SyntaxKind.CallExpression: { if (isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); } return false; } @@ -139,11 +138,11 @@ namespace ts.codefix { } if (isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); } else if (isPropertyAccessExpression(initializer) && isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); } else { // Move it out to its own variable statement. @@ -157,7 +156,7 @@ namespace ts.codefix { } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name: BindingName, propertyName: string, moduleSpecifier: string, identifiers: Identifiers): ReadonlyArray { + function convertPropertyAccessImport(name: BindingName, propertyName: string, moduleSpecifier: StringLiteralLike, identifiers: Identifiers): ReadonlyArray { switch (name.kind) { case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: { @@ -340,7 +339,7 @@ namespace ts.codefix { function convertSingleImport( file: SourceFile, name: BindingName, - moduleSpecifier: string, + moduleSpecifier: StringLiteralLike, changes: textChanges.ChangeTracker, checker: TypeChecker, identifiers: Identifiers, @@ -362,7 +361,7 @@ namespace ts.codefix { import x from "x"; const [a, b, c] = x; */ - const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ makeImport(createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), makeConst(/*modifiers*/ undefined, getSynthesizedDeepClone(name), createIdentifier(tmp)), @@ -379,7 +378,7 @@ namespace ts.codefix { * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file: SourceFile, name: Identifier, moduleSpecifier: string, changes: textChanges.ChangeTracker, checker: TypeChecker, identifiers: Identifiers): ReadonlyArray { + function convertSingleIdentifierImport(file: SourceFile, name: Identifier, moduleSpecifier: StringLiteralLike, changes: textChanges.ChangeTracker, checker: TypeChecker, identifiers: Identifiers): ReadonlyArray { const nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) const namedBindingsNames = createMap(); @@ -486,14 +485,14 @@ namespace ts.codefix { getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName: string, propertyName: string, moduleSpecifier: string): ImportDeclaration { + function makeSingleImport(localName: string, propertyName: string, moduleSpecifier: StringLiteralLike): ImportDeclaration { return propertyName === "default" ? makeImport(createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); } - function makeImport(name: Identifier | undefined, namedImports: ReadonlyArray | undefined, moduleSpecifier: string): ImportDeclaration { - return makeImportDeclaration(name, namedImports, createLiteral(moduleSpecifier)); + function makeImport(name: Identifier | undefined, namedImports: ReadonlyArray | undefined, moduleSpecifier: StringLiteralLike): ImportDeclaration { + return makeImportDeclaration(name, namedImports, moduleSpecifier); } export function makeImportDeclaration(name: Identifier, namedImports: ReadonlyArray | undefined, moduleSpecifier: Expression) { diff --git a/tests/cases/fourslash/refactorConvertToEs6Module_import_sideEffect.ts b/tests/cases/fourslash/refactorConvertToEs6Module_import_sideEffect.ts index f729f0a9815..28caeaf2411 100644 --- a/tests/cases/fourslash/refactorConvertToEs6Module_import_sideEffect.ts +++ b/tests/cases/fourslash/refactorConvertToEs6Module_import_sideEffect.ts @@ -5,7 +5,7 @@ // @allowJs: true // @Filename: /a.js -/////*a*/require/*b*/("foo"); +////require("foo"); verify.codeFix({ description: "Convert to ES6 module", diff --git a/tests/cases/fourslash/refactorConvertToEs6Module_preserveQuotes.ts b/tests/cases/fourslash/refactorConvertToEs6Module_preserveQuotes.ts new file mode 100644 index 00000000000..5260dc14fbc --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToEs6Module_preserveQuotes.ts @@ -0,0 +1,10 @@ +/// + +// @allowJs: true +// @Filename: /a.js +////const a = require('a'); + +verify.codeFix({ + description: "Convert to ES6 module", + newFileContent: "import a from 'a';", +}); From 2cbad6ab06ace3ff9b07d872ac4ee37eb7c0d306 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 17:02:04 -0700 Subject: [PATCH 24/75] Support completion details for string literal completions (#22664) --- src/services/completions.ts | 58 +++++++++++++------ .../completionForStringLiteral_details.ts | 28 +++++++++ 2 files changed, 67 insertions(+), 19 deletions(-) create mode 100644 tests/cases/fourslash/completionForStringLiteral_details.ts diff --git a/src/services/completions.ts b/src/services/completions.ts index c30a302dc09..57e071efc1a 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -89,7 +89,7 @@ namespace ts.Completions { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries }; } case StringLiteralCompletionKind.Types: { - const entries = completion.types.map(type => ({ name: type.value, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.variableElement, sortText: "0" })); + const entries = completion.types.map(type => ({ name: type.value, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.typeElement, sortText: "0" })); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries }; } default: @@ -531,6 +531,15 @@ namespace ts.Completions { ): CompletionEntryDetails { const typeChecker = program.getTypeChecker(); const { name } = entryId; + + const contextToken = findPrecedingToken(position, sourceFile); + if (isInString(sourceFile, position, contextToken)) { + const stringLiteralCompletions = !contextToken || !isStringLiteralLike(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker); + } + // Compute all the completion symbols again. const symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); switch (symbolCompletion.type) { @@ -550,29 +559,40 @@ namespace ts.Completions { case "symbol": { const { symbol, location, symbolToOriginInfoMap, previousToken } = symbolCompletion; const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences); - 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 }; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, codeActions, sourceDisplay); } - case "none": { + case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. - if (allKeywordsCompletions().some(c => c.name === name)) { - return { - name, - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - displayParts: [displayPart(name, SymbolDisplayPartKind.keyword)], - documentation: undefined, - tags: undefined, - codeActions: undefined, - source: undefined, - }; - } - return undefined; - } + return allKeywordsCompletions().some(c => c.name === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.keyword, [displayPart(name, SymbolDisplayPartKind.keyword)]) : undefined; } } + function createCompletionDetailsForSymbol(symbol: Symbol, checker: TypeChecker, sourceFile: SourceFile, location: Node, codeActions?: CodeAction[], sourceDisplay?: SymbolDisplayPart[]): CompletionEntryDetails { + const { displayParts, documentation, symbolKind, tags } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, SemanticMeaning.All); + return createCompletionDetails(symbol.name, SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + } + + function stringLiteralCompletionDetails(name: string, location: Node, completion: StringLiteralCompletion, sourceFile: SourceFile, checker: TypeChecker): CompletionEntryDetails | undefined { + switch (completion.kind) { + case StringLiteralCompletionKind.Paths: { + const match = find(completion.paths, p => p.name === name); + return match && createCompletionDetails(name, ScriptElementKindModifier.none, match.kind, [textPart(name)]); + } + case StringLiteralCompletionKind.Properties: { + const match = find(completion.symbols, s => s.name === name); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location); + } + case StringLiteralCompletionKind.Types: + return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.typeElement, [textPart(name)]) : undefined; + default: + return Debug.assertNever(completion); + } + } + + function createCompletionDetails(name: string, kindModifiers: string, kind: ScriptElementKind, displayParts: SymbolDisplayPart[], documentation?: SymbolDisplayPart[], tags?: JSDocTagInfo[], codeActions?: CodeAction[], source?: SymbolDisplayPart[]): CompletionEntryDetails { + return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source }; + } + interface CodeActionsAndSourceDisplay { readonly codeActions: CodeAction[] | undefined; readonly sourceDisplay: SymbolDisplayPart[] | undefined; diff --git a/tests/cases/fourslash/completionForStringLiteral_details.ts b/tests/cases/fourslash/completionForStringLiteral_details.ts new file mode 100644 index 00000000000..46832bc9025 --- /dev/null +++ b/tests/cases/fourslash/completionForStringLiteral_details.ts @@ -0,0 +1,28 @@ +/// + +// @Filename: /other.ts +////export const x = 0; + +// @Filename: /a.ts +////import {} from ".//*path*/"; +//// +////const x: "a" = "/*type*/"; +//// +////interface I { +//// /** Prop doc */ +//// x: number; +//// /** Method doc */ +//// m(): void; +////} +////declare const o: I; +////o["/*prop*/"]; + +goTo.marker("path"); +verify.completionListContains("other", "other", "", "script"); + +goTo.marker("type"); +verify.completionListContains("a", "a", "", "type"); + +goTo.marker("prop"); +verify.completionListContains("x", "(property) I.x: number", "Prop doc ", "property"); +verify.completionListContains("m", "(method) I.m(): void", "Method doc ", "method"); From 3e32e15895d4a032dd0bedeab704bfc6d6167e20 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 18:21:21 -0700 Subject: [PATCH 25/75] Add 'fixAllDescription' property to CodeFixAction (#22616) * Add 'fixAllDescription' property to CodeFixAction * Code review * Add to protocol * Make fixAllDescription be just a string --- src/compiler/diagnosticMessages.json | 96 +++++++++++++++++++ src/harness/fourslash.ts | 13 ++- src/server/client.ts | 2 +- src/server/protocol.ts | 2 + src/server/session.ts | 4 +- src/services/codeFixProvider.ts | 19 ++++ .../addMissingInvocationForDecorator.ts | 2 +- .../codefixes/annotateWithTypeFromJSDoc.ts | 3 +- .../codefixes/convertFunctionToEs6Class.ts | 2 +- src/services/codefixes/convertToEs6Module.ts | 3 +- ...correctQualifiedNameToIndexedAccessType.ts | 4 +- .../codefixes/disableJsDiagnostics.ts | 17 ++-- src/services/codefixes/fixAddMissingMember.ts | 13 +-- .../codefixes/fixAwaitInSyncFunction.ts | 2 +- src/services/codefixes/fixCannotFindModule.ts | 25 ++--- ...sDoesntImplementInheritedAbstractMember.ts | 2 +- .../fixClassIncorrectlyImplementsInterface.ts | 4 +- .../fixClassSuperMustPrecedeThisAccess.ts | 2 +- .../fixConstructorForDerivedNeedSuperCall.ts | 2 +- .../fixExtendsInterfaceBecomesImplements.ts | 2 +- .../fixForgottenThisPropertyAccess.ts | 2 +- .../codefixes/fixInvalidImportSyntax.ts | 23 ++--- src/services/codefixes/fixJSDocTypes.ts | 10 +- src/services/codefixes/fixSpelling.ts | 3 +- .../codefixes/fixStrictClassInitialization.ts | 11 +-- src/services/codefixes/fixUnusedIdentifier.ts | 9 +- src/services/codefixes/importFixes.ts | 11 +-- src/services/codefixes/inferFromUsage.ts | 6 +- src/services/codefixes/useDefaultImport.ts | 3 +- src/services/types.ts | 1 + .../reference/api/tsserverlibrary.d.ts | 3 + tests/baselines/reference/api/typescript.d.ts | 1 + .../annotateWithTypeFromJSDoc_all.ts | 1 + ...FixAddMissingInvocationForDecorator_all.ts | 1 + .../fourslash/codeFixAddMissingMember_all.ts | 1 + .../codeFixAddMissingMember_all_js.ts | 1 + .../codeFixAwaitInSyncFunction_all.ts | 1 + .../fourslash/codeFixCannotFindModule_all.ts | 1 + .../fourslash/codeFixChangeJSDocSyntax_all.ts | 1 + .../codeFixChangeJSDocSyntax_all_nullable.ts | 1 + .../codeFixClassExtendAbstractMethod_all.ts | 1 + .../codeFixClassImplementInterface_all.ts | 1 + ...odeFixClassPropertyInitialization_all_1.ts | 27 +++--- ...odeFixClassPropertyInitialization_all_2.ts | 27 +++--- ...odeFixClassPropertyInitialization_all_3.ts | 27 +++--- ...eFixClassSuperMustPrecedeThisAccess_all.ts | 1 + ...xConstructorForDerivedNeedSuperCall_all.ts | 1 + ...ectQualifiedNameToIndexedAccessType_all.ts | 1 + .../codeFixDisableJsDiagnosticsInFile_all.ts | 1 + ...ixExtendsInterfaceBecomesImplements_all.ts | 1 + .../codeFixForgottenThisPropertyAccess_all.ts | 1 + .../fourslash/codeFixInPropertyAccess_js.ts | 1 + .../fourslash/codeFixInferFromUsage_all.ts | 1 + tests/cases/fourslash/codeFixSpelling_all.ts | 1 + .../codeFixUnusedIdentifier_all_delete.ts | 1 + .../codeFixUnusedIdentifier_all_prefix.ts | 1 + .../fourslash/codeFixUseDefaultImport_all.ts | 1 + tests/cases/fourslash/fourslash.ts | 2 +- 58 files changed, 258 insertions(+), 149 deletions(-) diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 0905963541d..ea067001377 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -4026,5 +4026,101 @@ "Add definite assignment assertion to property '{0}'": { "category": "Message", "code": 95020 + }, + "Add all missing members": { + "category": "Message", + "code": 95022 + }, + "Infer all types from usage": { + "category": "Message", + "code": 95023 + }, + "Delete all unused declarations": { + "category": "Message", + "code": 95024 + }, + "Prefix all unused declarations with '_' where possible": { + "category": "Message", + "code": 95025 + }, + "Fix all detected spelling errors": { + "category": "Message", + "code": 95026 + }, + "Add initializers to all uninitialized properties": { + "category": "Message", + "code": 95027 + }, + "Add definite assignment assertions to all uninitialized properties": { + "category": "Message", + "code": 95028 + }, + "Add undefined type to all uninitialized properties": { + "category": "Message", + "code": 95029 + }, + "Change all jsdoc-style types to TypeScript": { + "category": "Message", + "code": 95030 + }, + "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)": { + "category": "Message", + "code": 95031 + }, + "Implement all unimplemented interfaces": { + "category": "Message", + "code": 95032 + }, + "Install all missing types packages": { + "category": "Message", + "code": 95033 + }, + "Rewrite all as indexed access types": { + "category": "Message", + "code": 95034 + }, + "Convert all to default imports": { + "category": "Message", + "code": 95035 + }, + "Make all 'super()' calls the first statement in their constructor": { + "category": "Message", + "code": 95036 + }, + "Add 'this.' to all unresolved variables matching a member name": { + "category": "Message", + "code": 95037 + }, + "Change all extended interfaces to 'implements'": { + "category": "Message", + "code": 95038 + }, + "Add all missing super calls": { + "category": "Message", + "code": 95039 + }, + "Implement all inherited abstract classes": { + "category": "Message", + "code": 95040 + }, + "Add all missing 'async' modifiers": { + "category": "Message", + "code": 95041 + }, + "Add '@ts-ignore' to all error messages": { + "category": "Message", + "code": 95042 + }, + "Annotate everything with types from JSDoc": { + "category": "Message", + "code": 95043 + }, + "Add '()' to all uncalled decorators": { + "category": "Message", + "code": 95044 + }, + "Convert all constructor functions to classes": { + "category": "Message", + "code": 95045 } } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 4e1c44ae01c..17b3d52c040 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2457,12 +2457,14 @@ 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}`); + public verifyCodeFixAll({ fixId, fixAllDescription, newFileContent, commands: expectedCommands }: FourSlashInterface.VerifyCodeFixAllOptions): void { + const fixWithId = ts.find(this.getCodeFixes(this.activeFile.fileName), a => a.fixId === fixId); + ts.Debug.assert(fixWithId !== undefined, "No available code fix has that group id.", () => + `Expected '${fixId}'. Available action ids: ${ts.mapDefined(this.getCodeFixes(this.activeFile.fileName), a => a.fixId)}`); + ts.Debug.assertEqual(fixWithId.fixAllDescription, fixAllDescription); + const { changes, commands } = this.languageService.getCombinedCodeFix({ type: "file", fileName: this.activeFile.fileName }, fixId, this.formatCodeSettings, ts.defaultPreferences); - assert.deepEqual(commands, options.commands); + assert.deepEqual(commands, expectedCommands); assert(changes.every(c => c.fileName === this.activeFile.fileName), "TODO: support testing codefixes that touch multiple files"); this.applyChanges(changes); this.verifyCurrentFileContent(newFileContent); @@ -4661,6 +4663,7 @@ namespace FourSlashInterface { export interface VerifyCodeFixAllOptions { fixId: string; + fixAllDescription: string; newFileContent: string; commands: ReadonlyArray<{}>; } diff --git a/src/server/client.ts b/src/server/client.ts index 1a0912d378c..98fb130dbb3 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -557,7 +557,7 @@ namespace ts.server { const request = this.processRequest(CommandNames.GetCodeFixes, args); const response = this.processResponse(request); - return response.body.map(({ description, changes, fixId }) => ({ description, changes: this.convertChanges(changes, file), fixId })); + return response.body.map(({ description, changes, fixId, fixAllDescription }) => ({ description, changes: this.convertChanges(changes, file), fixId, fixAllDescription })); } getCombinedCodeFix = notImplemented; diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 9e179db8e5e..3f0ce3b6d40 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -1701,6 +1701,8 @@ namespace ts.server.protocol { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; } /** diff --git a/src/server/session.ts b/src/server/session.ts index 4d9c296f6a9..4d39b4d0cf9 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1723,9 +1723,9 @@ namespace ts.server { return { startPosition, endPosition }; } - private mapCodeAction(project: Project, { description, changes: unmappedChanges, commands, fixId }: CodeFixAction): protocol.CodeFixAction { + private mapCodeAction(project: Project, { description, changes: unmappedChanges, commands, fixId, fixAllDescription }: CodeFixAction): protocol.CodeFixAction { const changes = unmappedChanges.map(change => this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(toNormalizedPath(change.fileName)))); - return { description, changes, commands, fixId }; + return { description, changes, commands, fixId, fixAllDescription }; } private mapTextChangesToCodeEdits(project: Project, textChanges: ReadonlyArray): protocol.FileCodeEdits[] { diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index 74d3487a74c..291f8fd1d66 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -27,6 +27,25 @@ namespace ts { const codeFixRegistrations: CodeFixRegistration[][] = []; const fixIdToRegistration = createMap(); + type DiagnosticAndArguments = DiagnosticMessage | [DiagnosticMessage, string] | [DiagnosticMessage, string, string]; + function diagnosticToString(diag: DiagnosticAndArguments): string { + return isArray(diag) + ? formatStringFromArgs(getLocaleSpecificMessage(diag[0]), diag.slice(1) as ReadonlyArray) + : getLocaleSpecificMessage(diag); + } + + export function createCodeFixActionNoFixId(changes: FileTextChanges[], description: DiagnosticAndArguments) { + return createCodeFixActionWorker(diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + + export function createCodeFixAction(changes: FileTextChanges[], description: DiagnosticAndArguments, fixId: {}, fixAllDescription: DiagnosticAndArguments, command?: CodeActionCommand): CodeFixAction { + return createCodeFixActionWorker(diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + + function createCodeFixActionWorker(description: string, changes: FileTextChanges[], fixId?: {}, fixAllDescription?: string, command?: CodeActionCommand): CodeFixAction { + return { description, changes, fixId, fixAllDescription, commands: command ? [command] : undefined }; + } + export function registerCodeFix(reg: CodeFixRegistration) { for (const error of reg.errorCodes) { let registrations = codeFixRegistrations[error]; diff --git a/src/services/codefixes/addMissingInvocationForDecorator.ts b/src/services/codefixes/addMissingInvocationForDecorator.ts index d063df87be4..7b8a7d05fe7 100644 --- a/src/services/codefixes/addMissingInvocationForDecorator.ts +++ b/src/services/codefixes/addMissingInvocationForDecorator.ts @@ -6,7 +6,7 @@ namespace ts.codefix { 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 }]; + return [createCodeFixAction(changes, Diagnostics.Call_decorator_expression, fixId, Diagnostics.Add_to_all_uncalled_decorators)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file!, diag.start!)), diff --git a/src/services/codefixes/annotateWithTypeFromJSDoc.ts b/src/services/codefixes/annotateWithTypeFromJSDoc.ts index 20fc3a9c601..5edbab01450 100644 --- a/src/services/codefixes/annotateWithTypeFromJSDoc.ts +++ b/src/services/codefixes/annotateWithTypeFromJSDoc.ts @@ -7,9 +7,8 @@ namespace ts.codefix { getCodeActions(context) { const decl = getDeclaration(context.sourceFile, context.span.start); if (!decl) return; - const description = getLocaleSpecificMessage(Diagnostics.Annotate_with_type_from_JSDoc); const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, decl)); - return [{ description, changes, fixId }]; + return [createCodeFixAction(changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId, Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index d63837e7dd4..a4386ab07f1 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -6,7 +6,7 @@ namespace ts.codefix { errorCodes, getCodeActions(context: CodeFixContext) { const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker())); - return [{ description: getLocaleSpecificMessage(Diagnostics.Convert_function_to_an_ES2015_class), changes, fixId }]; + return [createCodeFixAction(changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId, Diagnostics.Convert_all_constructor_functions_to_classes)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, err) => doChange(changes, err.file!, err.start, context.program.getTypeChecker())), diff --git a/src/services/codefixes/convertToEs6Module.ts b/src/services/codefixes/convertToEs6Module.ts index 23444af22ff..b8c78d57827 100644 --- a/src/services/codefixes/convertToEs6Module.ts +++ b/src/services/codefixes/convertToEs6Module.ts @@ -3,7 +3,6 @@ namespace ts.codefix { registerCodeFix({ errorCodes: [Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions(context) { - const description = getLocaleSpecificMessage(Diagnostics.Convert_to_ES6_module); const { sourceFile, program } = context; const changes = textChanges.ChangeTracker.with(context, changes => { const moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); @@ -14,7 +13,7 @@ namespace ts.codefix { } }); // No support for fix-all since this applies to the whole file at once anyway. - return [{ description, changes, fixId: undefined }]; + return [createCodeFixActionNoFixId(changes, Diagnostics.Convert_to_ES6_module)]; }, }); diff --git a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts index de4498035be..f47b65aad90 100644 --- a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts +++ b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts @@ -8,8 +8,8 @@ namespace ts.codefix { 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 }]; + const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`; + return [createCodeFixAction(changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], getAllCodeActions: (context) => codeFixAll(context, errorCodes, (changes, diag) => { diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index 2d82a198ce9..c53c35c5f81 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -16,23 +16,18 @@ namespace ts.codefix { } const fixes: CodeFixAction[] = [ - { - description: getLocaleSpecificMessage(Diagnostics.Disable_checking_for_this_file), - changes: [createFileTextChanges(sourceFile.fileName, [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + createCodeFixActionNoFixId( + [createFileTextChanges(sourceFile.fileName, [ createTextChange(sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0), `// @ts-nocheck${getNewLineOrDefaultFromHost(host, formatContext.options)}`), ])], - // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - fixId: undefined, - }]; + Diagnostics.Disable_checking_for_this_file), + ]; if (textChanges.isValidLocationToAddComment(sourceFile, span.start)) { - fixes.unshift({ - description: getLocaleSpecificMessage(Diagnostics.Ignore_this_error_message), - changes: textChanges.ChangeTracker.with(context, t => makeChange(t, sourceFile, span.start)), - fixId, - }); + fixes.unshift(createCodeFixAction(textChanges.ChangeTracker.with(context, t => makeChange(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId, Diagnostics.Add_ts_ignore_to_all_error_messages)); } return fixes; diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index b315dd0659f..d8df415a4de 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -97,9 +97,8 @@ namespace ts.codefix { 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 }; + return changes.length === 0 ? undefined + : createCodeFixAction(changes, [makeStatic ? Diagnostics.Initialize_static_property_0 : Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker: textChanges.ChangeTracker, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): void { @@ -143,9 +142,8 @@ namespace ts.codefix { } function createAddPropertyDeclarationAction(context: CodeFixContext, 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 }; + return createCodeFixAction(changes, [makeStatic ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, tokenName], fixId, Diagnostics.Add_all_missing_members); } function addPropertyDeclaration(changeTracker: textChanges.ChangeTracker, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, typeNode: TypeNode, makeStatic: boolean): void { @@ -178,7 +176,7 @@ namespace ts.codefix { 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 createCodeFixActionNoFixId(changes, [Diagnostics.Add_index_signature_for_property_0, tokenName]); } function getActionForMethodDeclaration( @@ -191,9 +189,8 @@ namespace ts.codefix { inJs: boolean, preferences: UserPreferences, ): 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, preferences)); - return { description, changes, fixId }; + return createCodeFixAction(changes, [makeStatic ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, token.text], fixId, Diagnostics.Add_all_missing_members); } function addMethodDeclaration( diff --git a/src/services/codefixes/fixAwaitInSyncFunction.ts b/src/services/codefixes/fixAwaitInSyncFunction.ts index 713a25456c0..804910e9a22 100644 --- a/src/services/codefixes/fixAwaitInSyncFunction.ts +++ b/src/services/codefixes/fixAwaitInSyncFunction.ts @@ -12,7 +12,7 @@ namespace ts.codefix { const nodes = getNodes(sourceFile, span.start); if (!nodes) return undefined; const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, nodes)); - return [{ description: getLocaleSpecificMessage(Diagnostics.Add_async_modifier_to_containing_function), changes, fixId }]; + return [createCodeFixAction(changes, Diagnostics.Add_async_modifier_to_containing_function, fixId, Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { diff --git a/src/services/codefixes/fixCannotFindModule.ts b/src/services/codefixes/fixCannotFindModule.ts index 41563e6ca90..89f7a3f7793 100644 --- a/src/services/codefixes/fixCannotFindModule.ts +++ b/src/services/codefixes/fixCannotFindModule.ts @@ -5,38 +5,27 @@ namespace ts.codefix { registerCodeFix({ errorCodes, getCodeActions: context => { - const codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); - return codeAction && [{ fixId, ...codeAction }]; + const { host, sourceFile, span: { start } } = context; + const packageName = getTypesPackageNameToInstall(host, sourceFile, start); + return packageName === undefined ? [] + : [createCodeFixAction(/*changes*/ [], [Diagnostics.Install_0, packageName], fixId, Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (_, diag, commands) => { - const pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + const pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start); if (pkg) { commands.push(getCommand(diag.file.fileName, pkg)); } }), }); - function getModuleName(sourceFile: SourceFile, pos: number): string { - return cast(getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isStringLiteral).text; - } - function getCommand(fileName: string, packageName: string): InstallPackageAction { return { type: "install package", file: fileName, packageName }; } - function getTypesPackageNameToInstall(host: LanguageServiceHost, moduleName: string): string | undefined { + function getTypesPackageNameToInstall(host: LanguageServiceHost, sourceFile: SourceFile, pos: number): string | undefined { + const moduleName = cast(getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isStringLiteral).text; const { packageName } = getPackageName(moduleName); - // If !registry, registry not available yet, can't do anything. return host.isKnownTypesPackageName(packageName) ? getTypesPackageName(packageName) : undefined; } - - 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: [getCommand(fileName, packageName)], - }; - } } diff --git a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts index cb33d1c1793..3a1443c04bb 100644 --- a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts +++ b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts @@ -11,7 +11,7 @@ namespace ts.codefix { const { program, sourceFile, span } = context; const changes = textChanges.ChangeTracker.with(context, t => addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences)); - return changes.length === 0 ? undefined : [{ description: getLocaleSpecificMessage(Diagnostics.Implement_inherited_abstract_class), changes, fixId }]; + return changes.length === 0 ? undefined : [createCodeFixAction(changes, Diagnostics.Implement_inherited_abstract_class, fixId, Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], getAllCodeActions: context => { diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 38cedbb2ce4..695bbdda4b0 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -11,9 +11,7 @@ namespace ts.codefix { const checker = program.getTypeChecker(); return mapDefined(getClassImplementsHeritageClauseElements(classDeclaration), implementedTypeNode => { const changes = textChanges.ChangeTracker.with(context, t => addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences)); - if (changes.length === 0) return undefined; - const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - return { description, changes, fixId }; + return changes.length === 0 ? undefined : createCodeFixAction(changes, [Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, Diagnostics.Implement_all_unimplemented_interfaces); }); }, fixIds: [fixId], diff --git a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts index 8d47e74d8a4..d9c98747286 100644 --- a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts +++ b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts @@ -10,7 +10,7 @@ namespace ts.codefix { 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 }]; + return [createCodeFixAction(changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId], getAllCodeActions(context) { diff --git a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts index 8fe2e8458a8..31aa4fcedae 100644 --- a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts +++ b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts @@ -8,7 +8,7 @@ namespace ts.codefix { 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 }]; + return [createCodeFixAction(changes, Diagnostics.Add_missing_super_call, fixId, Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index 92d65299489..381a8228c0d 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -10,7 +10,7 @@ namespace ts.codefix { 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 }]; + return [createCodeFixAction(changes, Diagnostics.Change_extends_to_implements, fixId, Diagnostics.Change_all_extended_interfaces_to_implements)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { diff --git a/src/services/codefixes/fixForgottenThisPropertyAccess.ts b/src/services/codefixes/fixForgottenThisPropertyAccess.ts index 10933b031e5..2cf7e2143a3 100644 --- a/src/services/codefixes/fixForgottenThisPropertyAccess.ts +++ b/src/services/codefixes/fixForgottenThisPropertyAccess.ts @@ -11,7 +11,7 @@ namespace ts.codefix { return undefined; } const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, token)); - return [{ description: getLocaleSpecificMessage(Diagnostics.Add_this_to_unresolved_variable), changes, fixId }]; + return [createCodeFixAction(changes, Diagnostics.Add_this_to_unresolved_variable, fixId, Diagnostics.Add_this_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { diff --git a/src/services/codefixes/fixInvalidImportSyntax.ts b/src/services/codefixes/fixInvalidImportSyntax.ts index fd66a9db37c..84bd9867c70 100644 --- a/src/services/codefixes/fixInvalidImportSyntax.ts +++ b/src/services/codefixes/fixInvalidImportSyntax.ts @@ -5,7 +5,7 @@ namespace ts.codefix { getCodeActions: getActionsForInvalidImport }); - function getActionsForInvalidImport(context: CodeFixContext): CodeAction[] | undefined { + function getActionsForInvalidImport(context: CodeFixContext): CodeFixAction[] | undefined { const sourceFile = context.sourceFile; // This is the whole import statement, eg: @@ -19,11 +19,11 @@ namespace ts.codefix { return getCodeFixesForImportDeclaration(context, node); } - function getCodeFixesForImportDeclaration(context: CodeFixContext, node: ImportDeclaration) { + function getCodeFixesForImportDeclaration(context: CodeFixContext, node: ImportDeclaration): CodeFixAction[] { const sourceFile = getSourceFileOfNode(node); const namespace = getNamespaceDeclarationNode(node) as NamespaceImport; const opts = context.program.getCompilerOptions(); - const variations: CodeAction[] = []; + const variations: CodeFixAction[] = []; // import Bluebird from "bluebird"; variations.push(createAction(context, sourceFile, node, makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); @@ -41,12 +41,9 @@ namespace ts.codefix { return variations; } - function createAction(context: CodeFixContext, sourceFile: SourceFile, node: Node, replacement: Node): CodeAction { + function createAction(context: CodeFixContext, sourceFile: SourceFile, node: Node, replacement: Node): CodeFixAction { const changes = textChanges.ChangeTracker.with(context, t => t.replaceNode(sourceFile, node, replacement)); - return { - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), - changes, - }; + return createCodeFixActionNoFixId(changes, [Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } registerCodeFix({ @@ -57,7 +54,7 @@ namespace ts.codefix { getCodeActions: getActionsForUsageOfInvalidImport }); - function getActionsForUsageOfInvalidImport(context: CodeFixContext): CodeAction[] | undefined { + function getActionsForUsageOfInvalidImport(context: CodeFixContext): CodeFixAction[] | 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; @@ -69,15 +66,13 @@ namespace ts.codefix { if (!(type.symbol && (type.symbol as TransientSymbol).originatingImport)) { return []; } - const fixes: CodeAction[] = []; + const fixes: CodeFixAction[] = []; const relatedImport = (type.symbol as TransientSymbol).originatingImport; if (!isImportCall(relatedImport)) { addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } - fixes.push({ - description: getLocaleSpecificMessage(Diagnostics.Use_synthetic_default_member), - changes: textChanges.ChangeTracker.with(context, t => t.replaceNode(sourceFile, expr, createPropertyAccess(expr, "default"), {})), - }); + const changes = textChanges.ChangeTracker.with(context, t => t.replaceNode(sourceFile, expr, createPropertyAccess(expr, "default"), {})); + fixes.push(createCodeFixActionNoFixId(changes, Diagnostics.Use_synthetic_default_member)); return fixes; } } diff --git a/src/services/codefixes/fixJSDocTypes.ts b/src/services/codefixes/fixJSDocTypes.ts index 344d840cc2e..848666b67f0 100644 --- a/src/services/codefixes/fixJSDocTypes.ts +++ b/src/services/codefixes/fixJSDocTypes.ts @@ -12,19 +12,17 @@ namespace ts.codefix { if (!info) return undefined; const { typeNode, type } = info; const original = typeNode.getText(sourceFile); - const actions = [fix(type, fixIdPlain)]; + const actions = [fix(type, fixIdPlain, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; 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)); + actions.push(fix(checker.getNullableType(type, TypeFlags.Undefined), fixIdNullable, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; - function fix(type: Type, fixId: string): CodeFixAction { - const newText = checker.typeToString(type); - const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_0_to_1), [original, newText]); + function fix(type: Type, fixId: string, fixAllDescription: DiagnosticMessage): CodeFixAction { const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, typeNode, type, checker)); - return { description, changes, fixId }; + return createCodeFixAction(changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts index 729f14e9ef9..b997c3c4312 100644 --- a/src/services/codefixes/fixSpelling.ts +++ b/src/services/codefixes/fixSpelling.ts @@ -13,8 +13,7 @@ namespace ts.codefix { 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 }]; + return [createCodeFixAction(changes, [Diagnostics.Change_spelling_to_0, suggestion], fixId, Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { diff --git a/src/services/codefixes/fixStrictClassInitialization.ts b/src/services/codefixes/fixStrictClassInitialization.ts index a5420f2c181..2f51cedbe82 100644 --- a/src/services/codefixes/fixStrictClassInitialization.ts +++ b/src/services/codefixes/fixStrictClassInitialization.ts @@ -52,9 +52,8 @@ namespace ts.codefix { } function getActionForAddMissingDefiniteAssignmentAssertion (context: CodeFixContext, propertyDeclaration: PropertyDeclaration): CodeFixAction { - const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_definite_assignment_assertion_to_property_0), [propertyDeclaration.getText()]); const changes = textChanges.ChangeTracker.with(context, t => addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration)); - return { description, changes, fixId: fixIdAddDefiniteAssignmentAssertions }; + return createCodeFixAction(changes, [Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } function addDefiniteAssignmentAssertion(changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration): void { @@ -71,9 +70,8 @@ namespace ts.codefix { } function getActionForAddMissingUndefinedType (context: CodeFixContext, propertyDeclaration: PropertyDeclaration): CodeFixAction { - const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_undefined_type_to_property_0), [propertyDeclaration.name.getText()]); const changes = textChanges.ChangeTracker.with(context, t => addUndefinedType(t, context.sourceFile, propertyDeclaration)); - return { description, changes, fixId: fixIdAddUndefinedType }; + return createCodeFixAction(changes, [Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration): void { @@ -82,14 +80,13 @@ namespace ts.codefix { changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, createUnionTypeNode(types)); } - function getActionForAddMissingInitializer (context: CodeFixContext, propertyDeclaration: PropertyDeclaration): CodeFixAction | undefined { + function getActionForAddMissingInitializer(context: CodeFixContext, propertyDeclaration: PropertyDeclaration): CodeFixAction | undefined { const checker = context.program.getTypeChecker(); const initializer = getInitializer(checker, propertyDeclaration); if (!initializer) return undefined; - const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_initializer_to_property_0), [propertyDeclaration.name.getText()]); const changes = textChanges.ChangeTracker.with(context, t => addInitializer(t, context.sourceFile, propertyDeclaration, initializer)); - return { description, changes, fixId: fixIdAddInitializer }; + return createCodeFixAction(changes, [Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, Diagnostics.Add_initializers_to_all_uninitialized_properties); } function addInitializer (changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration, initializer: Expression): void { diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 3de5e7e36b0..1fe0107dafb 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -13,9 +13,8 @@ namespace ts.codefix { const { errorCode, sourceFile } = context; const importDecl = tryGetFullImport(sourceFile, context.span.start); if (importDecl) { - const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Remove_import_from_0), [showModuleSpecifier(importDecl)]); const changes = textChanges.ChangeTracker.with(context, t => t.deleteNode(sourceFile, importDecl)); - return [{ description, changes, fixId: fixIdDelete }]; + return [createCodeFixAction(changes, [Diagnostics.Remove_import_from_0, showModuleSpecifier(importDecl)], fixIdDelete, Diagnostics.Delete_all_unused_declarations)]; } const token = getToken(sourceFile, textSpanEnd(context.span)); @@ -23,14 +22,12 @@ namespace ts.codefix { 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 }); + result.push(createCodeFixAction(deletion, [Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, Diagnostics.Delete_all_unused_declarations)); } const prefix = textChanges.ChangeTracker.with(context, t => tryPrefixDeclaration(t, 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 }); + result.push(createCodeFixAction(prefix, [Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, Diagnostics.Prefix_all_unused_declarations_with_where_possible)); } return result; diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index a22201d0479..95cd84ee620 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -33,10 +33,9 @@ namespace ts.codefix { preferences: UserPreferences; } - function createCodeAction(descriptionDiagnostic: DiagnosticMessage, diagnosticArgs: string[], changes: FileTextChanges[]): CodeFixAction { - const description = formatMessage.apply(undefined, [undefined, descriptionDiagnostic].concat(diagnosticArgs)); + function createCodeAction(descriptionDiagnostic: DiagnosticMessage, diagnosticArgs: [string, string], changes: FileTextChanges[]): CodeFixAction { // TODO: GH#20315 - return { description, changes, fixId: undefined }; + return createCodeFixActionNoFixId(changes, [descriptionDiagnostic, ...diagnosticArgs] as [DiagnosticMessage, string, string]); } function convertToImportCodeFixContext(context: CodeFixContext, symbolToken: Node, symbolName: string): ImportCodeFixContext { @@ -640,13 +639,13 @@ namespace ts.codefix { return createCodeAction(Diagnostics.Change_0_to_1, [symbolName, `${namespacePrefix}.${symbolName}`], changes); } - function getImportCodeActions(context: CodeFixContext): CodeAction[] { + function getImportCodeActions(context: CodeFixContext): CodeFixAction[] { return context.errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getActionsForUMDImport(context) : getActionsForNonUMDImport(context); } - function getActionsForUMDImport(context: CodeFixContext): CodeAction[] { + function getActionsForUMDImport(context: CodeFixContext): CodeFixAction[] { const token = getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); const checker = context.program.getTypeChecker(); @@ -702,7 +701,7 @@ namespace ts.codefix { } } - function getActionsForNonUMDImport(context: CodeFixContext): CodeAction[] | undefined { + function getActionsForNonUMDImport(context: CodeFixContext): CodeFixAction[] | undefined { // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. const { sourceFile, span, program, cancellationToken } = context; const checker = program.getTypeChecker(); diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index a79fa5acc66..8d46bbf4ded 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -33,10 +33,8 @@ namespace ts.codefix { const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); let declaration!: Declaration; const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); - if (changes.length === 0) return undefined; - const name = getNameOfDeclaration(declaration).getText(); - const description = formatStringFromArgs(getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name]); - return [{ description, changes, fixId }]; + return changes.length === 0 ? undefined + : [createCodeFixAction(changes, [getDiagnostic(errorCode, token), getNameOfDeclaration(declaration).getText(sourceFile)], fixId, Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions(context) { diff --git a/src/services/codefixes/useDefaultImport.ts b/src/services/codefixes/useDefaultImport.ts index bd0797953b9..7a6a0acfc30 100644 --- a/src/services/codefixes/useDefaultImport.ts +++ b/src/services/codefixes/useDefaultImport.ts @@ -8,9 +8,8 @@ namespace ts.codefix { const { sourceFile, span: { start } } = context; const info = getInfo(sourceFile, start); if (!info) return undefined; - const description = getLocaleSpecificMessage(Diagnostics.Convert_to_default_import); const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, info)); - return [{ description, changes, fixId }]; + return [createCodeFixAction(changes, Diagnostics.Convert_to_default_import, fixId, Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { diff --git a/src/services/types.ts b/src/services/types.ts index af496cfeb11..3eb6f5dba2a 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -440,6 +440,7 @@ namespace ts { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + fixAllDescription?: string; } export interface CombinedCodeActions { diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index c344b31b1fc..7a121848f47 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -4242,6 +4242,7 @@ declare namespace ts { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + fixAllDescription?: string; } interface CombinedCodeActions { changes: ReadonlyArray; @@ -6313,6 +6314,8 @@ declare namespace ts.server.protocol { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; } /** * Format and format on key response message. diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index f849dc7f664..94dcc50dc28 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -4494,6 +4494,7 @@ declare namespace ts { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + fixAllDescription?: string; } interface CombinedCodeActions { changes: ReadonlyArray; diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc_all.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc_all.ts index 60e10980bb9..d5de68c70ad 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc_all.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc_all.ts @@ -8,6 +8,7 @@ verify.codeFixAll({ fixId: "annotateWithTypeFromJSDoc", + fixAllDescription: "Annotate everything with types from JSDoc", newFileContent: `/** @type {number} */ var x: number; diff --git a/tests/cases/fourslash/codeFixAddMissingInvocationForDecorator_all.ts b/tests/cases/fourslash/codeFixAddMissingInvocationForDecorator_all.ts index f655065e78c..3b0f35b0ac6 100644 --- a/tests/cases/fourslash/codeFixAddMissingInvocationForDecorator_all.ts +++ b/tests/cases/fourslash/codeFixAddMissingInvocationForDecorator_all.ts @@ -11,6 +11,7 @@ verify.codeFixAll({ fixId: "addMissingInvocationForDecorator", + fixAllDescription: "Add '()' to all uncalled decorators", newFileContent: `declare function foo(): (...args: any[]) => void; class C { diff --git a/tests/cases/fourslash/codeFixAddMissingMember_all.ts b/tests/cases/fourslash/codeFixAddMissingMember_all.ts index ae5e957732b..5a2f8606f2d 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember_all.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember_all.ts @@ -10,6 +10,7 @@ verify.codeFixAll({ fixId: "addMissingMember", + fixAllDescription: "Add all missing members", newFileContent: `class C { x: number; diff --git a/tests/cases/fourslash/codeFixAddMissingMember_all_js.ts b/tests/cases/fourslash/codeFixAddMissingMember_all_js.ts index 305b6d87c30..5e5a2895fdc 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember_all_js.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember_all_js.ts @@ -15,6 +15,7 @@ verify.codeFixAll({ fixId: "addMissingMember", + fixAllDescription: "Add all missing members", newFileContent: `class C { y() { diff --git a/tests/cases/fourslash/codeFixAwaitInSyncFunction_all.ts b/tests/cases/fourslash/codeFixAwaitInSyncFunction_all.ts index e6314a3a5f0..4b5f7aea0a3 100644 --- a/tests/cases/fourslash/codeFixAwaitInSyncFunction_all.ts +++ b/tests/cases/fourslash/codeFixAwaitInSyncFunction_all.ts @@ -10,6 +10,7 @@ verify.codeFixAll({ fixId: "fixAwaitInSyncFunction", + fixAllDescription: "Add all missing 'async' modifiers", newFileContent: `async function f() { await Promise.resolve(); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_all.ts b/tests/cases/fourslash/codeFixCannotFindModule_all.ts index bbe4192c256..044d0c5deb0 100644 --- a/tests/cases/fourslash/codeFixCannotFindModule_all.ts +++ b/tests/cases/fourslash/codeFixCannotFindModule_all.ts @@ -22,6 +22,7 @@ goTo.marker(); verify.codeFixAll({ fixId: "fixCannotFindModule", + fixAllDescription: "Install all missing types packages", commands: [ { packageName: "@types/abs", file: "/a.ts", type: "install package" }, { packageName: "@types/zap", file: "/a.ts", type: "install package" }, diff --git a/tests/cases/fourslash/codeFixChangeJSDocSyntax_all.ts b/tests/cases/fourslash/codeFixChangeJSDocSyntax_all.ts index 2c0768c0580..03a51a02f4e 100644 --- a/tests/cases/fourslash/codeFixChangeJSDocSyntax_all.ts +++ b/tests/cases/fourslash/codeFixChangeJSDocSyntax_all.ts @@ -5,5 +5,6 @@ verify.codeFixAll({ fixId: "fixJSDocTypes_plain", + fixAllDescription: "Change all jsdoc-style types to TypeScript", newFileContent: "function f(a: number | null, b: string) {}", }) diff --git a/tests/cases/fourslash/codeFixChangeJSDocSyntax_all_nullable.ts b/tests/cases/fourslash/codeFixChangeJSDocSyntax_all_nullable.ts index 5a18fa620f8..2d987128fb1 100644 --- a/tests/cases/fourslash/codeFixChangeJSDocSyntax_all_nullable.ts +++ b/tests/cases/fourslash/codeFixChangeJSDocSyntax_all_nullable.ts @@ -5,5 +5,6 @@ verify.codeFixAll({ fixId: "fixJSDocTypes_nullable", + fixAllDescription: "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)", newFileContent: "function f(a: number | null | undefined, b: string) {}", }) diff --git a/tests/cases/fourslash/codeFixClassExtendAbstractMethod_all.ts b/tests/cases/fourslash/codeFixClassExtendAbstractMethod_all.ts index b158a215ca1..49770ec85ea 100644 --- a/tests/cases/fourslash/codeFixClassExtendAbstractMethod_all.ts +++ b/tests/cases/fourslash/codeFixClassExtendAbstractMethod_all.ts @@ -9,6 +9,7 @@ verify.codeFixAll({ fixId: "fixClassDoesntImplementInheritedAbstractMember", + fixAllDescription: "Implement all inherited abstract classes", newFileContent: `abstract class A { abstract m(): void; diff --git a/tests/cases/fourslash/codeFixClassImplementInterface_all.ts b/tests/cases/fourslash/codeFixClassImplementInterface_all.ts index ae70d6fb422..cdf11eec352 100644 --- a/tests/cases/fourslash/codeFixClassImplementInterface_all.ts +++ b/tests/cases/fourslash/codeFixClassImplementInterface_all.ts @@ -7,6 +7,7 @@ verify.codeFixAll({ fixId: "fixClassIncorrectlyImplementsInterface", + fixAllDescription: "Implement all unimplemented interfaces", newFileContent: `interface I { i(): void; } interface J { j(): void; } diff --git a/tests/cases/fourslash/codeFixClassPropertyInitialization_all_1.ts b/tests/cases/fourslash/codeFixClassPropertyInitialization_all_1.ts index 46d50c3c32a..2bf0098ceeb 100644 --- a/tests/cases/fourslash/codeFixClassPropertyInitialization_all_1.ts +++ b/tests/cases/fourslash/codeFixClassPropertyInitialization_all_1.ts @@ -7,38 +7,39 @@ //// class TT { constructor () {} } //// //// class AT extends A { a () {} } -//// +//// //// class Foo {} //// //// class T { -//// +//// //// a: string; -//// +//// //// static b: string; -//// +//// //// private c: string; -//// +//// //// d: number | undefined; -//// +//// //// e: string | number; -//// +//// //// f: 1; -//// +//// //// g: "123" | "456"; -//// +//// //// h: boolean; -//// +//// //// i: TT; -//// +//// //// j: A; -//// +//// //// k: AT; -//// +//// //// l: Foo; //// } verify.codeFixAll({ fixId: 'addMissingPropertyDefiniteAssignmentAssertions', + fixAllDescription: "Add definite assignment assertions to all uninitialized properties", newFileContent: `abstract class A { abstract a (); } class TT { constructor () {} } diff --git a/tests/cases/fourslash/codeFixClassPropertyInitialization_all_2.ts b/tests/cases/fourslash/codeFixClassPropertyInitialization_all_2.ts index ccf78aa1124..707b50e5115 100644 --- a/tests/cases/fourslash/codeFixClassPropertyInitialization_all_2.ts +++ b/tests/cases/fourslash/codeFixClassPropertyInitialization_all_2.ts @@ -7,38 +7,39 @@ //// class TT { constructor () {} } //// //// class AT extends A { a () {} } -//// +//// //// class Foo {} //// //// class T { -//// +//// //// a: string; -//// +//// //// static b: string; -//// +//// //// private c: string; -//// +//// //// d: number | undefined; -//// +//// //// e: string | number; -//// +//// //// f: 1; -//// +//// //// g: "123" | "456"; -//// +//// //// h: boolean; -//// +//// //// i: TT; -//// +//// //// j: A; -//// +//// //// k: AT; -//// +//// //// l: Foo; //// } verify.codeFixAll({ fixId: 'addMissingPropertyUndefinedType', + fixAllDescription: "Add undefined type to all uninitialized properties", newFileContent: `abstract class A { abstract a (); } class TT { constructor () {} } diff --git a/tests/cases/fourslash/codeFixClassPropertyInitialization_all_3.ts b/tests/cases/fourslash/codeFixClassPropertyInitialization_all_3.ts index 28518d3d16f..5931c6bd977 100644 --- a/tests/cases/fourslash/codeFixClassPropertyInitialization_all_3.ts +++ b/tests/cases/fourslash/codeFixClassPropertyInitialization_all_3.ts @@ -7,38 +7,39 @@ //// class TT { constructor () {} } //// //// class AT extends A { a () {} } -//// +//// //// class Foo {} //// //// class T { -//// +//// //// a: string; -//// +//// //// static b: string; -//// +//// //// private c: string; -//// +//// //// d: number | undefined; -//// +//// //// e: string | number; -//// +//// //// f: 1; -//// +//// //// g: "123" | "456"; -//// +//// //// h: boolean; -//// +//// //// i: TT; -//// +//// //// j: A; -//// +//// //// k: AT; -//// +//// //// l: Foo; //// } verify.codeFixAll({ fixId: 'addMissingPropertyInitializer', + fixAllDescription: "Add initializers to all uninitialized properties", newFileContent: `abstract class A { abstract a (); } class TT { constructor () {} } diff --git a/tests/cases/fourslash/codeFixClassSuperMustPrecedeThisAccess_all.ts b/tests/cases/fourslash/codeFixClassSuperMustPrecedeThisAccess_all.ts index 96f3677fda7..41650e42cac 100644 --- a/tests/cases/fourslash/codeFixClassSuperMustPrecedeThisAccess_all.ts +++ b/tests/cases/fourslash/codeFixClassSuperMustPrecedeThisAccess_all.ts @@ -16,6 +16,7 @@ verify.codeFixAll({ fixId: "classSuperMustPrecedeThisAccess", + fixAllDescription: "Make all 'super()' calls the first statement in their constructor", newFileContent: `class C extends Object { constructor() { super(); diff --git a/tests/cases/fourslash/codeFixConstructorForDerivedNeedSuperCall_all.ts b/tests/cases/fourslash/codeFixConstructorForDerivedNeedSuperCall_all.ts index 3833af62de0..bb576795338 100644 --- a/tests/cases/fourslash/codeFixConstructorForDerivedNeedSuperCall_all.ts +++ b/tests/cases/fourslash/codeFixConstructorForDerivedNeedSuperCall_all.ts @@ -9,6 +9,7 @@ verify.codeFixAll({ fixId: "constructorForDerivedNeedSuperCall", + fixAllDescription: "Add all missing super calls", newFileContent: `class C extends Object { constructor() { super(); diff --git a/tests/cases/fourslash/codeFixCorrectQualifiedNameToIndexedAccessType_all.ts b/tests/cases/fourslash/codeFixCorrectQualifiedNameToIndexedAccessType_all.ts index 334972ea13a..6f769b1f075 100644 --- a/tests/cases/fourslash/codeFixCorrectQualifiedNameToIndexedAccessType_all.ts +++ b/tests/cases/fourslash/codeFixCorrectQualifiedNameToIndexedAccessType_all.ts @@ -8,6 +8,7 @@ verify.codeFixAll({ fixId: "correctQualifiedNameToIndexedAccessType", + fixAllDescription: "Rewrite all as indexed access types", newFileContent: `interface Foo { bar: string; diff --git a/tests/cases/fourslash/codeFixDisableJsDiagnosticsInFile_all.ts b/tests/cases/fourslash/codeFixDisableJsDiagnosticsInFile_all.ts index 89f94520374..1a374e5f897 100644 --- a/tests/cases/fourslash/codeFixDisableJsDiagnosticsInFile_all.ts +++ b/tests/cases/fourslash/codeFixDisableJsDiagnosticsInFile_all.ts @@ -11,6 +11,7 @@ verify.codeFixAll({ fixId: "disableJsDiagnostics", + fixAllDescription: "Add '@ts-ignore' to all error messages", newFileContent: `let x = ""; // @ts-ignore diff --git a/tests/cases/fourslash/codeFixExtendsInterfaceBecomesImplements_all.ts b/tests/cases/fourslash/codeFixExtendsInterfaceBecomesImplements_all.ts index db039c92890..e1594c72fcb 100644 --- a/tests/cases/fourslash/codeFixExtendsInterfaceBecomesImplements_all.ts +++ b/tests/cases/fourslash/codeFixExtendsInterfaceBecomesImplements_all.ts @@ -6,6 +6,7 @@ verify.codeFixAll({ fixId: "extendsInterfaceBecomesImplements", + fixAllDescription: "Change all extended interfaces to 'implements'", newFileContent: `interface I {} class C implements I {} class D implements I {}`, diff --git a/tests/cases/fourslash/codeFixForgottenThisPropertyAccess_all.ts b/tests/cases/fourslash/codeFixForgottenThisPropertyAccess_all.ts index 75ded0290e6..ab95f6b3355 100644 --- a/tests/cases/fourslash/codeFixForgottenThisPropertyAccess_all.ts +++ b/tests/cases/fourslash/codeFixForgottenThisPropertyAccess_all.ts @@ -10,6 +10,7 @@ verify.codeFixAll({ fixId: "forgottenThisPropertyAccess", + fixAllDescription: "Add 'this.' to all unresolved variables matching a member name", newFileContent: `class C { foo: number; diff --git a/tests/cases/fourslash/codeFixInPropertyAccess_js.ts b/tests/cases/fourslash/codeFixInPropertyAccess_js.ts index 2afde9b5ee1..ef69d889626 100644 --- a/tests/cases/fourslash/codeFixInPropertyAccess_js.ts +++ b/tests/cases/fourslash/codeFixInPropertyAccess_js.ts @@ -18,6 +18,7 @@ verify.codeFixAll({ fixId: "correctQualifiedNameToIndexedAccessType", + fixAllDescription: "Rewrite all as indexed access types", newFileContent: `/** * @typedef Foo diff --git a/tests/cases/fourslash/codeFixInferFromUsage_all.ts b/tests/cases/fourslash/codeFixInferFromUsage_all.ts index 5a6b9d0cbd2..a093b9ab12c 100644 --- a/tests/cases/fourslash/codeFixInferFromUsage_all.ts +++ b/tests/cases/fourslash/codeFixInferFromUsage_all.ts @@ -13,6 +13,7 @@ verify.codeFixAll({ fixId: "inferFromUsage", + fixAllDescription: "Infer all types from usage", newFileContent: `function f(x: number, y: string) { x += 0; diff --git a/tests/cases/fourslash/codeFixSpelling_all.ts b/tests/cases/fourslash/codeFixSpelling_all.ts index 08b73b9ca1b..973f1e1503c 100644 --- a/tests/cases/fourslash/codeFixSpelling_all.ts +++ b/tests/cases/fourslash/codeFixSpelling_all.ts @@ -7,6 +7,7 @@ verify.codeFixAll({ fixId: "fixSpelling", + fixAllDescription: "Fix all detected spelling errors", newFileContent: `function f(s: string) { s.toString(); diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_all_delete.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_all_delete.ts index f42915249e9..8b7234732e2 100644 --- a/tests/cases/fourslash/codeFixUnusedIdentifier_all_delete.ts +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_all_delete.ts @@ -9,6 +9,7 @@ verify.codeFixAll({ fixId: "unusedIdentifier_delete", + fixAllDescription: "Delete all unused declarations", newFileContent: `function f() { }`, diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_all_prefix.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_all_prefix.ts index 55475321f94..fb8a2b9a3a4 100644 --- a/tests/cases/fourslash/codeFixUnusedIdentifier_all_prefix.ts +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_all_prefix.ts @@ -9,6 +9,7 @@ verify.codeFixAll({ fixId: "unusedIdentifier_prefix", + fixAllDescription: "Prefix all unused declarations with '_' where possible", newFileContent: `function f(_a, _b) { const x = 0; // Can't be prefixed, ignored diff --git a/tests/cases/fourslash/codeFixUseDefaultImport_all.ts b/tests/cases/fourslash/codeFixUseDefaultImport_all.ts index d3f82d7ed02..0154685d1fe 100644 --- a/tests/cases/fourslash/codeFixUseDefaultImport_all.ts +++ b/tests/cases/fourslash/codeFixUseDefaultImport_all.ts @@ -13,6 +13,7 @@ goTo.file("/b.ts"); verify.codeFixAll({ fixId: "useDefaultImport", + fixAllDescription: "Convert all to default imports", newFileContent: `import a1 from "./a"; import a2 from "./a";`, diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 60ccbf8963a..61899dde030 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -298,7 +298,7 @@ declare namespace FourSlashInterface { docCommentTemplateAt(markerName: string | FourSlashInterface.Marker, expectedOffset: number, expectedText: string): void; noDocCommentTemplateAt(markerName: string | FourSlashInterface.Marker): void; rangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void; - codeFixAll(options: { fixId: string, newFileContent: string, commands?: {}[] }): void; + codeFixAll(options: { fixId: string, fixAllDescription: string, newFileContent: string, commands?: {}[] }): void; fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, actionName: string, formattingOptions?: FormatCodeOptions): void; rangeIs(expectedText: string, includeWhiteSpace?: boolean): void; fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, formattingOptions?: FormatCodeOptions): void; From b5181208838f1b12d5fc09ab966b87225d98154e Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 18:48:27 -0700 Subject: [PATCH 26/75] findAllReferences: Respect search file set searching for references to an exported symbol (#22657) * findAllReferences: Respect search file set searching for references to an exported symbol * Remove debugging code --- src/harness/fourslash.ts | 10 +++---- src/services/findAllReferences.ts | 27 +++++++++---------- ...ntHighlights_moduleImport_filesToSearch.ts | 17 ++++++++++++ tests/cases/fourslash/fourslash.ts | 9 ++++--- 4 files changed, 40 insertions(+), 23 deletions(-) create mode 100644 tests/cases/fourslash/documentHighlights_moduleImport_filesToSearch.ts diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 17b3d52c040..270b3d15d2d 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2866,7 +2866,7 @@ Actual: ${stringify(fullActual)}`); } public verifyRangesWithSameTextAreDocumentHighlights() { - this.rangesByText().forEach(ranges => this.verifyRangesAreDocumentHighlights(ranges)); + this.rangesByText().forEach(ranges => this.verifyRangesAreDocumentHighlights(ranges, /*options*/ undefined)); } public verifyDocumentHighlightsOf(startRange: Range, ranges: Range[], options: FourSlashInterface.VerifyDocumentHighlightsOptions | undefined) { @@ -2875,9 +2875,9 @@ Actual: ${stringify(fullActual)}`); this.verifyDocumentHighlights(ranges, fileNames); } - public verifyRangesAreDocumentHighlights(ranges?: Range[]) { + public verifyRangesAreDocumentHighlights(ranges: Range[] | undefined, options: FourSlashInterface.VerifyDocumentHighlightsOptions | undefined) { ranges = ranges || this.getRanges(); - const fileNames = unique(ranges, range => range.fileName); + const fileNames = options && options.filesToSearch || unique(ranges, range => range.fileName); for (const range of ranges) { this.goToRangeStart(range); this.verifyDocumentHighlights(ranges, fileNames); @@ -4276,8 +4276,8 @@ namespace FourSlashInterface { this.state.verifyRangesAreRenameLocations(options); } - public rangesAreDocumentHighlights(ranges?: FourSlash.Range[]) { - this.state.verifyRangesAreDocumentHighlights(ranges); + public rangesAreDocumentHighlights(ranges?: FourSlash.Range[], options?: VerifyDocumentHighlightsOptions) { + this.state.verifyRangesAreDocumentHighlights(ranges, options); } public rangesWithSameTextAreDocumentHighlights() { diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 89627774fe6..bf646fb717f 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -366,7 +366,7 @@ namespace ts.FindAllReferences.Core { // otherwise we'll need to search globally (i.e. include each file). const scope = getSymbolScope(symbol); if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(isSourceFile(scope) && !contains(sourceFiles, scope))); } else { // Global search @@ -595,9 +595,8 @@ namespace ts.FindAllReferences.Core { function searchForImportedSymbol(symbol: Symbol, state: State): void { for (const declaration of symbol.declarations) { const exportingFile = declaration.getSourceFile(); - if (state.includesSourceFile(exportingFile)) { - getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, ImportExport.Import), state); - } + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, ImportExport.Import), state, state.includesSourceFile(exportingFile)); } } @@ -800,9 +799,9 @@ namespace ts.FindAllReferences.Core { return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references }] : undefined; } - function getReferencesInSourceFile(sourceFile: SourceFile, search: Search, state: State): void { + function getReferencesInSourceFile(sourceFile: SourceFile, search: Search, state: State, addReferencesHere = true): void { state.cancellationToken.throwIfCancellationRequested(); - return getReferencesInContainer(sourceFile, sourceFile, search, state); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); } /** @@ -810,17 +809,17 @@ namespace ts.FindAllReferences.Core { * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). * searchLocation: a node where the search value */ - function getReferencesInContainer(container: Node, sourceFile: SourceFile, search: Search, state: State): void { + function getReferencesInContainer(container: Node, sourceFile: SourceFile, search: Search, state: State, addReferencesHere: boolean): void { if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container)) { - getReferencesAtLocation(sourceFile, position, search, state); + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } - function getReferencesAtLocation(sourceFile: SourceFile, position: number, search: Search, state: State): void { + function getReferencesAtLocation(sourceFile: SourceFile, position: number, search: Search, state: State, addReferencesHere: boolean): void { const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { @@ -855,7 +854,7 @@ namespace ts.FindAllReferences.Core { if (isExportSpecifier(parent)) { Debug.assert(referenceLocation.kind === SyntaxKind.Identifier); - getReferencesAtExportSpecifier(referenceLocation as Identifier, referenceSymbol, parent, search, state); + getReferencesAtExportSpecifier(referenceLocation as Identifier, referenceSymbol, parent, search, state, addReferencesHere); return; } @@ -867,7 +866,7 @@ namespace ts.FindAllReferences.Core { switch (state.specialSearchKind) { case SpecialSearchKind.None: - addReference(referenceLocation, relatedSymbol, state); + if (addReferencesHere) addReference(referenceLocation, relatedSymbol, state); break; case SpecialSearchKind.Constructor: addConstructorReferences(referenceLocation, sourceFile, search, state); @@ -882,7 +881,7 @@ namespace ts.FindAllReferences.Core { getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation: Identifier, referenceSymbol: Symbol, exportSpecifier: ExportSpecifier, search: Search, state: State): void { + function getReferencesAtExportSpecifier(referenceLocation: Identifier, referenceSymbol: Symbol, exportSpecifier: ExportSpecifier, search: Search, state: State, addReferencesHere: boolean): void { const { parent, propertyName, name } = exportSpecifier; const exportDeclaration = parent.parent; const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -900,7 +899,7 @@ namespace ts.FindAllReferences.Core { addRef(); } - if (!state.options.isForRename && state.markSeenReExportRHS(name)) { + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { addReference(name, referenceSymbol, state); } } @@ -925,7 +924,7 @@ namespace ts.FindAllReferences.Core { } function addRef() { - addReference(referenceLocation, localSymbol, state); + if (addReferencesHere) addReference(referenceLocation, localSymbol, state); } } diff --git a/tests/cases/fourslash/documentHighlights_moduleImport_filesToSearch.ts b/tests/cases/fourslash/documentHighlights_moduleImport_filesToSearch.ts new file mode 100644 index 00000000000..53dc470a82a --- /dev/null +++ b/tests/cases/fourslash/documentHighlights_moduleImport_filesToSearch.ts @@ -0,0 +1,17 @@ +/// + +// @Filename: /node_modules/@types/foo/index.d.ts +////export const x: number; + +// @Filename: /a.ts +////import * as foo from "foo"; +////foo.[|x|]; + +// @Filename: /b.ts +////import { [|x|] } from "foo"; + +// @Filename: /c.ts +////import { x } from "foo"; + +const [r0, r1] = test.ranges(); +verify.rangesAreDocumentHighlights(test.ranges(), { filesToSearch: ["/a.ts", "/b.ts"] }); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 61899dde030..55f2afe747e 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -311,11 +311,9 @@ declare namespace FourSlashInterface { navigationItemsListContains(name: string, kind: string, searchValue: string, matchKind: string, fileName?: string, parentName?: string): void; occurrencesAtPositionContains(range: Range, isWriteAccess?: boolean): void; occurrencesAtPositionCount(expectedCount: number): void; - rangesAreDocumentHighlights(ranges?: Range[]): void; + rangesAreDocumentHighlights(ranges?: Range[], options?: VerifyDocumentHighlightsOptions): void; rangesWithSameTextAreDocumentHighlights(): void; - documentHighlightsOf(startRange: Range, ranges: Range[], options?: { - filesToSearch?: ReadonlyArray; - }): void; + documentHighlightsOf(startRange: Range, ranges: Range[], options?: VerifyDocumentHighlightsOptions): void; completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]): void; /** * This method *requires* a contiguous, complete, and ordered stream of classifications for a file. @@ -529,6 +527,9 @@ declare namespace FourSlashInterface { range?: Range; code: number; } + interface VerifyDocumentHighlightsOptions { + filesToSearch?: ReadonlyArray; + } interface UserPreferences { quotePreference?: "double" | "single"; includeCompletionsForModuleExports?: boolean; From ddb7bb22dc315a73b96f4d1b1bade0014e5b0dbf Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 27 Mar 2018 19:28:58 -0700 Subject: [PATCH 27/75] Add regression test for GH #21871 (#22733) --- .../amdDeclarationEmitNoExtraDeclare.js | 86 +++++++++++++++++++ .../amdDeclarationEmitNoExtraDeclare.symbols | 43 ++++++++++ .../amdDeclarationEmitNoExtraDeclare.types | 47 ++++++++++ .../amdDeclarationEmitNoExtraDeclare.ts | 22 +++++ 4 files changed, 198 insertions(+) create mode 100644 tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js create mode 100644 tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.symbols create mode 100644 tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.types create mode 100644 tests/cases/compiler/amdDeclarationEmitNoExtraDeclare.ts diff --git a/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js new file mode 100644 index 00000000000..3f6ecf1ca36 --- /dev/null +++ b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js @@ -0,0 +1,86 @@ +//// [tests/cases/compiler/amdDeclarationEmitNoExtraDeclare.ts] //// + +//// [Class.ts] +import { Configurable } from "./Configurable" + +export class HiddenClass {} + +export class ActualClass extends Configurable(HiddenClass) {} +//// [Configurable.ts] +export type Constructor = { + new(...args: any[]): T; +} +export function Configurable>(base: T): T { + return class extends base { + + constructor(...args: any[]) { + super(...args); + } + + }; +} + + +//// [dist.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 __()); + }; +})(); +define("Configurable", ["require", "exports"], function (require, exports) { + "use strict"; + exports.__esModule = true; + function Configurable(base) { + return /** @class */ (function (_super) { + __extends(class_1, _super); + function class_1() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _super.apply(this, args) || this; + } + return class_1; + }(base)); + } + exports.Configurable = Configurable; +}); +define("Class", ["require", "exports", "Configurable"], function (require, exports, Configurable_1) { + "use strict"; + exports.__esModule = true; + var HiddenClass = /** @class */ (function () { + function HiddenClass() { + } + return HiddenClass; + }()); + exports.HiddenClass = HiddenClass; + var ActualClass = /** @class */ (function (_super) { + __extends(ActualClass, _super); + function ActualClass() { + return _super !== null && _super.apply(this, arguments) || this; + } + return ActualClass; + }(Configurable_1.Configurable(HiddenClass))); + exports.ActualClass = ActualClass; +}); + + +//// [dist.d.ts] +declare module "Configurable" { + export type Constructor = { + new (...args: any[]): T; + }; + export function Configurable>(base: T): T; +} +declare module "Class" { + export class HiddenClass { + } + const ActualClass_base: typeof HiddenClass; + export class ActualClass extends ActualClass_base { + } +} diff --git a/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.symbols b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.symbols new file mode 100644 index 00000000000..e3754a46eed --- /dev/null +++ b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.symbols @@ -0,0 +1,43 @@ +=== tests/cases/compiler/Class.ts === +import { Configurable } from "./Configurable" +>Configurable : Symbol(Configurable, Decl(Class.ts, 0, 8)) + +export class HiddenClass {} +>HiddenClass : Symbol(HiddenClass, Decl(Class.ts, 0, 45)) + +export class ActualClass extends Configurable(HiddenClass) {} +>ActualClass : Symbol(ActualClass, Decl(Class.ts, 2, 27)) +>Configurable : Symbol(Configurable, Decl(Class.ts, 0, 8)) +>HiddenClass : Symbol(HiddenClass, Decl(Class.ts, 0, 45)) + +=== tests/cases/compiler/Configurable.ts === +export type Constructor = { +>Constructor : Symbol(Constructor, Decl(Configurable.ts, 0, 0)) +>T : Symbol(T, Decl(Configurable.ts, 0, 24)) + + new(...args: any[]): T; +>args : Symbol(args, Decl(Configurable.ts, 1, 8)) +>T : Symbol(T, Decl(Configurable.ts, 0, 24)) +} +export function Configurable>(base: T): T { +>Configurable : Symbol(Configurable, Decl(Configurable.ts, 2, 1)) +>T : Symbol(T, Decl(Configurable.ts, 3, 29)) +>Constructor : Symbol(Constructor, Decl(Configurable.ts, 0, 0)) +>base : Symbol(base, Decl(Configurable.ts, 3, 56)) +>T : Symbol(T, Decl(Configurable.ts, 3, 29)) +>T : Symbol(T, Decl(Configurable.ts, 3, 29)) + + return class extends base { +>base : Symbol(base, Decl(Configurable.ts, 3, 56)) + + constructor(...args: any[]) { +>args : Symbol(args, Decl(Configurable.ts, 6, 20)) + + super(...args); +>super : Symbol(T, Decl(Configurable.ts, 3, 29)) +>args : Symbol(args, Decl(Configurable.ts, 6, 20)) + } + + }; +} + diff --git a/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.types b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.types new file mode 100644 index 00000000000..2953ede4026 --- /dev/null +++ b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.types @@ -0,0 +1,47 @@ +=== tests/cases/compiler/Class.ts === +import { Configurable } from "./Configurable" +>Configurable : {}>(base: T) => T + +export class HiddenClass {} +>HiddenClass : HiddenClass + +export class ActualClass extends Configurable(HiddenClass) {} +>ActualClass : ActualClass +>Configurable(HiddenClass) : HiddenClass +>Configurable : {}>(base: T) => T +>HiddenClass : typeof HiddenClass + +=== tests/cases/compiler/Configurable.ts === +export type Constructor = { +>Constructor : Constructor +>T : T + + new(...args: any[]): T; +>args : any[] +>T : T +} +export function Configurable>(base: T): T { +>Configurable : >(base: T) => T +>T : T +>Constructor : Constructor +>base : T +>T : T +>T : T + + return class extends base { +>class extends base { constructor(...args: any[]) { super(...args); } } : { new (...args: any[]): (Anonymous class); prototype: Configurable.(Anonymous class); } & T +>base : {} + + constructor(...args: any[]) { +>args : any[] + + super(...args); +>super(...args) : void +>super : T +>...args : any +>args : any[] + } + + }; +} + diff --git a/tests/cases/compiler/amdDeclarationEmitNoExtraDeclare.ts b/tests/cases/compiler/amdDeclarationEmitNoExtraDeclare.ts new file mode 100644 index 00000000000..fb70a40df94 --- /dev/null +++ b/tests/cases/compiler/amdDeclarationEmitNoExtraDeclare.ts @@ -0,0 +1,22 @@ +// @declaration: true +// @module: amd +// @out: dist.js +// @filename: Class.ts +import { Configurable } from "./Configurable" + +export class HiddenClass {} + +export class ActualClass extends Configurable(HiddenClass) {} +// @filename: Configurable.ts +export type Constructor = { + new(...args: any[]): T; +} +export function Configurable>(base: T): T { + return class extends base { + + constructor(...args: any[]) { + super(...args); + } + + }; +} From 4f1656035bce0d3d43738a7ddce2d0e69e4e1f98 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 19:36:16 -0700 Subject: [PATCH 28/75] findAllReferences: Consistently use getTextSpan (#22847) * findAllReferences: Consistently use getTextSpan * Remove initializer --- src/services/findAllReferences.ts | 15 ++++----------- .../findAllRefsForComputedProperties.ts | 19 +++++++++---------- .../findAllRefsForComputedProperties2.ts | 19 +++++++++---------- 3 files changed, 22 insertions(+), 31 deletions(-) diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index bf646fb717f..e742a7f1030 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -132,15 +132,8 @@ namespace ts.FindAllReferences { const { node, name, kind, displayParts } = info; const sourceFile = node.getSourceFile(); - return { - containerKind: ScriptElementKind.unknown, - containerName: "", - fileName: sourceFile.fileName, - kind, - name, - textSpan: createTextSpanFromNode(node, sourceFile), - displayParts - }; + const textSpan = getTextSpan(isComputedPropertyName(node) ? node.expression : node, sourceFile); + return { containerKind: ScriptElementKind.unknown, containerName: "", fileName: sourceFile.fileName, kind, name, textSpan, displayParts }; } function getDefinitionKindAndDisplayParts(symbol: Symbol, checker: TypeChecker, node: Node): { displayParts: SymbolDisplayPart[], kind: ScriptElementKind } { @@ -218,8 +211,8 @@ namespace ts.FindAllReferences { return { fileName, span }; } - function getTextSpan(node: Node): TextSpan { - let start = node.getStart(); + function getTextSpan(node: Node, sourceFile?: SourceFile): TextSpan { + let start = node.getStart(sourceFile); let end = node.getEnd(); if (node.kind === SyntaxKind.StringLiteral) { start += 1; diff --git a/tests/cases/fourslash/findAllRefsForComputedProperties.ts b/tests/cases/fourslash/findAllRefsForComputedProperties.ts index 3df35cbfd76..5e11ec6f357 100644 --- a/tests/cases/fourslash/findAllRefsForComputedProperties.ts +++ b/tests/cases/fourslash/findAllRefsForComputedProperties.ts @@ -1,25 +1,24 @@ /// ////interface I { -//// [|["[|{| "isDefinition": true |}prop1|]"]|]: () => void; +//// ["[|{| "isDefinition": true |}prop1|]"]: () => void; ////} //// ////class C implements I { -//// [|["[|{| "isDefinition": true |}prop1|]"]|]: any; +//// ["[|{| "isDefinition": true |}prop1|]"]: any; ////} //// ////var x: I = { -//// [|["[|{| "isDefinition": true |}prop1|]"]|]: function () { }, +//// ["[|{| "isDefinition": true |}prop1|]"]: function () { }, ////} -// TODO: GH#22690 -const [r0Big, r0, r1Big, r1, r2Big, r2] = test.ranges(); +const [r0, r1, r2] = test.ranges(); verify.referenceGroups([r0, r1], [ - { definition: { text: '(property) I["prop1"]: () => void', range: r0Big }, ranges: [r0, r2] }, - { definition: { text: '(property) C["prop1"]: any', range: r1Big }, ranges: [r1] }, + { definition: { text: '(property) I["prop1"]: () => void', range: r0 }, ranges: [r0, r2] }, + { definition: { text: '(property) C["prop1"]: any', range: r1 }, ranges: [r1] }, ]); verify.referenceGroups(r2, [ - { definition: { text: '(property) I["prop1"]: () => void', range: r0Big }, ranges: [r0] }, - { definition: { text: '(property) C["prop1"]: any', range: r1Big }, ranges: [r1] }, - { definition: { text: '(property) ["prop1"]: () => void', range: r2Big }, ranges: [r2] }, + { definition: { text: '(property) I["prop1"]: () => void', range: r0 }, ranges: [r0] }, + { definition: { text: '(property) C["prop1"]: any', range: r1 }, ranges: [r1] }, + { definition: { text: '(property) ["prop1"]: () => void', range: r2 }, ranges: [r2] }, ]); diff --git a/tests/cases/fourslash/findAllRefsForComputedProperties2.ts b/tests/cases/fourslash/findAllRefsForComputedProperties2.ts index c38487d58d3..1461dc304a5 100644 --- a/tests/cases/fourslash/findAllRefsForComputedProperties2.ts +++ b/tests/cases/fourslash/findAllRefsForComputedProperties2.ts @@ -1,25 +1,24 @@ /// ////interface I { -//// [|[[|{| "isDefinition": true |}42|]]|](): void; +//// [[|{| "isDefinition": true |}42|]](): void; ////} //// ////class C implements I { -//// [|[[|{| "isDefinition": true |}42|]]|]: any; +//// [[|{| "isDefinition": true |}42|]]: any; ////} //// ////var x: I = { -//// [|["[|{| "isDefinition": true |}42|]"]|]: function () { } +//// ["[|{| "isDefinition": true |}42|]"]: function () { } ////} -// TODO: GH#22690 -const [r0Big, r0, r1Big, r1, r2Big, r2] = test.ranges(); +const [r0, r1, r2] = test.ranges(); verify.referenceGroups([r0, r1], [ - { definition: { text: '(method) I[42](): void', range: r0Big }, ranges: [r0, r2] }, - { definition: { text: '(property) C[42]: any', range: r1Big }, ranges: [r1] }, + { definition: { text: '(method) I[42](): void', range: r0 }, ranges: [r0, r2] }, + { definition: { text: '(property) C[42]: any', range: r1 }, ranges: [r1] }, ]); verify.referenceGroups(r2, [ - { definition: { text: '(method) I[42](): void', range: r0Big }, ranges: [r0] }, - { definition: { text: '(property) C[42]: any', range: r1Big }, ranges: [r1] }, - { definition: { text: '(property) ["42"]: () => void', range: r2Big }, ranges: [r2] }, + { definition: { text: '(method) I[42](): void', range: r0 }, ranges: [r0] }, + { definition: { text: '(property) C[42]: any', range: r1 }, ranges: [r1] }, + { definition: { text: '(property) ["42"]: () => void', range: r2 }, ranges: [r2] }, ]); From 6118f211d1b650f061084d9b5c74cfa4e64cc7a7 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 19:36:42 -0700 Subject: [PATCH 29/75] Add 'isParameterPropertyModifier' helper (#22841) --- src/compiler/parser.ts | 13 -------- src/compiler/utilities.ts | 10 ++++++ src/services/codefixes/inferFromUsage.ts | 16 +-------- src/services/completions.ts | 42 ++++-------------------- 4 files changed, 17 insertions(+), 64 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index b5c780de934..c3709fa4e0c 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -5461,19 +5461,6 @@ namespace ts { return finishNode(node); } - function isClassMemberModifier(idToken: SyntaxKind) { - switch (idToken) { - case SyntaxKind.PublicKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.StaticKeyword: - case SyntaxKind.ReadonlyKeyword: - return true; - default: - return false; - } - } - function isClassMemberStart(): boolean { let idToken: SyntaxKind; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index fa49837fa84..1022e6c11eb 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -5436,6 +5436,16 @@ namespace ts { return false; } + /* @internal */ + export function isParameterPropertyModifier(kind: SyntaxKind): boolean { + return !!(modifierToFlag(kind) & ModifierFlags.ParameterPropertyModifier); + } + + /* @internal */ + export function isClassMemberModifier(idToken: SyntaxKind): boolean { + return isParameterPropertyModifier(idToken) || idToken === SyntaxKind.StaticKeyword; + } + export function isModifier(node: Node): node is Modifier { return isModifierKind(node.kind); } diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 8d46bbf4ded..8398bc7c6d5 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -58,7 +58,7 @@ namespace ts.codefix { } function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, seenFunctions?: Map): Declaration | undefined { - if (!isAllowedTokenKind(token.kind)) { + if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken) { return undefined; } @@ -125,20 +125,6 @@ namespace ts.codefix { } } - 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 annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, cancellationToken: CancellationToken): void { if (isIdentifier(declaration.name)) { annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); diff --git a/src/services/completions.ts b/src/services/completions.ts index 57e071efc1a..c0f11d516b9 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1645,7 +1645,7 @@ namespace ts.Completions { function isConstructorParameterCompletion(node: Node) { return node.parent && isParameterOfConstructorDeclaration(node.parent) && - (isConstructorParameterCompletionKeyword(node.kind) || isDeclarationName(node)); + (isParameterPropertyModifier(node.kind) || isDeclarationName(node)); } /** @@ -1840,7 +1840,7 @@ namespace ts.Completions { // - its name of the parameter and not being edited // eg. constructor(a |<- this shouldnt show completion if (!isIdentifier(contextToken) || - isConstructorParameterCompletionKeyword(keywordForNode(contextToken)) || + isParameterPropertyModifier(keywordForNode(contextToken)) || isCurrentlyEditingNode(contextToken)) { return false; } @@ -2118,9 +2118,9 @@ namespace ts.Completions { case KeywordCompletionFilters.InterfaceElementKeywords: return isInterfaceOrTypeLiteralCompletionKeyword(kind); case KeywordCompletionFilters.ConstructorParameterKeywords: - return isConstructorParameterCompletionKeyword(kind); + return isParameterPropertyModifier(kind); case KeywordCompletionFilters.FunctionLikeBodyKeywords: - return isFunctionLikeBodyCompletionKeyword(kind); + return !isClassMemberCompletionKeyword(kind); case KeywordCompletionFilters.TypeKeywords: return isTypeKeyword(kind); default: @@ -2135,17 +2135,14 @@ namespace ts.Completions { function isClassMemberCompletionKeyword(kind: SyntaxKind) { switch (kind) { - case SyntaxKind.PublicKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.PrivateKeyword: case SyntaxKind.AbstractKeyword: - case SyntaxKind.StaticKeyword: case SyntaxKind.ConstructorKeyword: - case SyntaxKind.ReadonlyKeyword: case SyntaxKind.GetKeyword: case SyntaxKind.SetKeyword: case SyntaxKind.AsyncKeyword: return true; + default: + return isClassMemberModifier(kind); } } @@ -2153,33 +2150,6 @@ namespace ts.Completions { return isIdentifier(node) ? node.originalKeywordKind || SyntaxKind.Unknown : node.kind; } - function isConstructorParameterCompletionKeyword(kind: SyntaxKind) { - switch (kind) { - case SyntaxKind.PublicKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.ReadonlyKeyword: - return true; - } - } - - function isFunctionLikeBodyCompletionKeyword(kind: SyntaxKind) { - switch (kind) { - case SyntaxKind.PublicKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.ReadonlyKeyword: - case SyntaxKind.ConstructorKeyword: - case SyntaxKind.StaticKeyword: - case SyntaxKind.AbstractKeyword: - case SyntaxKind.GetKeyword: - case SyntaxKind.SetKeyword: - case SyntaxKind.UndefinedKeyword: - return false; - } - return true; - } - function isEqualityOperatorKind(kind: SyntaxKind): kind is EqualityOperator { switch (kind) { case SyntaxKind.EqualsEqualsEqualsToken: From 659dc03f6869477e5422f32dd54f94bae39df1fc Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 19:36:54 -0700 Subject: [PATCH 30/75] completions: isNewIdentifierLocation = false for string literal where all legal values are known (#22933) --- .../fixClassIncorrectlyImplementsInterface.ts | 4 +-- src/services/completions.ts | 32 ++++++++++++------- ...nForQuotedPropertyInPropertyAssignment1.ts | 4 +-- ...nForQuotedPropertyInPropertyAssignment2.ts | 4 +-- ...nForQuotedPropertyInPropertyAssignment3.ts | 4 +-- .../fourslash/completionForStringLiteral2.ts | 15 +++------ .../fourslash/completionForStringLiteral3.ts | 10 +----- .../fourslash/completionForStringLiteral7.ts | 7 ++-- .../completionListInvalidMemberNames.ts | 3 +- .../completionsJsPropertyAssignment.ts | 3 +- .../fourslash/completionsJsdocTypeTagCast.ts | 2 +- ...letionsStringLiteral_fromTypeConstraint.ts | 3 +- tests/cases/fourslash/completionsUnion.ts | 3 +- 13 files changed, 42 insertions(+), 52 deletions(-) diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 695bbdda4b0..91815edb775 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -48,10 +48,10 @@ namespace ts.codefix { const classType = checker.getTypeAtLocation(classDeclaration); - if (!checker.getIndexTypeOfType(classType, IndexKind.Number)) { + if (!classType.getNumberIndexType()) { createMissingIndexSignatureDeclaration(implementedType, IndexKind.Number); } - if (!checker.getIndexTypeOfType(classType, IndexKind.String)) { + if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, IndexKind.String); } diff --git a/src/services/completions.ts b/src/services/completions.ts index c0f11d516b9..ebc3674129e 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -86,11 +86,11 @@ namespace ts.Completions { case StringLiteralCompletionKind.Properties: { const entries: CompletionEntry[] = []; getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, ScriptTarget.ESNext, log, CompletionKind.String, preferences); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries }; } case StringLiteralCompletionKind.Types: { const entries = completion.types.map(type => ({ name: type.value, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.typeElement, sortText: "0" })); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; } default: return Debug.assertNever(completion); @@ -360,9 +360,14 @@ namespace ts.Completions { } const enum StringLiteralCompletionKind { Paths, Properties, Types } + interface StringLiteralCompletionsFromProperties { + readonly kind: StringLiteralCompletionKind.Properties; + readonly symbols: ReadonlyArray; + readonly hasIndexSignature: boolean; + } type StringLiteralCompletion = | { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray } - | { readonly kind: StringLiteralCompletionKind.Properties, readonly symbols: ReadonlyArray } + | StringLiteralCompletionsFromProperties | { readonly kind: StringLiteralCompletionKind.Types, readonly types: ReadonlyArray }; function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { switch (node.parent.kind) { @@ -377,7 +382,7 @@ namespace ts.Completions { // bar: string; // } // let x: Foo["/*completion position*/"] - return { kind: StringLiteralCompletionKind.Properties, symbols: typeChecker.getTypeFromTypeNode((node.parent.parent as IndexedAccessTypeNode).objectType).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((node.parent.parent as IndexedAccessTypeNode).objectType)); default: return undefined; } @@ -396,8 +401,7 @@ namespace ts.Completions { // foo({ // '/*completion position*/' // }); - const type = typeChecker.getContextualType(node.parent.parent); - return { kind: StringLiteralCompletionKind.Properties, symbols: type && type.getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); } return fromContextualType(); @@ -410,7 +414,7 @@ namespace ts.Completions { // } // let a: A; // a['/*completion position*/'] - return { kind: StringLiteralCompletionKind.Properties, symbols: typeChecker.getTypeAtLocation(expression).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); } return undefined; } @@ -454,6 +458,10 @@ namespace ts.Completions { } } + function stringLiteralCompletionsFromProperties(type: Type | undefined): StringLiteralCompletionsFromProperties | undefined { + return type && { kind: StringLiteralCompletionKind.Properties, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } + function getStringLiteralTypes(type: Type, typeChecker: TypeChecker, uniques = createMap()): ReadonlyArray { if (type && type.flags & TypeFlags.TypeParameter) { type = type.getConstraint(); @@ -1051,7 +1059,7 @@ namespace ts.Completions { } function addTypeProperties(type: Type): void { - isNewIdentifierLocation = !!type.getStringIndexType() || !!type.getNumberIndexType(); + isNewIdentifierLocation = hasIndexSignature(type); if (isSourceFileJavaScript(sourceFile)) { // In javascript files, for union types, we don't just get the members that @@ -1454,11 +1462,9 @@ namespace ts.Completions { let existingMembers: ReadonlyArray; if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) { - // We are completing on contextual types, but may also include properties - // other than those within the declared type. - isNewIdentifierLocation = true; const typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return GlobalsSearch.Fail; + isNewIdentifierLocation = hasIndexSignature(typeForObject); typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); existingMembers = objectLikeContainer.properties; } @@ -2247,4 +2253,8 @@ namespace ts.Completions { function isFromObjectTypeDeclaration(node: Node): boolean { return node.parent && (isClassElement(node.parent) || isTypeElement(node.parent)) && isObjectTypeDeclaration(node.parent.parent); } + + function hasIndexSignature(type: Type): boolean { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } } diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts index ab218cea93d..1b1cbe9a4df 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts @@ -13,5 +13,5 @@ //// '/*1*/': '' //// } -verify.completionsAt("0", ["jspm", '"jspm:browser"', '"jspm:dev"', '"jspm:node"'], { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["jspm", "jspm:browser", "jspm:dev", "jspm:node"], { isNewIdentifierLocation: true }); +verify.completionsAt("0", ["jspm", '"jspm:browser"', '"jspm:dev"', '"jspm:node"']); +verify.completionsAt("1", ["jspm", "jspm:browser", "jspm:dev", "jspm:node"]); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts index 66ba4ada241..669e58bdac1 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts @@ -19,5 +19,5 @@ //// } //// } -verify.completionsAt("0", ["jspm", '"jspm:browser"', '"jspm:dev"', '"jspm:node"'], { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["jspm", "jspm:browser", "jspm:dev", "jspm:node"], { isNewIdentifierLocation: true }); +verify.completionsAt("0", ["jspm", '"jspm:browser"', '"jspm:dev"', '"jspm:node"']); +verify.completionsAt("1", ["jspm", "jspm:browser", "jspm:dev", "jspm:node"]); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts index 1ab9aa4a8cf..7878750c6fa 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts @@ -15,5 +15,5 @@ //// '/*1*/': "" //// } -verify.completionsAt("0", ["jspm", '"jspm:browser"'], { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["jspm", "jspm:browser"], { isNewIdentifierLocation: true }); +verify.completionsAt("0", ["jspm", '"jspm:browser"']); +verify.completionsAt("1", ["jspm", "jspm:browser"]); diff --git a/tests/cases/fourslash/completionForStringLiteral2.ts b/tests/cases/fourslash/completionForStringLiteral2.ts index 9b00208c729..2bc783f7e53 100644 --- a/tests/cases/fourslash/completionForStringLiteral2.ts +++ b/tests/cases/fourslash/completionForStringLiteral2.ts @@ -5,16 +5,11 @@ //// bar: 0, //// "some other name": 1 ////}; +////declare const p: { [s: string]: any, a: number }; //// ////o["/*1*/bar"]; -////o["/*2*/ +////o["/*2*/ ; +////p["/*3*/"]; -goTo.marker('1'); -verify.completionListContains("foo"); -verify.completionListAllowsNewIdentifier(); -verify.completionListCount(3); - -goTo.marker('2'); -verify.completionListContains("some other name"); -verify.completionListAllowsNewIdentifier(); -verify.completionListCount(3); +verify.completionsAt(["1", "2"], ["foo", "bar", "some other name"]); +verify.completionsAt("3", ["a"], { isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteral3.ts b/tests/cases/fourslash/completionForStringLiteral3.ts index 238ba74b4d8..7b4713a81a7 100644 --- a/tests/cases/fourslash/completionForStringLiteral3.ts +++ b/tests/cases/fourslash/completionForStringLiteral3.ts @@ -9,12 +9,4 @@ //// ////f("/*2*/ -goTo.marker('1'); -verify.completionListContains("A"); -verify.completionListAllowsNewIdentifier(); -verify.completionListCount(3); - -goTo.marker('2'); -verify.completionListContains("A"); -verify.completionListAllowsNewIdentifier(); -verify.completionListCount(3); +verify.completionsAt(["1", "2"], ["A", "B", "C"]); diff --git a/tests/cases/fourslash/completionForStringLiteral7.ts b/tests/cases/fourslash/completionForStringLiteral7.ts index 6b7bead2a66..23a12f9ea4b 100644 --- a/tests/cases/fourslash/completionForStringLiteral7.ts +++ b/tests/cases/fourslash/completionForStringLiteral7.ts @@ -5,8 +5,5 @@ ////function f(x: T, ...args: U[]) { }; ////f("/*1*/", "/*2*/", "/*3*/"); -// TODO: GH#22907 -const options = { isNewIdentifierLocation: true }; -verify.completionsAt("1", ["foo", "bar"], options); -verify.completionsAt("2", ["oof", "rab"], options); -verify.completionsAt("3", ["oof", "rab"], options); +verify.completionsAt("1", ["foo", "bar"]); +verify.completionsAt(["2", "3"], ["oof", "rab"]); diff --git a/tests/cases/fourslash/completionListInvalidMemberNames.ts b/tests/cases/fourslash/completionListInvalidMemberNames.ts index 291ea945b29..3dc54274e83 100644 --- a/tests/cases/fourslash/completionListInvalidMemberNames.ts +++ b/tests/cases/fourslash/completionListInvalidMemberNames.ts @@ -14,8 +14,7 @@ ////x[|./*a*/|]; ////x["/*b*/"]; -// TODO: GH#22907 -verify.completionsAt("b", ["foo ", "bar", "break", "any", "#", "$", "b", "1b"], { isNewIdentifierLocation: true }); +verify.completionsAt("b", ["foo ", "bar", "break", "any", "#", "$", "b", "1b"]); const replacementSpan = test.ranges()[0]; verify.completionsAt("a", [ diff --git a/tests/cases/fourslash/completionsJsPropertyAssignment.ts b/tests/cases/fourslash/completionsJsPropertyAssignment.ts index fa758188ea9..c7e8a9ad268 100644 --- a/tests/cases/fourslash/completionsJsPropertyAssignment.ts +++ b/tests/cases/fourslash/completionsJsPropertyAssignment.ts @@ -7,5 +7,4 @@ ////const x = { p: "x" }; ////x.p = "/**/"; -// TODO: GH#22907 -verify.completionsAt("", ["x", "y"], { isNewIdentifierLocation: true }); +verify.completionsAt("", ["x", "y"]); diff --git a/tests/cases/fourslash/completionsJsdocTypeTagCast.ts b/tests/cases/fourslash/completionsJsdocTypeTagCast.ts index 8cd78103e34..822069feb53 100644 --- a/tests/cases/fourslash/completionsJsdocTypeTagCast.ts +++ b/tests/cases/fourslash/completionsJsdocTypeTagCast.ts @@ -4,4 +4,4 @@ // @Filename: /a.js ////const x = /** @type {{ s: string }} */ ({ /**/ }); -verify.completionsAt("", ["s", "x"], { isNewIdentifierLocation: true }); +verify.completionsAt("", ["s", "x"]); diff --git a/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts b/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts index 18941eb35ea..cb3f1a31fe2 100644 --- a/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts +++ b/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts @@ -3,5 +3,4 @@ ////interface Foo { foo: string; bar: string; } ////type T = Pick; -// TODO: GH#22907 -verify.completionsAt("", ["foo", "bar"], { isNewIdentifierLocation: true }); +verify.completionsAt("", ["foo", "bar"]); diff --git a/tests/cases/fourslash/completionsUnion.ts b/tests/cases/fourslash/completionsUnion.ts index 4ee701dddbe..d9d1d3c792f 100644 --- a/tests/cases/fourslash/completionsUnion.ts +++ b/tests/cases/fourslash/completionsUnion.ts @@ -7,5 +7,4 @@ // We specifically filter out any array-like types. // Private members will be excluded by `createUnionOrIntersectionProperty`. -// TODO: GH#22907 -verify.completionsAt("", ["x"], { isNewIdentifierLocation: true }); +verify.completionsAt("", ["x"]); From e60348be46ad6e14c43c5606b295a2f4a16fc33d Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 27 Mar 2018 20:15:43 -0700 Subject: [PATCH 31/75] Inline isParameterOfConstructorDeclaration (#22838) --- src/services/completions.ts | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index ebc3674129e..e7bbb47513f 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1644,14 +1644,9 @@ namespace ts.Completions { return undefined; } - function isParameterOfConstructorDeclaration(node: Node) { - return isParameter(node) && isConstructorDeclaration(node.parent); - } - - function isConstructorParameterCompletion(node: Node) { - return node.parent && - isParameterOfConstructorDeclaration(node.parent) && - (isParameterPropertyModifier(node.kind) || isDeclarationName(node)); + function isConstructorParameterCompletion(node: Node): boolean { + return !!node.parent && isParameter(node.parent) && isConstructorDeclaration(node.parent.parent) + && (isParameterPropertyModifier(node.kind) || isDeclarationName(node)); } /** From 0e403087927d2d4a22d32e306f358c8b51a11d1f Mon Sep 17 00:00:00 2001 From: Andrew Faulkner Date: Tue, 27 Mar 2018 23:42:01 -0400 Subject: [PATCH 32/75] Fix typo in Array Type Literals section of spec Extra end bracket in 1st example code block under Array Type Literals subsection of the spec --- doc/spec.md | 13468 +++++++++++++++++++++++++------------------------- 1 file changed, 6734 insertions(+), 6734 deletions(-) diff --git a/doc/spec.md b/doc/spec.md index fa69d321056..ed99088443f 100644 --- a/doc/spec.md +++ b/doc/spec.md @@ -1,6738 +1,6738 @@ -# TypeScript Language Specification - -Version 1.8 - -January, 2016 - -
- -Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ("OWF 1.0") as of October 1, 2012. The OWF 1.0 is available at [http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0](http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0). - -TypeScript is a trademark of Microsoft Corporation. - -
- -## Table of Contents - -* [1 Introduction](#1) - * [1.1 Ambient Declarations](#1.1) - * [1.2 Function Types](#1.2) - * [1.3 Object Types](#1.3) - * [1.4 Structural Subtyping](#1.4) - * [1.5 Contextual Typing](#1.5) - * [1.6 Classes](#1.6) - * [1.7 Enum Types](#1.7) - * [1.8 Overloading on String Parameters](#1.8) - * [1.9 Generic Types and Functions](#1.9) - * [1.10 Namespaces](#1.10) - * [1.11 Modules](#1.11) -* [2 Basic Concepts](#2) - * [2.1 Grammar Conventions](#2.1) - * [2.2 Names](#2.2) - * [2.2.1 Reserved Words](#2.2.1) - * [2.2.2 Property Names](#2.2.2) - * [2.2.3 Computed Property Names](#2.2.3) - * [2.3 Declarations](#2.3) - * [2.4 Scopes](#2.4) -* [3 Types](#3) - * [3.1 The Any Type](#3.1) - * [3.2 Primitive Types](#3.2) - * [3.2.1 The Number Type](#3.2.1) - * [3.2.2 The Boolean Type](#3.2.2) - * [3.2.3 The String Type](#3.2.3) - * [3.2.4 The Symbol Type](#3.2.4) - * [3.2.5 The Void Type](#3.2.5) - * [3.2.6 The Null Type](#3.2.6) - * [3.2.7 The Undefined Type](#3.2.7) - * [3.2.8 Enum Types](#3.2.8) - * [3.2.9 String Literal Types](#3.2.9) - * [3.3 Object Types](#3.3) - * [3.3.1 Named Type References](#3.3.1) - * [3.3.2 Array Types](#3.3.2) - * [3.3.3 Tuple Types](#3.3.3) - * [3.3.4 Function Types](#3.3.4) - * [3.3.5 Constructor Types](#3.3.5) - * [3.3.6 Members](#3.3.6) - * [3.4 Union Types](#3.4) - * [3.5 Intersection Types](#3.5) - * [3.6 Type Parameters](#3.6) - * [3.6.1 Type Parameter Lists](#3.6.1) - * [3.6.2 Type Argument Lists](#3.6.2) - * [3.6.3 This-types](#3.6.3) - * [3.7 Named Types](#3.7) - * [3.8 Specifying Types](#3.8) - * [3.8.1 Predefined Types](#3.8.1) - * [3.8.2 Type References](#3.8.2) - * [3.8.3 Object Type Literals](#3.8.3) - * [3.8.4 Array Type Literals](#3.8.4) - * [3.8.5 Tuple Type Literals](#3.8.5) - * [3.8.6 Union Type Literals](#3.8.6) - * [3.8.7 Intersection Type Literals](#3.8.7) - * [3.8.8 Function Type Literals](#3.8.8) - * [3.8.9 Constructor Type Literals](#3.8.9) - * [3.8.10 Type Queries](#3.8.10) - * [3.8.11 This-Type References](#3.8.11) - * [3.9 Specifying Members](#3.9) - * [3.9.1 Property Signatures](#3.9.1) - * [3.9.2 Call Signatures](#3.9.2) - * [3.9.3 Construct Signatures](#3.9.3) - * [3.9.4 Index Signatures](#3.9.4) - * [3.9.5 Method Signatures](#3.9.5) - * [3.10 Type Aliases](#3.10) - * [3.11 Type Relationships](#3.11) - * [3.11.1 Apparent Members](#3.11.1) - * [3.11.2 Type and Member Identity](#3.11.2) - * [3.11.3 Subtypes and Supertypes](#3.11.3) - * [3.11.4 Assignment Compatibility](#3.11.4) - * [3.11.5 Excess Properties](#3.11.5) - * [3.11.6 Contextual Signature Instantiation](#3.11.6) - * [3.11.7 Type Inference](#3.11.7) - * [3.11.8 Recursive Types](#3.11.8) - * [3.12 Widened Types](#3.12) -* [4 Expressions](#4) - * [4.1 Values and References](#4.1) - * [4.2 The this Keyword](#4.2) - * [4.3 Identifiers](#4.3) - * [4.4 Literals](#4.4) - * [4.5 Object Literals](#4.5) - * [4.6 Array Literals](#4.6) - * [4.7 Template Literals](#4.7) - * [4.8 Parentheses](#4.8) - * [4.9 The super Keyword](#4.9) - * [4.9.1 Super Calls](#4.9.1) - * [4.9.2 Super Property Access](#4.9.2) - * [4.10 Function Expressions](#4.10) - * [4.11 Arrow Functions](#4.11) - * [4.12 Class Expressions](#4.12) - * [4.13 Property Access](#4.13) - * [4.14 The new Operator](#4.14) - * [4.15 Function Calls](#4.15) - * [4.15.1 Overload Resolution](#4.15.1) - * [4.15.2 Type Argument Inference](#4.15.2) - * [4.15.3 Grammar Ambiguities](#4.15.3) - * [4.16 Type Assertions](#4.16) - * [4.17 JSX Expressions](#4.17) - * [4.18 Unary Operators](#4.18) - * [4.18.1 The ++ and -- operators](#4.18.1) - * [4.18.2 The +, –, and ~ operators](#4.18.2) - * [4.18.3 The ! operator](#4.18.3) - * [4.18.4 The delete Operator](#4.18.4) - * [4.18.5 The void Operator](#4.18.5) - * [4.18.6 The typeof Operator](#4.18.6) - * [4.19 Binary Operators](#4.19) - * [4.19.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators](#4.19.1) - * [4.19.2 The + operator](#4.19.2) - * [4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators](#4.19.3) - * [4.19.4 The instanceof operator](#4.19.4) - * [4.19.5 The in operator](#4.19.5) - * [4.19.6 The && operator](#4.19.6) - * [4.19.7 The || operator](#4.19.7) - * [4.20 The Conditional Operator](#4.20) - * [4.21 Assignment Operators](#4.21) - * [4.21.1 Destructuring Assignment](#4.21.1) - * [4.22 The Comma Operator](#4.22) - * [4.23 Contextually Typed Expressions](#4.23) - * [4.24 Type Guards](#4.24) -* [5 Statements](#5) - * [5.1 Blocks](#5.1) - * [5.2 Variable Statements](#5.2) - * [5.2.1 Simple Variable Declarations](#5.2.1) - * [5.2.2 Destructuring Variable Declarations](#5.2.2) - * [5.2.3 Implied Type](#5.2.3) - * [5.3 Let and Const Declarations](#5.3) - * [5.4 If, Do, and While Statements](#5.4) - * [5.5 For Statements](#5.5) - * [5.6 For-In Statements](#5.6) - * [5.7 For-Of Statements](#5.7) - * [5.8 Continue Statements](#5.8) - * [5.9 Break Statements](#5.9) - * [5.10 Return Statements](#5.10) - * [5.11 With Statements](#5.11) - * [5.12 Switch Statements](#5.12) - * [5.13 Throw Statements](#5.13) - * [5.14 Try Statements](#5.14) -* [6 Functions](#6) - * [6.1 Function Declarations](#6.1) - * [6.2 Function Overloads](#6.2) - * [6.3 Function Implementations](#6.3) - * [6.4 Destructuring Parameter Declarations](#6.4) - * [6.5 Generic Functions](#6.5) - * [6.6 Code Generation](#6.6) - * [6.7 Generator Functions](#6.7) - * [6.8 Asynchronous Functions](#6.8) - * [6.9 Type Guard Functions](#6.9) -* [7 Interfaces](#7) - * [7.1 Interface Declarations](#7.1) - * [7.2 Declaration Merging](#7.2) - * [7.3 Interfaces Extending Classes](#7.3) - * [7.4 Dynamic Type Checks](#7.4) -* [8 Classes](#8) - * [8.1 Class Declarations](#8.1) - * [8.1.1 Class Heritage Specification](#8.1.1) - * [8.1.2 Class Body](#8.1.2) - * [8.2 Members](#8.2) - * [8.2.1 Instance and Static Members](#8.2.1) - * [8.2.2 Accessibility](#8.2.2) - * [8.2.3 Inheritance and Overriding](#8.2.3) - * [8.2.4 Class Types](#8.2.4) - * [8.2.5 Constructor Function Types](#8.2.5) - * [8.3 Constructor Declarations](#8.3) - * [8.3.1 Constructor Parameters](#8.3.1) - * [8.3.2 Super Calls](#8.3.2) - * [8.3.3 Automatic Constructors](#8.3.3) - * [8.4 Property Member Declarations](#8.4) - * [8.4.1 Member Variable Declarations](#8.4.1) - * [8.4.2 Member Function Declarations](#8.4.2) - * [8.4.3 Member Accessor Declarations](#8.4.3) - * [8.4.4 Dynamic Property Declarations](#8.4.4) - * [8.5 Index Member Declarations](#8.5) - * [8.6 Decorators](#8.6) - * [8.7 Code Generation](#8.7) - * [8.7.1 Classes Without Extends Clauses](#8.7.1) - * [8.7.2 Classes With Extends Clauses](#8.7.2) -* [9 Enums](#9) - * [9.1 Enum Declarations](#9.1) - * [9.2 Enum Members](#9.2) - * [9.3 Declaration Merging](#9.3) - * [9.4 Constant Enum Declarations](#9.4) - * [9.5 Code Generation](#9.5) -* [10 Namespaces](#10) - * [10.1 Namespace Declarations](#10.1) - * [10.2 Namespace Body](#10.2) - * [10.3 Import Alias Declarations](#10.3) - * [10.4 Export Declarations](#10.4) - * [10.5 Declaration Merging](#10.5) - * [10.6 Code Generation](#10.6) -* [11 Scripts and Modules](#11) - * [11.1 Programs and Source Files](#11.1) - * [11.1.1 Source Files Dependencies](#11.1.1) - * [11.2 Scripts](#11.2) - * [11.3 Modules](#11.3) - * [11.3.1 Module Names](#11.3.1) - * [11.3.2 Import Declarations](#11.3.2) - * [11.3.3 Import Require Declarations](#11.3.3) - * [11.3.4 Export Declarations](#11.3.4) - * [11.3.5 Export Assignments](#11.3.5) - * [11.3.6 CommonJS Modules](#11.3.6) - * [11.3.7 AMD Modules](#11.3.7) -* [12 Ambients](#12) - * [12.1 Ambient Declarations](#12.1) - * [12.1.1 Ambient Variable Declarations](#12.1.1) - * [12.1.2 Ambient Function Declarations](#12.1.2) - * [12.1.3 Ambient Class Declarations](#12.1.3) - * [12.1.4 Ambient Enum Declarations](#12.1.4) - * [12.1.5 Ambient Namespace Declarations](#12.1.5) - * [12.2 Ambient Module Declarations](#12.2) -* [A Grammar](#A) - * [A.1 Types](#A.1) - * [A.2 Expressions](#A.2) - * [A.3 Statements](#A.3) - * [A.4 Functions](#A.4) - * [A.5 Interfaces](#A.5) - * [A.6 Classes](#A.6) - * [A.7 Enums](#A.7) - * [A.8 Namespaces](#A.8) - * [A.9 Scripts and Modules](#A.9) - * [A.10 Ambients](#A.10) - -
- -# 1 Introduction - -JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript's optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code re-factoring. - -TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development. - -TypeScript syntax includes all features of ECMAScript 2015, including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code. - -Classes enable programmers to express common object-oriented patterns in a standard way, making features like inheritance more readable and interoperable. Modules enable programmers to organize their code into components while avoiding naming conflicts. The TypeScript compiler provides module code generation options that support either static or dynamic loading of module contents. - -TypeScript also provides to JavaScript programmers a system of optional type annotations. These type annotations are like the JSDoc comments found in the Closure system, but in TypeScript they are integrated directly into the language syntax. This integration makes the code more readable and reduces the maintenance cost of synchronizing type annotations with their corresponding variables. - -The TypeScript type system enables programmers to express limits on the capabilities of JavaScript objects, and to use tools that enforce these limits. To minimize the number of annotations needed for tools to become useful, the TypeScript type system makes extensive use of type inference. For example, from the following statement, TypeScript will infer that the variable 'i' has the type number. - -```TypeScript -var i = 0; -``` - -TypeScript will infer from the following function definition that the function f has return type string. - -```TypeScript -function f() { - return "hello"; -} -``` - -To benefit from this inference, a programmer can use the TypeScript language service. For example, a code editor can incorporate the TypeScript language service and use the service to find the members of a string object as in the following screen shot. - +# TypeScript Language Specification + +Version 1.8 + +January, 2016 + +
+ +Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ("OWF 1.0") as of October 1, 2012. The OWF 1.0 is available at [http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0](http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0). + +TypeScript is a trademark of Microsoft Corporation. + +
+ +## Table of Contents + +* [1 Introduction](#1) + * [1.1 Ambient Declarations](#1.1) + * [1.2 Function Types](#1.2) + * [1.3 Object Types](#1.3) + * [1.4 Structural Subtyping](#1.4) + * [1.5 Contextual Typing](#1.5) + * [1.6 Classes](#1.6) + * [1.7 Enum Types](#1.7) + * [1.8 Overloading on String Parameters](#1.8) + * [1.9 Generic Types and Functions](#1.9) + * [1.10 Namespaces](#1.10) + * [1.11 Modules](#1.11) +* [2 Basic Concepts](#2) + * [2.1 Grammar Conventions](#2.1) + * [2.2 Names](#2.2) + * [2.2.1 Reserved Words](#2.2.1) + * [2.2.2 Property Names](#2.2.2) + * [2.2.3 Computed Property Names](#2.2.3) + * [2.3 Declarations](#2.3) + * [2.4 Scopes](#2.4) +* [3 Types](#3) + * [3.1 The Any Type](#3.1) + * [3.2 Primitive Types](#3.2) + * [3.2.1 The Number Type](#3.2.1) + * [3.2.2 The Boolean Type](#3.2.2) + * [3.2.3 The String Type](#3.2.3) + * [3.2.4 The Symbol Type](#3.2.4) + * [3.2.5 The Void Type](#3.2.5) + * [3.2.6 The Null Type](#3.2.6) + * [3.2.7 The Undefined Type](#3.2.7) + * [3.2.8 Enum Types](#3.2.8) + * [3.2.9 String Literal Types](#3.2.9) + * [3.3 Object Types](#3.3) + * [3.3.1 Named Type References](#3.3.1) + * [3.3.2 Array Types](#3.3.2) + * [3.3.3 Tuple Types](#3.3.3) + * [3.3.4 Function Types](#3.3.4) + * [3.3.5 Constructor Types](#3.3.5) + * [3.3.6 Members](#3.3.6) + * [3.4 Union Types](#3.4) + * [3.5 Intersection Types](#3.5) + * [3.6 Type Parameters](#3.6) + * [3.6.1 Type Parameter Lists](#3.6.1) + * [3.6.2 Type Argument Lists](#3.6.2) + * [3.6.3 This-types](#3.6.3) + * [3.7 Named Types](#3.7) + * [3.8 Specifying Types](#3.8) + * [3.8.1 Predefined Types](#3.8.1) + * [3.8.2 Type References](#3.8.2) + * [3.8.3 Object Type Literals](#3.8.3) + * [3.8.4 Array Type Literals](#3.8.4) + * [3.8.5 Tuple Type Literals](#3.8.5) + * [3.8.6 Union Type Literals](#3.8.6) + * [3.8.7 Intersection Type Literals](#3.8.7) + * [3.8.8 Function Type Literals](#3.8.8) + * [3.8.9 Constructor Type Literals](#3.8.9) + * [3.8.10 Type Queries](#3.8.10) + * [3.8.11 This-Type References](#3.8.11) + * [3.9 Specifying Members](#3.9) + * [3.9.1 Property Signatures](#3.9.1) + * [3.9.2 Call Signatures](#3.9.2) + * [3.9.3 Construct Signatures](#3.9.3) + * [3.9.4 Index Signatures](#3.9.4) + * [3.9.5 Method Signatures](#3.9.5) + * [3.10 Type Aliases](#3.10) + * [3.11 Type Relationships](#3.11) + * [3.11.1 Apparent Members](#3.11.1) + * [3.11.2 Type and Member Identity](#3.11.2) + * [3.11.3 Subtypes and Supertypes](#3.11.3) + * [3.11.4 Assignment Compatibility](#3.11.4) + * [3.11.5 Excess Properties](#3.11.5) + * [3.11.6 Contextual Signature Instantiation](#3.11.6) + * [3.11.7 Type Inference](#3.11.7) + * [3.11.8 Recursive Types](#3.11.8) + * [3.12 Widened Types](#3.12) +* [4 Expressions](#4) + * [4.1 Values and References](#4.1) + * [4.2 The this Keyword](#4.2) + * [4.3 Identifiers](#4.3) + * [4.4 Literals](#4.4) + * [4.5 Object Literals](#4.5) + * [4.6 Array Literals](#4.6) + * [4.7 Template Literals](#4.7) + * [4.8 Parentheses](#4.8) + * [4.9 The super Keyword](#4.9) + * [4.9.1 Super Calls](#4.9.1) + * [4.9.2 Super Property Access](#4.9.2) + * [4.10 Function Expressions](#4.10) + * [4.11 Arrow Functions](#4.11) + * [4.12 Class Expressions](#4.12) + * [4.13 Property Access](#4.13) + * [4.14 The new Operator](#4.14) + * [4.15 Function Calls](#4.15) + * [4.15.1 Overload Resolution](#4.15.1) + * [4.15.2 Type Argument Inference](#4.15.2) + * [4.15.3 Grammar Ambiguities](#4.15.3) + * [4.16 Type Assertions](#4.16) + * [4.17 JSX Expressions](#4.17) + * [4.18 Unary Operators](#4.18) + * [4.18.1 The ++ and -- operators](#4.18.1) + * [4.18.2 The +, –, and ~ operators](#4.18.2) + * [4.18.3 The ! operator](#4.18.3) + * [4.18.4 The delete Operator](#4.18.4) + * [4.18.5 The void Operator](#4.18.5) + * [4.18.6 The typeof Operator](#4.18.6) + * [4.19 Binary Operators](#4.19) + * [4.19.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators](#4.19.1) + * [4.19.2 The + operator](#4.19.2) + * [4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators](#4.19.3) + * [4.19.4 The instanceof operator](#4.19.4) + * [4.19.5 The in operator](#4.19.5) + * [4.19.6 The && operator](#4.19.6) + * [4.19.7 The || operator](#4.19.7) + * [4.20 The Conditional Operator](#4.20) + * [4.21 Assignment Operators](#4.21) + * [4.21.1 Destructuring Assignment](#4.21.1) + * [4.22 The Comma Operator](#4.22) + * [4.23 Contextually Typed Expressions](#4.23) + * [4.24 Type Guards](#4.24) +* [5 Statements](#5) + * [5.1 Blocks](#5.1) + * [5.2 Variable Statements](#5.2) + * [5.2.1 Simple Variable Declarations](#5.2.1) + * [5.2.2 Destructuring Variable Declarations](#5.2.2) + * [5.2.3 Implied Type](#5.2.3) + * [5.3 Let and Const Declarations](#5.3) + * [5.4 If, Do, and While Statements](#5.4) + * [5.5 For Statements](#5.5) + * [5.6 For-In Statements](#5.6) + * [5.7 For-Of Statements](#5.7) + * [5.8 Continue Statements](#5.8) + * [5.9 Break Statements](#5.9) + * [5.10 Return Statements](#5.10) + * [5.11 With Statements](#5.11) + * [5.12 Switch Statements](#5.12) + * [5.13 Throw Statements](#5.13) + * [5.14 Try Statements](#5.14) +* [6 Functions](#6) + * [6.1 Function Declarations](#6.1) + * [6.2 Function Overloads](#6.2) + * [6.3 Function Implementations](#6.3) + * [6.4 Destructuring Parameter Declarations](#6.4) + * [6.5 Generic Functions](#6.5) + * [6.6 Code Generation](#6.6) + * [6.7 Generator Functions](#6.7) + * [6.8 Asynchronous Functions](#6.8) + * [6.9 Type Guard Functions](#6.9) +* [7 Interfaces](#7) + * [7.1 Interface Declarations](#7.1) + * [7.2 Declaration Merging](#7.2) + * [7.3 Interfaces Extending Classes](#7.3) + * [7.4 Dynamic Type Checks](#7.4) +* [8 Classes](#8) + * [8.1 Class Declarations](#8.1) + * [8.1.1 Class Heritage Specification](#8.1.1) + * [8.1.2 Class Body](#8.1.2) + * [8.2 Members](#8.2) + * [8.2.1 Instance and Static Members](#8.2.1) + * [8.2.2 Accessibility](#8.2.2) + * [8.2.3 Inheritance and Overriding](#8.2.3) + * [8.2.4 Class Types](#8.2.4) + * [8.2.5 Constructor Function Types](#8.2.5) + * [8.3 Constructor Declarations](#8.3) + * [8.3.1 Constructor Parameters](#8.3.1) + * [8.3.2 Super Calls](#8.3.2) + * [8.3.3 Automatic Constructors](#8.3.3) + * [8.4 Property Member Declarations](#8.4) + * [8.4.1 Member Variable Declarations](#8.4.1) + * [8.4.2 Member Function Declarations](#8.4.2) + * [8.4.3 Member Accessor Declarations](#8.4.3) + * [8.4.4 Dynamic Property Declarations](#8.4.4) + * [8.5 Index Member Declarations](#8.5) + * [8.6 Decorators](#8.6) + * [8.7 Code Generation](#8.7) + * [8.7.1 Classes Without Extends Clauses](#8.7.1) + * [8.7.2 Classes With Extends Clauses](#8.7.2) +* [9 Enums](#9) + * [9.1 Enum Declarations](#9.1) + * [9.2 Enum Members](#9.2) + * [9.3 Declaration Merging](#9.3) + * [9.4 Constant Enum Declarations](#9.4) + * [9.5 Code Generation](#9.5) +* [10 Namespaces](#10) + * [10.1 Namespace Declarations](#10.1) + * [10.2 Namespace Body](#10.2) + * [10.3 Import Alias Declarations](#10.3) + * [10.4 Export Declarations](#10.4) + * [10.5 Declaration Merging](#10.5) + * [10.6 Code Generation](#10.6) +* [11 Scripts and Modules](#11) + * [11.1 Programs and Source Files](#11.1) + * [11.1.1 Source Files Dependencies](#11.1.1) + * [11.2 Scripts](#11.2) + * [11.3 Modules](#11.3) + * [11.3.1 Module Names](#11.3.1) + * [11.3.2 Import Declarations](#11.3.2) + * [11.3.3 Import Require Declarations](#11.3.3) + * [11.3.4 Export Declarations](#11.3.4) + * [11.3.5 Export Assignments](#11.3.5) + * [11.3.6 CommonJS Modules](#11.3.6) + * [11.3.7 AMD Modules](#11.3.7) +* [12 Ambients](#12) + * [12.1 Ambient Declarations](#12.1) + * [12.1.1 Ambient Variable Declarations](#12.1.1) + * [12.1.2 Ambient Function Declarations](#12.1.2) + * [12.1.3 Ambient Class Declarations](#12.1.3) + * [12.1.4 Ambient Enum Declarations](#12.1.4) + * [12.1.5 Ambient Namespace Declarations](#12.1.5) + * [12.2 Ambient Module Declarations](#12.2) +* [A Grammar](#A) + * [A.1 Types](#A.1) + * [A.2 Expressions](#A.2) + * [A.3 Statements](#A.3) + * [A.4 Functions](#A.4) + * [A.5 Interfaces](#A.5) + * [A.6 Classes](#A.6) + * [A.7 Enums](#A.7) + * [A.8 Namespaces](#A.8) + * [A.9 Scripts and Modules](#A.9) + * [A.10 Ambients](#A.10) + +
+ +#
1 Introduction + +JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript's optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code re-factoring. + +TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development. + +TypeScript syntax includes all features of ECMAScript 2015, including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code. + +Classes enable programmers to express common object-oriented patterns in a standard way, making features like inheritance more readable and interoperable. Modules enable programmers to organize their code into components while avoiding naming conflicts. The TypeScript compiler provides module code generation options that support either static or dynamic loading of module contents. + +TypeScript also provides to JavaScript programmers a system of optional type annotations. These type annotations are like the JSDoc comments found in the Closure system, but in TypeScript they are integrated directly into the language syntax. This integration makes the code more readable and reduces the maintenance cost of synchronizing type annotations with their corresponding variables. + +The TypeScript type system enables programmers to express limits on the capabilities of JavaScript objects, and to use tools that enforce these limits. To minimize the number of annotations needed for tools to become useful, the TypeScript type system makes extensive use of type inference. For example, from the following statement, TypeScript will infer that the variable 'i' has the type number. + +```TypeScript +var i = 0; +``` + +TypeScript will infer from the following function definition that the function f has return type string. + +```TypeScript +function f() { + return "hello"; +} +``` + +To benefit from this inference, a programmer can use the TypeScript language service. For example, a code editor can incorporate the TypeScript language service and use the service to find the members of a string object as in the following screen shot. +   ![](images/image1.png) - -In this example, the programmer benefits from type inference without providing type annotations. Some beneficial tools, however, do require the programmer to provide type annotations. In TypeScript, we can express a parameter requirement as in the following code fragment. - -```TypeScript -function f(s: string) { - return s; -} - -f({}); // Error -f("hello"); // Ok -``` - -This optional type annotation on the parameter 's' lets the TypeScript type checker know that the programmer expects parameter 's' to be of type 'string'. Within the body of function 'f', tools can assume 's' is of type 'string' and provide operator type checking and member completion consistent with this assumption. Tools can also signal an error on the first call to 'f', because 'f' expects a string, not an object, as its parameter. For the function 'f', the TypeScript compiler will emit the following JavaScript code: - -```TypeScript -function f(s) { - return s; -} -``` - -In the JavaScript output, all type annotations have been erased. In general, TypeScript erases all type information before emiting JavaScript. - -## 1.1 Ambient Declarations - -An ambient declaration introduces a variable into a TypeScript scope, but has zero impact on the emitted JavaScript program. Programmers can use ambient declarations to tell the TypeScript compiler that some other component will supply a variable. For example, by default the TypeScript compiler will print an error for uses of undefined variables. To add some of the common variables defined by browsers, a TypeScript programmer can use ambient declarations. The following example declares the 'document' object supplied by browsers. Because the declaration does not specify a type, the type 'any' is inferred. The type 'any' means that a tool can assume nothing about the shape or behavior of the document object. Some of the examples below will illustrate how programmers can use types to further characterize the expected behavior of an object. - -```TypeScript -declare var document; -document.title = "Hello"; // Ok because document has been declared -``` - -In the case of 'document', the TypeScript compiler automatically supplies a declaration, because TypeScript by default includes a file 'lib.d.ts' that provides interface declarations for the built-in JavaScript library as well as the Document Object Model. - -The TypeScript compiler does not include by default an interface for jQuery, so to use jQuery, a programmer could supply a declaration such as: - -```TypeScript -declare var $; -``` - -Section [1.3](#1.3) provides a more extensive example of how a programmer can add type information for jQuery and other libraries. - -## 1.2 Function Types - -Function expressions are a powerful feature of JavaScript. They enable function definitions to create closures: functions that capture information from the lexical scope surrounding the function's definition. Closures are currently JavaScript's only way of enforcing data encapsulation. By capturing and using environment variables, a closure can retain information that cannot be accessed from outside the closure. JavaScript programmers often use closures to express event handlers and other asynchronous callbacks, in which another software component, such as the DOM, will call back into JavaScript through a handler function. - -TypeScript function types make it possible for programmers to express the expected *signature* of a function. A function signature is a sequence of parameter types plus a return type. The following example uses function types to express the callback signature requirements of an asynchronous voting mechanism. - -```TypeScript -function vote(candidate: string, callback: (result: string) => any) { - // ... -} - -vote("BigPig", - function(result: string) { - if (result === "BigPig") { - // ... - } - } -); -``` - -In this example, the second parameter to 'vote' has the function type - -```TypeScript -(result: string) => any -``` - -which means the second parameter is a function returning type 'any' that has a single parameter of type 'string' named 'result'. - -Section [3.9.2](#3.9.2) provides additional information about function types. - -## 1.3 Object Types - -TypeScript programmers use *object types* to declare their expectations of object behavior. The following code uses an *object type literal* to specify the return type of the 'MakePoint' function. - -```TypeScript -var MakePoint: () => { - x: number; y: number; -}; -``` - -Programmers can give names to object types; we call named object types *interfaces*. For example, in the following code, an interface declares one required field (name) and one optional field (favoriteColor). - -```TypeScript -interface Friend { - name: string; - favoriteColor?: string; -} - -function add(friend: Friend) { - var name = friend.name; -} - -add({ name: "Fred" }); // Ok -add({ favoriteColor: "blue" }); // Error, name required -add({ name: "Jill", favoriteColor: "green" }); // Ok -``` - -TypeScript object types model the diversity of behaviors that a JavaScript object can exhibit. For example, the jQuery library defines an object, '$', that has methods, such as 'get' (which sends an Ajax message), and fields, such as 'browser' (which gives browser vendor information). However, jQuery clients can also call '$' as a function. The behavior of this function depends on the type of parameters passed to the function. - -The following code fragment captures a small subset of jQuery behavior, just enough to use jQuery in a simple way. - -```TypeScript -interface JQuery { - text(content: string); -} - -interface JQueryStatic { - get(url: string, callback: (data: string) => any); - (query: string): JQuery; -} - -declare var $: JQueryStatic; - -$.get("http://mysite.org/divContent", - function (data: string) { - $("div").text(data); - } -); -``` - -The 'JQueryStatic' interface references another interface: 'JQuery'. This interface represents a collection of one or more DOM elements. The jQuery library can perform many operations on such a collection, but in this example the jQuery client only needs to know that it can set the text content of each jQuery element in a collection by passing a string to the 'text' method. The 'JQueryStatic' interface also contains a method, 'get', that performs an Ajax get operation on the provided URL and arranges to invoke the provided callback upon receipt of a response. - -Finally, the 'JQueryStatic' interface contains a bare function signature - -```TypeScript -(query: string): JQuery; -``` - -The bare signature indicates that instances of the interface are callable. This example illustrates that TypeScript function types are just special cases of TypeScript object types. Specifically, function types are object types that contain one or more call signatures. For this reason we can write any function type as an object type literal. The following example uses both forms to describe the same type. - -```TypeScript -var f: { (): string; }; -var sameType: () => string = f; // Ok -var nope: () => number = sameType; // Error: type mismatch -``` - -We mentioned above that the '$' function behaves differently depending on the type of its parameter. So far, our jQuery typing only captures one of these behaviors: return an object of type 'JQuery' when passed a string. To specify multiple behaviors, TypeScript supports *overloading* of function signatures in object types. For example, we can add an additional call signature to the 'JQueryStatic' interface. - -```TypeScript -(ready: () => any): any; -``` - -This signature denotes that a function may be passed as the parameter of the '$' function. When a function is passed to '$', the jQuery library will invoke that function when a DOM document is ready. Because TypeScript supports overloading, tools can use TypeScript to show all available function signatures with their documentation tips and to give the correct documentation once a function has been called with a particular signature. - -A typical client would not need to add any additional typing but could just use a community-supplied typing to discover (through statement completion with documentation tips) and verify (through static checking) correct use of the library, as in the following screen shot. - + +In this example, the programmer benefits from type inference without providing type annotations. Some beneficial tools, however, do require the programmer to provide type annotations. In TypeScript, we can express a parameter requirement as in the following code fragment. + +```TypeScript +function f(s: string) { + return s; +} + +f({}); // Error +f("hello"); // Ok +``` + +This optional type annotation on the parameter 's' lets the TypeScript type checker know that the programmer expects parameter 's' to be of type 'string'. Within the body of function 'f', tools can assume 's' is of type 'string' and provide operator type checking and member completion consistent with this assumption. Tools can also signal an error on the first call to 'f', because 'f' expects a string, not an object, as its parameter. For the function 'f', the TypeScript compiler will emit the following JavaScript code: + +```TypeScript +function f(s) { + return s; +} +``` + +In the JavaScript output, all type annotations have been erased. In general, TypeScript erases all type information before emiting JavaScript. + +## 1.1 Ambient Declarations + +An ambient declaration introduces a variable into a TypeScript scope, but has zero impact on the emitted JavaScript program. Programmers can use ambient declarations to tell the TypeScript compiler that some other component will supply a variable. For example, by default the TypeScript compiler will print an error for uses of undefined variables. To add some of the common variables defined by browsers, a TypeScript programmer can use ambient declarations. The following example declares the 'document' object supplied by browsers. Because the declaration does not specify a type, the type 'any' is inferred. The type 'any' means that a tool can assume nothing about the shape or behavior of the document object. Some of the examples below will illustrate how programmers can use types to further characterize the expected behavior of an object. + +```TypeScript +declare var document; +document.title = "Hello"; // Ok because document has been declared +``` + +In the case of 'document', the TypeScript compiler automatically supplies a declaration, because TypeScript by default includes a file 'lib.d.ts' that provides interface declarations for the built-in JavaScript library as well as the Document Object Model. + +The TypeScript compiler does not include by default an interface for jQuery, so to use jQuery, a programmer could supply a declaration such as: + +```TypeScript +declare var $; +``` + +Section [1.3](#1.3) provides a more extensive example of how a programmer can add type information for jQuery and other libraries. + +## 1.2 Function Types + +Function expressions are a powerful feature of JavaScript. They enable function definitions to create closures: functions that capture information from the lexical scope surrounding the function's definition. Closures are currently JavaScript's only way of enforcing data encapsulation. By capturing and using environment variables, a closure can retain information that cannot be accessed from outside the closure. JavaScript programmers often use closures to express event handlers and other asynchronous callbacks, in which another software component, such as the DOM, will call back into JavaScript through a handler function. + +TypeScript function types make it possible for programmers to express the expected *signature* of a function. A function signature is a sequence of parameter types plus a return type. The following example uses function types to express the callback signature requirements of an asynchronous voting mechanism. + +```TypeScript +function vote(candidate: string, callback: (result: string) => any) { + // ... +} + +vote("BigPig", + function(result: string) { + if (result === "BigPig") { + // ... + } + } +); +``` + +In this example, the second parameter to 'vote' has the function type + +```TypeScript +(result: string) => any +``` + +which means the second parameter is a function returning type 'any' that has a single parameter of type 'string' named 'result'. + +Section [3.9.2](#3.9.2) provides additional information about function types. + +## 1.3 Object Types + +TypeScript programmers use *object types* to declare their expectations of object behavior. The following code uses an *object type literal* to specify the return type of the 'MakePoint' function. + +```TypeScript +var MakePoint: () => { + x: number; y: number; +}; +``` + +Programmers can give names to object types; we call named object types *interfaces*. For example, in the following code, an interface declares one required field (name) and one optional field (favoriteColor). + +```TypeScript +interface Friend { + name: string; + favoriteColor?: string; +} + +function add(friend: Friend) { + var name = friend.name; +} + +add({ name: "Fred" }); // Ok +add({ favoriteColor: "blue" }); // Error, name required +add({ name: "Jill", favoriteColor: "green" }); // Ok +``` + +TypeScript object types model the diversity of behaviors that a JavaScript object can exhibit. For example, the jQuery library defines an object, '$', that has methods, such as 'get' (which sends an Ajax message), and fields, such as 'browser' (which gives browser vendor information). However, jQuery clients can also call '$' as a function. The behavior of this function depends on the type of parameters passed to the function. + +The following code fragment captures a small subset of jQuery behavior, just enough to use jQuery in a simple way. + +```TypeScript +interface JQuery { + text(content: string); +} + +interface JQueryStatic { + get(url: string, callback: (data: string) => any); + (query: string): JQuery; +} + +declare var $: JQueryStatic; + +$.get("http://mysite.org/divContent", + function (data: string) { + $("div").text(data); + } +); +``` + +The 'JQueryStatic' interface references another interface: 'JQuery'. This interface represents a collection of one or more DOM elements. The jQuery library can perform many operations on such a collection, but in this example the jQuery client only needs to know that it can set the text content of each jQuery element in a collection by passing a string to the 'text' method. The 'JQueryStatic' interface also contains a method, 'get', that performs an Ajax get operation on the provided URL and arranges to invoke the provided callback upon receipt of a response. + +Finally, the 'JQueryStatic' interface contains a bare function signature + +```TypeScript +(query: string): JQuery; +``` + +The bare signature indicates that instances of the interface are callable. This example illustrates that TypeScript function types are just special cases of TypeScript object types. Specifically, function types are object types that contain one or more call signatures. For this reason we can write any function type as an object type literal. The following example uses both forms to describe the same type. + +```TypeScript +var f: { (): string; }; +var sameType: () => string = f; // Ok +var nope: () => number = sameType; // Error: type mismatch +``` + +We mentioned above that the '$' function behaves differently depending on the type of its parameter. So far, our jQuery typing only captures one of these behaviors: return an object of type 'JQuery' when passed a string. To specify multiple behaviors, TypeScript supports *overloading* of function signatures in object types. For example, we can add an additional call signature to the 'JQueryStatic' interface. + +```TypeScript +(ready: () => any): any; +``` + +This signature denotes that a function may be passed as the parameter of the '$' function. When a function is passed to '$', the jQuery library will invoke that function when a DOM document is ready. Because TypeScript supports overloading, tools can use TypeScript to show all available function signatures with their documentation tips and to give the correct documentation once a function has been called with a particular signature. + +A typical client would not need to add any additional typing but could just use a community-supplied typing to discover (through statement completion with documentation tips) and verify (through static checking) correct use of the library, as in the following screen shot. +   ![](images/image2.png) - -Section [3.3](#3.3) provides additional information about object types. - -## 1.4 Structural Subtyping - -Object types are compared *structurally*. For example, in the code fragment below, class 'CPoint' matches interface 'Point' because 'CPoint' has all of the required members of 'Point'. A class may optionally declare that it implements an interface, so that the compiler will check the declaration for structural compatibility. The example also illustrates that an object type can match the type inferred from an object literal, as long as the object literal supplies all of the required members. - -```TypeScript -interface Point { - x: number; - y: number; -} - -function getX(p: Point) { - return p.x; -} - -class CPoint { - x: number; - y: number; - constructor(x: number, y: number) { - this.x = x; - this.y = y; - } -} - -getX(new CPoint(0, 0)); // Ok, fields match - -getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok - -getX({ x: 0 }); // Error: supplied parameter does not match -``` - -See section [3.11](#3.11) for more information about type comparisons. - -## 1.5 Contextual Typing - -Ordinarily, TypeScript type inference proceeds "bottom-up": from the leaves of an expression tree to its root. In the following example, TypeScript infers 'number' as the return type of the function 'mul' by flowing type information bottom up in the return expression. - -```TypeScript -function mul(a: number, b: number) { - return a * b; -} -``` - -For variables and parameters without a type annotation or a default value, TypeScript infers type 'any', ensuring that compilers do not need non-local information about a function's call sites to infer the function's return type. Generally, this bottom-up approach provides programmers with a clear intuition about the flow of type information. - -However, in some limited contexts, inference proceeds "top-down" from the context of an expression. Where this happens, it is called contextual typing. Contextual typing helps tools provide excellent information when a programmer is using a type but may not know all of the details of the type. For example, in the jQuery example, above, the programmer supplies a function expression as the second parameter to the 'get' method. During typing of that expression, tools can assume that the type of the function expression is as given in the 'get' signature and can provide a template that includes parameter names and types. - -```TypeScript -$.get("http://mysite.org/divContent", - function (data) { - $("div").text(data); // TypeScript infers data is a string - } -); -``` - -Contextual typing is also useful for writing out object literals. As the programmer types the object literal, the contextual type provides information that enables tools to provide completion for object member names. - -Section [4.23](#4.23) provides additional information about contextually typed expressions. - -## 1.6 Classes - -JavaScript practice has two very common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as 'prototype.js' are typical of this practice. TypeScript's namespaces are a formalization of the module pattern. (The term "module pattern" is somewhat unfortunate now that ECMAScript 2015 formally supports modules in a manner different from what the module pattern prescribes. For this reason, TypeScript uses the term "namespace" for its formalization of the module pattern.) - -This section and the namespace section below will show how TypeScript emits consistent, idiomatic JavaScript when emitting ECMAScript 3 or 5 compliant code for classes and namespaces. The goal of TypeScript's translation is to emit exactly what a programmer would type when implementing a class or namespace unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We'll start with a simple BankAccount class. - -```TypeScript -class BankAccount { - balance = 0; - deposit(credit: number) { - this.balance += credit; - return this.balance; - } -} -``` - -This class generates the following JavaScript code. - -```TypeScript -var BankAccount = (function () { - function BankAccount() { - this.balance = 0; - } - BankAccount.prototype.deposit = function(credit) { - this.balance += credit; - return this.balance; - }; - return BankAccount; -})(); -``` - -This TypeScript class declaration creates a variable named 'BankAccount' whose value is the constructor function for 'BankAccount' instances. This declaration also creates an instance type of the same name. If we were to write this type as an interface it would look like the following. - -```TypeScript -interface BankAccount { - balance: number; - deposit(credit: number): number; -} -``` - -If we were to write out the function type declaration for the 'BankAccount' constructor variable, it would have the following form. - -```TypeScript -var BankAccount: new() => BankAccount; -``` - -The function signature is prefixed with the keyword 'new' indicating that the 'BankAccount' function must be called as a constructor. It is possible for a function's type to have both call and constructor signatures. For example, the type of the built-in JavaScript Date object includes both kinds of signatures. - -If we want to start our bank account with an initial balance, we can add to the 'BankAccount' class a constructor declaration. - -```TypeScript -class BankAccount { - balance: number; - constructor(initially: number) { - this.balance = initially; - } - deposit(credit: number) { - this.balance += credit; - return this.balance; - } -} -``` - -This version of the 'BankAccount' class requires us to introduce a constructor parameter and then assign it to the 'balance' field. To simplify this common case, TypeScript accepts the following shorthand syntax. - -```TypeScript -class BankAccount { - constructor(public balance: number) { - } - deposit(credit: number) { - this.balance += credit; - return this.balance; - } -} -``` - -The 'public' keyword denotes that the constructor parameter is to be retained as a field. Public is the default accessibility for class members, but a programmer can also specify private or protected accessibility for a class member. Accessibility is a design-time construct; it is enforced during static type checking but does not imply any runtime enforcement. - -TypeScript classes also support inheritance, as in the following example.* * - -```TypeScript -class CheckingAccount extends BankAccount { - constructor(balance: number) { - super(balance); - } - writeCheck(debit: number) { - this.balance -= debit; - } -} -``` - -In this example, the class 'CheckingAccount' *derives* from class 'BankAccount'. The constructor for 'CheckingAccount' calls the constructor for class 'BankAccount' using the 'super' keyword. In the emitted JavaScript code, the prototype of 'CheckingAccount' will chain to the prototype of 'BankAccount'. - -TypeScript classes may also specify static members. Static class members become properties of the class constructor. - -Section [8](#8) provides additional information about classes. - -## 1.7 Enum Types - -TypeScript enables programmers to summarize a set of numeric constants as an *enum type*. The example below creates an enum type to represent operators in a calculator application. - -```TypeScript -const enum Operator { - ADD, - DIV, - MUL, - SUB -} - -function compute(op: Operator, a: number, b: number) { - console.log("the operator is" + Operator[op]); - // ... -} -``` - -In this example, the compute function logs the operator 'op' using a feature of enum types: reverse mapping from the enum value ('op') to the string corresponding to that value. For example, the declaration of 'Operator' automatically assigns integers, starting from zero, to the listed enum members. Section [9](#9) describes how programmers can also explicitly assign integers to enum members, and can use any string to name an enum member. - -When enums are declared with the `const` modifier, the TypeScript compiler will emit for an enum member a JavaScript constant corresponding to that member's assigned value (annotated with a comment). This improves performance on many JavaScript engines. - -For example, the 'compute' function could contain a switch statement like the following. - -```TypeScript -switch (op) { - case Operator.ADD: - // execute add - break; - case Operator.DIV: - // execute div - break; - // ... -} -``` - -For this switch statement, the compiler will generate the following code. - -```TypeScript -switch (op) { - case 0 /* Operator.ADD */: - // execute add - break; - case 1 /* Operator.DIV */: - // execute div - break; - // ... -} -``` - -JavaScript implementations can use these explicit constants to generate efficient code for this switch statement, for example by building a jump table indexed by case value. - -## 1.8 Overloading on String Parameters - -An important goal of TypeScript is to provide accurate and straightforward types for existing JavaScript programming patterns. To that end, TypeScript includes generic types, discussed in the next section, and *overloading on string parameters*, the topic of this section. - -JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screen shot shows that the 'createElement' method of the 'document' object has multiple signatures, some of which identify the types returned when specific strings are passed into the method. - + +Section [3.3](#3.3) provides additional information about object types. + +## 1.4 Structural Subtyping + +Object types are compared *structurally*. For example, in the code fragment below, class 'CPoint' matches interface 'Point' because 'CPoint' has all of the required members of 'Point'. A class may optionally declare that it implements an interface, so that the compiler will check the declaration for structural compatibility. The example also illustrates that an object type can match the type inferred from an object literal, as long as the object literal supplies all of the required members. + +```TypeScript +interface Point { + x: number; + y: number; +} + +function getX(p: Point) { + return p.x; +} + +class CPoint { + x: number; + y: number; + constructor(x: number, y: number) { + this.x = x; + this.y = y; + } +} + +getX(new CPoint(0, 0)); // Ok, fields match + +getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok + +getX({ x: 0 }); // Error: supplied parameter does not match +``` + +See section [3.11](#3.11) for more information about type comparisons. + +## 1.5 Contextual Typing + +Ordinarily, TypeScript type inference proceeds "bottom-up": from the leaves of an expression tree to its root. In the following example, TypeScript infers 'number' as the return type of the function 'mul' by flowing type information bottom up in the return expression. + +```TypeScript +function mul(a: number, b: number) { + return a * b; +} +``` + +For variables and parameters without a type annotation or a default value, TypeScript infers type 'any', ensuring that compilers do not need non-local information about a function's call sites to infer the function's return type. Generally, this bottom-up approach provides programmers with a clear intuition about the flow of type information. + +However, in some limited contexts, inference proceeds "top-down" from the context of an expression. Where this happens, it is called contextual typing. Contextual typing helps tools provide excellent information when a programmer is using a type but may not know all of the details of the type. For example, in the jQuery example, above, the programmer supplies a function expression as the second parameter to the 'get' method. During typing of that expression, tools can assume that the type of the function expression is as given in the 'get' signature and can provide a template that includes parameter names and types. + +```TypeScript +$.get("http://mysite.org/divContent", + function (data) { + $("div").text(data); // TypeScript infers data is a string + } +); +``` + +Contextual typing is also useful for writing out object literals. As the programmer types the object literal, the contextual type provides information that enables tools to provide completion for object member names. + +Section [4.23](#4.23) provides additional information about contextually typed expressions. + +## 1.6 Classes + +JavaScript practice has two very common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as 'prototype.js' are typical of this practice. TypeScript's namespaces are a formalization of the module pattern. (The term "module pattern" is somewhat unfortunate now that ECMAScript 2015 formally supports modules in a manner different from what the module pattern prescribes. For this reason, TypeScript uses the term "namespace" for its formalization of the module pattern.) + +This section and the namespace section below will show how TypeScript emits consistent, idiomatic JavaScript when emitting ECMAScript 3 or 5 compliant code for classes and namespaces. The goal of TypeScript's translation is to emit exactly what a programmer would type when implementing a class or namespace unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We'll start with a simple BankAccount class. + +```TypeScript +class BankAccount { + balance = 0; + deposit(credit: number) { + this.balance += credit; + return this.balance; + } +} +``` + +This class generates the following JavaScript code. + +```TypeScript +var BankAccount = (function () { + function BankAccount() { + this.balance = 0; + } + BankAccount.prototype.deposit = function(credit) { + this.balance += credit; + return this.balance; + }; + return BankAccount; +})(); +``` + +This TypeScript class declaration creates a variable named 'BankAccount' whose value is the constructor function for 'BankAccount' instances. This declaration also creates an instance type of the same name. If we were to write this type as an interface it would look like the following. + +```TypeScript +interface BankAccount { + balance: number; + deposit(credit: number): number; +} +``` + +If we were to write out the function type declaration for the 'BankAccount' constructor variable, it would have the following form. + +```TypeScript +var BankAccount: new() => BankAccount; +``` + +The function signature is prefixed with the keyword 'new' indicating that the 'BankAccount' function must be called as a constructor. It is possible for a function's type to have both call and constructor signatures. For example, the type of the built-in JavaScript Date object includes both kinds of signatures. + +If we want to start our bank account with an initial balance, we can add to the 'BankAccount' class a constructor declaration. + +```TypeScript +class BankAccount { + balance: number; + constructor(initially: number) { + this.balance = initially; + } + deposit(credit: number) { + this.balance += credit; + return this.balance; + } +} +``` + +This version of the 'BankAccount' class requires us to introduce a constructor parameter and then assign it to the 'balance' field. To simplify this common case, TypeScript accepts the following shorthand syntax. + +```TypeScript +class BankAccount { + constructor(public balance: number) { + } + deposit(credit: number) { + this.balance += credit; + return this.balance; + } +} +``` + +The 'public' keyword denotes that the constructor parameter is to be retained as a field. Public is the default accessibility for class members, but a programmer can also specify private or protected accessibility for a class member. Accessibility is a design-time construct; it is enforced during static type checking but does not imply any runtime enforcement. + +TypeScript classes also support inheritance, as in the following example.* * + +```TypeScript +class CheckingAccount extends BankAccount { + constructor(balance: number) { + super(balance); + } + writeCheck(debit: number) { + this.balance -= debit; + } +} +``` + +In this example, the class 'CheckingAccount' *derives* from class 'BankAccount'. The constructor for 'CheckingAccount' calls the constructor for class 'BankAccount' using the 'super' keyword. In the emitted JavaScript code, the prototype of 'CheckingAccount' will chain to the prototype of 'BankAccount'. + +TypeScript classes may also specify static members. Static class members become properties of the class constructor. + +Section [8](#8) provides additional information about classes. + +## 1.7 Enum Types + +TypeScript enables programmers to summarize a set of numeric constants as an *enum type*. The example below creates an enum type to represent operators in a calculator application. + +```TypeScript +const enum Operator { + ADD, + DIV, + MUL, + SUB +} + +function compute(op: Operator, a: number, b: number) { + console.log("the operator is" + Operator[op]); + // ... +} +``` + +In this example, the compute function logs the operator 'op' using a feature of enum types: reverse mapping from the enum value ('op') to the string corresponding to that value. For example, the declaration of 'Operator' automatically assigns integers, starting from zero, to the listed enum members. Section [9](#9) describes how programmers can also explicitly assign integers to enum members, and can use any string to name an enum member. + +When enums are declared with the `const` modifier, the TypeScript compiler will emit for an enum member a JavaScript constant corresponding to that member's assigned value (annotated with a comment). This improves performance on many JavaScript engines. + +For example, the 'compute' function could contain a switch statement like the following. + +```TypeScript +switch (op) { + case Operator.ADD: + // execute add + break; + case Operator.DIV: + // execute div + break; + // ... +} +``` + +For this switch statement, the compiler will generate the following code. + +```TypeScript +switch (op) { + case 0 /* Operator.ADD */: + // execute add + break; + case 1 /* Operator.DIV */: + // execute div + break; + // ... +} +``` + +JavaScript implementations can use these explicit constants to generate efficient code for this switch statement, for example by building a jump table indexed by case value. + +## 1.8 Overloading on String Parameters + +An important goal of TypeScript is to provide accurate and straightforward types for existing JavaScript programming patterns. To that end, TypeScript includes generic types, discussed in the next section, and *overloading on string parameters*, the topic of this section. + +JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screen shot shows that the 'createElement' method of the 'document' object has multiple signatures, some of which identify the types returned when specific strings are passed into the method. +   ![](images/image3.png) - -The following code fragment uses this feature. Because the 'span' variable is inferred to have the type 'HTMLSpanElement', the code can reference without static error the 'isMultiline' property of 'span'. - -```TypeScript -var span = document.createElement("span"); -span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property -``` - -In the following screen shot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable 'e' is 'MouseEvent' and that therefore 'e' has a 'clientX' property. - + +The following code fragment uses this feature. Because the 'span' variable is inferred to have the type 'HTMLSpanElement', the code can reference without static error the 'isMultiline' property of 'span'. + +```TypeScript +var span = document.createElement("span"); +span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property +``` + +In the following screen shot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable 'e' is 'MouseEvent' and that therefore 'e' has a 'clientX' property. +   ![](images/image4.png) - -Section [3.9.2.4](#3.9.2.4) provides details on how to use string literals in function signatures. - -## 1.9 Generic Types and Functions - -Like overloading on string parameters, *generic types* make it easier for TypeScript to accurately capture the behavior of JavaScript libraries. Because they enable type information to flow from client code, through library code, and back into client code, generic types may do more than any other TypeScript feature to support detailed API descriptions. - -To illustrate this, let's take a look at part of the TypeScript interface for the built-in JavaScript array type. You can find this interface in the 'lib.d.ts' file that accompanies a TypeScript distribution. - -```TypeScript -interface Array { - reverse(): T[]; - sort(compareFn?: (a: T, b: T) => number): T[]; - // ... -} -``` - -Interface definitions, like the one above, can have one or more *type parameters*. In this case the 'Array' interface has a single parameter, 'T', that defines the element type for the array. The 'reverse' method returns an array with the same element type. The sort method takes an optional parameter, 'compareFn', whose type is a function that takes two parameters of type 'T' and returns a number. Finally, sort returns an array with element type 'T'. - -Functions can also have generic parameters. For example, the array interface contains a 'map' method, defined as follows: - -```TypeScript -map(func: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; -``` - -The map method, invoked on an array 'a' with element type 'T', will apply function 'func' to each element of 'a', returning a value of type 'U'. - -The TypeScript compiler can often infer generic method parameters, making it unnecessary for the programmer to explicitly provide them. In the following example, the compiler infers that parameter 'U' of the map method has type 'string', because the function passed to map returns a string. - -```TypeScript -function numberToString(a: number[]) { - var stringArray = a.map(v => v.toString()); - return stringArray; -} -``` - -The compiler infers in this example that the 'numberToString' function returns an array of strings. - -In TypeScript, classes can also have type parameters. The following code declares a class that implements a linked list of items of type 'T'. This code illustrates how programmers can *constrain* type parameters to extend a specific type. In this case, the items on the list must extend the type 'NamedItem'. This enables the programmer to implement the 'log' function, which logs the name of the item. - -```TypeScript -interface NamedItem { - name: string; -} - -class List { - next: List = null; - - constructor(public item: T) { - } - - insertAfter(item: T) { - var temp = this.next; - this.next = new List(item); - this.next.next = temp; - } - - log() { - console.log(this.item.name); - } - - // ... -} -``` - -Section [3.7](#3.7) provides further information about generic types. - -## 1.10 Namespaces - -Classes and interfaces support large-scale JavaScript development by providing a mechanism for describing how to use a software component that can be separated from that component's implementation. TypeScript enforces *encapsulation* of implementation in classes at design time (by restricting use of private and protected members), but cannot enforce encapsulation at runtime because all object properties are accessible at runtime. Future versions of JavaScript may provide *private names* which would enable runtime enforcement of private and protected members. - -In JavaScript, a very common way to enforce encapsulation at runtime is to use the module pattern: encapsulate private fields and methods using closure variables. The module pattern is a natural way to provide organizational structure and dynamic loading options by drawing a boundary around a software component. The module pattern can also provide the ability to introduce namespaces, avoiding use of the global namespace for most software components. - -The following example illustrates the JavaScript module pattern. - -```TypeScript -(function(exports) { - var key = generateSecretKey(); - function sendMessage(message) { - sendSecureMessage(message, key); - } - exports.sendMessage = sendMessage; -})(MessageModule); -``` - -This example illustrates the two essential elements of the module pattern: a *module closure* and a *module* *object*. The module closure is a function that encapsulates the module's implementation, in this case the variable 'key' and the function 'sendMessage'. The module object contains the exported variables and functions of the module. Simple modules may create and return the module object. The module above takes the module object as a parameter, 'exports', and adds the 'sendMessage' property to the module object. This *augmentation* approach simplifies dynamic loading of modules and also supports separation of module code into multiple files. - -The example assumes that an outer lexical scope defines the functions 'generateSecretKey' and 'sendSecureMessage'; it also assumes that the outer scope has assigned the module object to the variable 'MessageModule'. - -TypeScript namespaces provide a mechanism for succinctly expressing the module pattern. In TypeScript, programmers can combine the module pattern with the class pattern by nesting namespaces and classes within an outer namespace. - -The following example shows the definition and use of a simple namespace. - -```TypeScript -namespace M { - var s = "hello"; - export function f() { - return s; - } -} - -M.f(); -M.s; // Error, s is not exported -``` - -In this example, variable 's' is a private feature of the namespace, but function 'f' is exported from the namespace and accessible to code outside of the namespace. If we were to describe the effect of namespace 'M' in terms of interfaces and variables, we would write - -```TypeScript -interface M { - f(): string; -} - -var M: M; -``` - -The interface 'M' summarizes the externally visible behavior of namespace 'M'. In this example, we can use the same name for the interface as for the initialized variable because in TypeScript type names and variable names do not conflict: each lexical scope contains a variable declaration space and type declaration space (see section [2.3](#2.3) for more details). - -The TypeScript compiler emits the following JavaScript code for the namespace: - -```TypeScript -var M; -(function(M) { - var s = "hello"; - function f() { - return s; - } - M.f = f; -})(M || (M = {})); -``` - -In this case, the compiler assumes that the namespace object resides in global variable 'M', which may or may not have been initialized to the desired namespace object. - -## 1.11 Modules - -TypeScript also supports ECMAScript 2015 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 2015 compliant code and down-level ECMAScript 3 or 5 compliant code for a variety of module loading systems, including CommonJS, Asynchronous Module Definition (AMD), and Universal Module Definition (UMD). - -
- -#
2 Basic Concepts - -The remainder of this document is the formal specification of the TypeScript programming language and is intended to be read as an adjunct to the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition). This document describes the syntactic grammar added by TypeScript along with the compile-time processing and type checking performed by the TypeScript compiler, but it only minimally discusses the run-time behavior of programs since that is covered by the ECMAScript specification. - -## 2.1 Grammar Conventions - -The syntactic grammar added by TypeScript language is specified throughout this document using the existing conventions and production names of the ECMAScript grammar. In places where TypeScript augments an existing grammar production it is so noted. For example: - -  *Declaration:* *( Modified )* -   … -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *EnumDeclaration* - -The '*( Modified )*' annotation indicates that an existing grammar production is being replaced, and the '…' references the contents of the original grammar production. - -Similar to the ECMAScript grammar, if the phrase "*[no LineTerminator here]*" appears in the right-hand side of a production of the syntactic grammar, it indicates that the production is not a match if a *LineTerminator* occurs in the input stream at the indicated position. - -## 2.2 Names - -A core purpose of the TypeScript compiler is to track the named entities in a program and validate that they are used according to their designated meaning. Names in TypeScript can be written in several ways, depending on context. Specifically, a name can be written as - -* an *IdentifierName*, -* a *StringLiteral* in a property name, -* a *NumericLiteral* in a property name, or -* a *ComputedPropertyName* that denotes a well-known symbol ([2.2.3](#2.2.3)). - -Most commonly, names are written to conform with the *Identifier* production, which is any *IdentifierName* that isn't a reserved word. - -### 2.2.1 Reserved Words - -The following keywords are reserved and cannot be used as an *Identifier*: - -```TypeScript -break case catch class -const continue debugger default -delete do else enum -export extends false finally -for function if import -in instanceof new null -return super switch this -throw true try typeof -var void while with -``` - -The following keywords cannot be used as identifiers in strict mode code, but are otherwise not restricted: - -```TypeScript -implements interface let package -private protected public static -yield -``` - -The following keywords cannot be used as user defined type names, but are otherwise not restricted: - -```TypeScript -any boolean number string -symbol -``` - -The following keywords have special meaning in certain contexts, but are valid identifiers: - -```TypeScript -abstract as async await -constructor declare from get -is module namespace of -require set type -``` - -### 2.2.2 Property Names - -The *PropertyName* production from the ECMAScript grammar is reproduced below: - -  *PropertyName:* -   *LiteralPropertyName* -   *ComputedPropertyName* - -  *LiteralPropertyName:* -   *IdentifierName* -   *StringLiteral* -   *NumericLiteral* - -  *ComputedPropertyName:* -   `[` *AssignmentExpression* `]` - -A property name can be any identifier (including a reserved word), a string literal, a numeric literal, or a computed property name. String literals may be used to give properties names that are not valid identifiers, such as names containing blanks. Numeric literal property names are equivalent to string literal property names with the string representation of the numeric literal, as defined in the ECMAScript specification. - -### 2.2.3 Computed Property Names - -ECMAScript 2015 permits object literals and classes to declare members with computed property names. A computed property name specifies an expression that computes the actual property name at run-time. Because the final property name isn't known at compile-time, TypeScript can only perform limited checks for entities declared with computed property names. However, a subset of computed property names known as ***well-known symbols*** can be used anywhere a *PropertyName* is expected, including property names within types. A computed property name is a well-known symbol if it is of the form - -```TypeScript -[ Symbol . xxx ] -``` - -In a well-known symbol, the identifier to the right of the dot must denote a property of the primitive type `symbol` in the type of the global variable 'Symbol', or otherwise an error occurs. - -In a *PropertyName* that specifies a *ComputedPropertyName*, the computed property name is required to denote a well-known symbol unless the property name occurs in a property assignment of an object literal ([4.5](#4.5)) or a property member declaration in a non-ambient class ([8.4](#8.4)). - -Below is an example of an interface that declares a property with a well-known symbol name: - -```TypeScript -interface Iterable { - [Symbol.iterator](): Iterator; -} -``` - -*TODO: Update to reflect treatment of [computed property names with literal expressions](https://github.com/Microsoft/TypeScript/pull/5535)*. - -## 2.3 Declarations - -Declarations introduce names in their associated ***declaration spaces***. A name must be unique in its declaration space and can denote a ***value***, a ***type***, or a ***namespace***, or some combination thereof. Effectively, a single name can have as many as three distinct meanings. For example: - -```TypeScript -var X: string; // Value named X - -type X = number; // Type named X - -namespace X { // Namespace named X - type Y = string; -} -``` - -A name that denotes a value has an associated type (section [3](#3)) and can be referenced in expressions (section [4.3](#4.3)). A name that denotes a type can be used by itself in a type reference or on the right hand side of a dot in a type reference ([3.8.2](#3.8.2)). A name that denotes a namespace can be used one the left hand side of a dot in a type reference. - -When a name with multiple meanings is referenced, the context in which the reference occurs determines the meaning. For example: - -```TypeScript -var n: X; // X references type -var s: X.Y = X; // First X references namespace, second X references value -``` - -In the first line, X references the type X because it occurs in a type position. In the second line, the first X references the namespace X because it occurs before a dot in a type name, and the second X references the variable X because it occurs in an expression. - -Declarations introduce the following meanings for the name they declare: - -* A variable, parameter, function, generator, member variable, member function, member accessor, or enum member declaration introduces a value meaning. -* An interface, type alias, or type parameter declaration introduces a type meaning. -* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class type). -* An enum declaration introduces a value meaning (the enum instance) and a type meaning (the enum type). -* A namespace declaration introduces a namespace meaning (the type and namespace container) and, if the namespace is instantiated (section [10.1](#10.1)), a value meaning (the namespace instance). -* An import or export declaration introduces the meaning(s) of the imported or exported entity. - -Below are some examples of declarations that introduce multiple meanings for a name: - -```TypeScript -class C { // Value and type named C - x: string; -} - -namespace N { // Value and namespace named N - export var x: string; -} -``` - -Declaration spaces exist as follows: - -* The global namespace, each module, and each declared namespace has a declaration space for its contained entities (whether local or exported). -* Each module has a declaration space for its exported entities. All export declarations in the module contribute to this declaration space. -* Each declared namespace has a declaration space for its exported entities. All export declarations in the namespace contribute to this declaration space. A declared namespace’s declaration space is shared with other declared namespaces that have the same root container and the same qualified name starting from that root container. -* Each class declaration has a declaration space for instance members and type parameters, and a declaration space for static members. -* Each interface declaration has a declaration space for members and type parameters. An interface's declaration space is shared with other interfaces that have the same root container and the same qualified name starting from that root container. -* Each enum declaration has a declaration space for its enum members. An enum's declaration space is shared with other enums that have the same root container and the same qualified name starting from that root container. -* Each type alias declaration has a declaration space for its type parameters. -* Each function-like declaration (including function declarations, constructor declarations, member function declarations, member accessor declarations, function expressions, and arrow functions) has a declaration space for locals and type parameters. This declaration space includes parameter declarations, all local var and function declarations, and local let, const, class, interface, type alias, and enum declarations that occur immediately within the function body and are not further nested in blocks. -* Each statement block has a declaration space for local let, const, class, interface, type alias, and enum declarations that occur immediately within that block. -* Each object literal has a declaration space for its properties. -* Each object type literal has a declaration space for its members. - -Top-level declarations in a source file with no top-level import or export declarations belong to the ***global namespace***. Top-level declarations in a source file with one or more top-level import or export declarations belong to the ***module*** represented by that source file. - -The ***container*** of an entity is defined as follows: - -* The container of an entity declared in a namespace declaration is that namespace declaration. -* The container of an entity declared in a module is that module. -* The container of an entity declared in the global namespace is the global namespace. -* The container of a module is the global namespace. - -The ***root container*** of an entity is defined as follows: - -* The root container of a non-exported entity is the entity’s container. -* The root container of an exported entity is the root container of the entity's container. - -Intuitively, the root container of an entity is the outermost module or namespace body from within which the entity is reachable. - -Interfaces, enums, and namespaces are "open ended," meaning that interface, enum, and namespace declarations with the same qualified name relative to a common root are automatically merged. For further details, see sections [7.2](#7.2), [9.3](#9.3), and [10.5](#10.5). - -Instance and static members in a class are in separate declaration spaces. Thus the following is permitted: - -```TypeScript -class C { - x: number; // Instance member - static x: string; // Static member -} -``` - -## 2.4 Scopes - -The ***scope*** of a name is the region of program text within which it is possible to refer to the entity declared by that name without qualification of the name. The scope of a name depends on the context in which the name is declared. The contexts are listed below in order from outermost to innermost: - -* The scope of a name declared in the global namespace is the entire program text. -* The scope of a name declared in a module is the source file of that module. -* The scope of an exported name declared within a namespace declaration is the body of that namespace declaration and every namespace declaration with the same root and the same qualified name relative to that root. -* The scope of a non-exported name declared within a namespace declaration is the body of that namespace declaration. -* The scope of a type parameter name declared in a class or interface declaration is that entire declaration, including constraints, extends clause, implements clause, and declaration body, but not including static member declarations. -* The scope of a type parameter name declared in a type alias declaration is that entire type alias declaration. -* The scope of a member name declared in an enum declaration is the body of that declaration and every enum declaration with the same root and the same qualified name relative to that root. -* The scope of a type parameter name declared in a call or construct signature is that entire signature declaration, including constraints, parameter list, and return type. If the signature is part of a function implementation, the scope includes the function body. -* The scope of a parameter name declared in a call or construct signature is the remainder of the signature declaration. If the signature is part of a function-like declaration with a body (including a function declaration, constructor declaration, member function declaration, member accessor declaration, function expression, or arrow function), the scope includes the body of that function-like declaration. -* The scope of a local var or function name declared anywhere in the body of a function-like declaration is the body of that function-like declaration. -* The scope of a local let, const, class, interface, type alias, or enum declaration declared immediately within the body of a function-like declaration is the body of that function-like declaration. -* The scope of a local let, const, class, interface, type alias, or enum declaration declared immediately within a statement block is the body of that statement block. - -Scopes may overlap, for example through nesting of namespaces and functions. When the scopes of two names overlap, the name with the innermost declaration takes precedence and access to the outer name is either not possible or only possible by qualification. - -When an identifier is resolved as a *PrimaryExpression* (section [4.3](#4.3)), only names in scope with a value meaning are considered and other names are ignored. - -When an identifier is resolved as a *TypeName* (section [3.8.2](#3.8.2)), only names in scope with a type meaning are considered and other names are ignored. - -When an identifier is resolved as a *NamespaceName* (section [3.8.2](#3.8.2)), only names in scope with a namespace meaning are considered and other names are ignored. - -*TODO: [Include specific rules for alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*. - -Note that class and interface members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class or interface instance. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`. - -As the rules above imply, locally declared entities in a namespace are closer in scope than exported entities declared in other namespace declarations for the same namespace. For example: - -```TypeScript -var x = 1; -namespace M { - export var x = 2; - console.log(x); // 2 -} -namespace M { - console.log(x); // 2 -} -namespace M { - var x = 3; - console.log(x); // 3 -} -``` - -
- -#
3 Types - -TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development. TypeScript's *static* compile-time type system closely models the *dynamic* run-time type system of JavaScript, allowing programmers to accurately express the type relationships that are expected to exist when their programs run and have those assumptions pre-validated by the TypeScript compiler. TypeScript's type analysis occurs entirely at compile-time and adds no run-time overhead to program execution. - -All types in TypeScript are subtypes of a single top type called the Any type. The `any` keyword references this type. The Any type is the one type that can represent *any* JavaScript value with no constraints. All other types are categorized as ***primitive types***, ***object types***, ***union types***, ***intersection types***, or ***type parameters***. These types introduce various static constraints on their values. - -The primitive types are the Number, Boolean, String, Symbol, Void, Null, and Undefined types along with user defined enum types. The `number`, `boolean`, `string`, `symbol`, and `void` keywords reference the Number, Boolean, String, Symbol, and Void primitive types respectively. The Void type exists purely to indicate the absence of a value, such as in a function with no return value. It is not possible to explicitly reference the Null and Undefined types—only *values* of those types can be referenced, using the `null` and `undefined` literals. - -The object types are all class, interface, array, tuple, function, and constructor types. Class and interface types are introduced through class and interface declarations and are referenced by the name given to them in their declarations. Class and interface types may be ***generic types*** which have one or more type parameters. - -Union types represent values that have one of multiple types, and intersection types represent values that simultaneously have more than one type. - -Declarations of classes, properties, functions, variables and other language entities associate types with those entities. The mechanism by which a type is formed and associated with a language entity depends on the particular kind of entity. For example, a namespace declaration associates the namespace with an anonymous type containing a set of properties corresponding to the exported variables and functions in the namespace, and a function declaration associates the function with an anonymous type containing a call signature corresponding to the parameters and return type of the function. Types can be associated with variables through explicit ***type annotations***, such as - -```TypeScript -var x: number; -``` - -or through implicit ***type inference***, as in - -```TypeScript -var x = 1; -``` - -which infers the type of 'x' to be the Number primitive type because that is the type of the value used to initialize 'x'. - -## 3.1 The Any Type - -The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list. - -The `any` keyword references the Any type. In general, in places where a type is not explicitly provided and TypeScript cannot infer one, the Any type is assumed. - -The Any type is a supertype of all types, and is assignable to and from all types. - -Some examples: - -```TypeScript -var x: any; // Explicitly typed -var y; // Same as y: any -var z: { a; b; }; // Same as z: { a: any; b: any; } - -function f(x) { // Same as f(x: any): void - console.log(x); -} -``` - -## 3.2 Primitive Types - -The primitive types are the Number, Boolean, String, Symbol, Void, Null, and Undefined types and all user defined enum types. - -### 3.2.1 The Number Type - -The Number primitive type corresponds to the similarly named JavaScript primitive type and represents double-precision 64-bit format IEEE 754 floating point values. - -The `number` keyword references the Number primitive type and numeric literals may be used to write values of the Number primitive type. - -For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Number primitive type behaves as an object type with the same properties as the global interface type 'Number'. - -Some examples: - -```TypeScript -var x: number; // Explicitly typed -var y = 0; // Same as y: number = 0 -var z = 123.456; // Same as z: number = 123.456 -var s = z.toFixed(2); // Property of Number interface -``` - -### 3.2.2 The Boolean Type - -The Boolean primitive type corresponds to the similarly named JavaScript primitive type and represents logical values that are either true or false. - -The `boolean` keyword references the Boolean primitive type and the `true` and `false` literals reference the two Boolean truth values. - -For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Boolean primitive type behaves as an object type with the same properties as the global interface type 'Boolean'. - -Some examples: - -```TypeScript -var b: boolean; // Explicitly typed -var yes = true; // Same as yes: boolean = true -var no = false; // Same as no: boolean = false -``` - -### 3.2.3 The String Type - -The String primitive type corresponds to the similarly named JavaScript primitive type and represents sequences of characters stored as Unicode UTF-16 code units. - -The `string` keyword references the String primitive type and string literals may be used to write values of the String primitive type. - -For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the String primitive type behaves as an object type with the same properties as the global interface type 'String'. - -Some examples: - -```TypeScript -var s: string; // Explicitly typed -var empty = ""; // Same as empty: string = "" -var abc = 'abc'; // Same as abc: string = "abc" -var c = abc.charAt(2); // Property of String interface -``` - -### 3.2.4 The Symbol Type - -The Symbol primitive type corresponds to the similarly named JavaScript primitive type and represents unique tokens that may be used as keys for object properties. - -The `symbol` keyword references the Symbol primitive type. Symbol values are obtained using the global object 'Symbol' which has a number of methods and properties and can be invoked as a function. In particular, the global object 'Symbol' defines a number of well-known symbols ([2.2.3](#2.2.3)) that can be used in a manner similar to identifiers. Note that the 'Symbol' object is available only in ECMAScript 2015 environments. - -For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Symbol primitive type behaves as an object type with the same properties as the global interface type 'Symbol'. - -Some examples: - -```TypeScript -var secretKey = Symbol(); -var obj = {}; -obj[secretKey] = "secret message"; // Use symbol as property key -obj[Symbol.toStringTag] = "test"; // Use of well-known symbol -``` - -### 3.2.5 The Void Type - -The Void type, referenced by the `void` keyword, represents the absence of a value and is used as the return type of functions with no return value. - -The only possible values for the Void type are `null` and `undefined`. The Void type is a subtype of the Any type and a supertype of the Null and Undefined types, but otherwise Void is unrelated to all other types. - -*NOTE: We might consider disallowing declaring variables of type Void as they serve no useful purpose. However, because Void is permitted as a type argument to a generic type or function it is not feasible to disallow Void properties or parameters*. - -### 3.2.6 The Null Type - -The Null type corresponds to the similarly named JavaScript primitive type and is the type of the `null` literal. - -The `null` literal references the one and only value of the Null type. It is not possible to directly reference the Null type itself. - -The Null type is a subtype of all types, except the Undefined type. This means that `null` is considered a valid value for all primitive types, object types, union types, intersection types, and type parameters, including even the Number and Boolean primitive types. - -Some examples: - -```TypeScript -var n: number = null; // Primitives can be null -var x = null; // Same as x: any = null -var e: Null; // Error, can't reference Null type -``` - -### 3.2.7 The Undefined Type - -The Undefined type corresponds to the similarly named JavaScript primitive type and is the type of the `undefined` literal. - -The `undefined` literal denotes the value given to all uninitialized variables and is the one and only value of the Undefined type. It is not possible to directly reference the Undefined type itself. - -The undefined type is a subtype of all types. This means that `undefined` is considered a valid value for all primitive types, object types, union types, intersection types, and type parameters. - -Some examples: - -```TypeScript -var n: number; // Same as n: number = undefined -var x = undefined; // Same as x: any = undefined -var e: Undefined; // Error, can't reference Undefined type -``` - -### 3.2.8 Enum Types - -Enum types are distinct user defined subtypes of the Number primitive type. Enum types are declared using enum declarations (section [9.1](#9.1)) and referenced using type references (section [3.8.2](#3.8.2)). - -Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other. - -### 3.2.9 String Literal Types - -Specialized signatures (section [3.9.2.4](#3.9.2.4)) permit string literals to be used as types in parameter type annotations. String literal types are permitted only in that context and nowhere else. - -All string literal types are subtypes of the String primitive type. - -*TODO: Update to reflect [expanded support for string literal types](https://github.com/Microsoft/TypeScript/pull/5185)*. - -## 3.3 Object Types - -Object types are composed from properties, call signatures, construct signatures, and index signatures, collectively called members. - -Class and interface type references, array types, tuple types, function types, and constructor types are all classified as object types. Multiple constructs in the TypeScript language create object types, including: - -* Object type literals (section [3.8.3](#3.8.3)). -* Array type literals (section [3.8.4](#3.8.4)). -* Tuple type literals (section [3.8.5](#3.8.5)). -* Function type literals (section [3.8.8](#3.8.8)). -* Constructor type literals (section [3.8.9](#3.8.9)). -* Object literals (section [4.5](#4.5)). -* Array literals (section [4.6](#4.6)). -* Function expressions (section [4.10](#4.10)) and function declarations ([6.1](#6.1)). -* Constructor function types created by class declarations (section [8.2.5](#8.2.5)). -* Namespace instance types created by namespace declarations (section [10.3](#10.3)). - -### 3.3.1 Named Type References - -Type references (section [3.8.2](#3.8.2)) to class and interface types are classified as object types. Type references to generic class and interface types include type arguments that are substituted for the type parameters of the class or interface to produce an actual object type. - -### 3.3.2 Array Types - -***Array types*** represent JavaScript arrays with a common element type. Array types are named type references created from the generic interface type 'Array' in the global namespace with the array element type as a type argument. Array type literals (section [3.8.4](#3.8.4)) provide a shorthand notation for creating such references. - -The declaration of the 'Array' interface includes a property 'length' and a numeric index signature for the element type, along with other members: - -```TypeScript -interface Array { - length: number; - [x: number]: T; - // Other members -} -``` - -Array literals (section [4.6](#4.6)) may be used to create values of array types. For example - -```TypeScript -var a: string[] = ["hello", "world"]; -``` - -A type is said to be an ***array-like type*** if it is assignable (section [3.11.4](#3.11.4)) to the type `any[]`. - -### 3.3.3 Tuple Types - -***Tuple types*** represent JavaScript arrays with individually tracked element types. Tuple types are written using tuple type literals (section [3.8.5](#3.8.5)). A tuple type combines a set of numerically named properties with the members of an array type. Specifically, a tuple type - -```TypeScript -[ T0, T1, ..., Tn ] -``` - -combines the set of properties - -```TypeScript -{ - 0: T0; - 1: T1; - ... - n: Tn; -} -``` - -with the members of an array type whose element type is the union type (section [3.4](#3.4)) of the tuple element types. - -Array literals (section [4.6](#4.6)) may be used to create values of tuple types. For example: - -```TypeScript -var t: [number, string] = [3, "three"]; -var n = t[0]; // Type of n is number -var s = t[1]; // Type of s is string -var i: number; -var x = t[i]; // Type of x is number | string -``` - -Named tuple types can be created by declaring interfaces that derive from Array<T> and introduce numerically named properties. For example: - -```TypeScript -interface KeyValuePair extends Array { 0: K; 1: V; } - -var x: KeyValuePair = [10, "ten"]; -``` - -A type is said to be a ***tuple-like type*** if it has a property with the numeric name '0'. - -### 3.3.4 Function Types - -An object type containing one or more call signatures is said to be a ***function type***. Function types may be written using function type literals (section [3.8.8](#3.8.8)) or by including call signatures in object type literals. - -### 3.3.5 Constructor Types - -An object type containing one or more construct signatures is said to be a ***constructor type***. Constructor types may be written using constructor type literals (section [3.8.9](#3.8.9)) or by including construct signatures in object type literals. - -### 3.3.6 Members - -Every object type is composed from zero or more of the following kinds of members: - -* ***Properties***, which define the names and types of the properties of objects of the given type. Property names are unique within their type. -* ***Call signatures***, which define the possible parameter lists and return types associated with applying call operations to objects of the given type. -* ***Construct signatures***, which define the possible parameter lists and return types associated with applying the `new` operator to objects of the given type. -* ***Index signatures***, which define type constraints for properties in the given type. An object type can have at most one string index signature and one numeric index signature. - -Properties are either ***public***, ***private***, or ***protected*** and are either ***required*** or ***optional***: - -* Properties in a class declaration may be designated public, private, or protected, while properties declared in other contexts are always considered public. Private members are only accessible within their declaring class, as described in section [8.2.2](#8.2.2), and private properties match only themselves in subtype and assignment compatibility checks, as described in section [3.11](#3.11). Protected members are only accessible within their declaring class and classes derived from it, as described in section [8.2.2](#8.2.2), and protected properties match only themselves and overrides in subtype and assignment compatibility checks, as described in section [3.11](#3.11). -* Properties in an object type literal or interface declaration may be designated required or optional, while properties declared in other contexts are always considered required. Properties that are optional in the target type of an assignment may be omitted from source objects, as described in section [3.11.4](#3.11.4). - -Call and construct signatures may be ***specialized*** (section [3.9.2.4](#3.9.2.4)) by including parameters with string literal types. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. - -## 3.4 Union Types - -***Union types*** represent values that may have one of several distinct representations. A value of a union type *A* | *B* is a value that is *either* of type *A* or type *B*. Union types are written using union type literals (section [3.8.6](#3.8.6)). - -A union type encompasses an ordered set of constituent types. While it is generally true that *A* | *B* is equivalent to *B* | *A*, the order of the constituent types may matter when determining the call and construct signatures of the union type. - -Union types have the following subtype relationships: - -* A union type *U* is a subtype of a type *T* if each type in *U* is a subtype of *T*. -* A type *T* is a subtype of a union type *U* if *T* is a subtype of any type in *U*. - -Similarly, union types have the following assignability relationships: - -* A union type *U* is assignable to a type *T* if each type in *U* is assignable to *T*. -* A type *T* is assignable to a union type *U* if *T* is assignable to any type in *U*. - -The || and conditional operators (section [4.19.7](#4.19.7) and [4.20](#4.20)) may produce values of union types, and array literals (section [4.6](#4.6)) may produce array values that have union types as their element types. - -Type guards (section [4.24](#4.24)) may be used to narrow a union type to a more specific type. In particular, type guards are useful for narrowing union type values to a non-union type values. - -In the example - -```TypeScript -var x: string | number; -var test: boolean; -x = "hello"; // Ok -x = 42; // Ok -x = test; // Error, boolean not assignable -x = test ? 5 : "five"; // Ok -x = test ? 0 : false; // Error, number | boolean not assignable -``` - -it is possible to assign 'x' a value of type `string`, `number`, or the union type `string | number`, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either `string` or `number`: - -```TypeScript -var n = typeof x === "string" ? x.length : x; // Type of n is number -``` - -For purposes of property access and function calls, the apparent members (section [3.11.1](#3.11.1)) of a union type are those that are present in every one of its constituent types, with types that are unions of the respective apparent members in the constituent types. The following example illustrates the merging of member types that occurs when union types are created from object types. - -```TypeScript -interface A { - a: string; - b: number; -} - -interface B { - a: number; - b: number; - c: number; -} - -var x: A | B; -var a = x.a; // a has type string | number -var b = x.b; // b has type number -var c = x.c; // Error, no property c in union type -``` - -Note that 'x.a' has a union type because the type of 'a' is different in 'A' and 'B', whereas 'x.b' simply has type number because that is the type of 'b' in both 'A' and 'B'. Also note that there is no property 'x.c' because only 'B' has a property 'c'. - -When used as a contextual type (section [4.23](#4.23)), a union type has those members that are present in any of its constituent types, with types that are unions of the respective members in the constituent types. Specifically, a union type used as a contextual type has the apparent members defined in section [3.11.1](#3.11.1), except that a particular member need only be present in one or more constituent types instead of all constituent types. - -## 3.5 Intersection Types - -***Intersection types*** represent values that simultaneously have multiple types. A value of an intersection type *A* & *B* is a value that is *both* of type *A* and type *B*. Intersection types are written using intersection type literals (section [3.8.7](#3.8.7)). - -An intersection type encompasses an ordered set of constituent types. While it is generally true that *A* & *B* is equivalent to *B* & *A*, the order of the constituent types may matter when determining the call and construct signatures of the intersection type. - -Intersection types have the following subtype relationships: - -* An intersection type *I* is a subtype of a type *T* if any type in *I* is a subtype of *T*. -* A type *T* is a subtype of an intersection type *I* if *T* is a subtype of each type in *I*. - -Similarly, intersection types have the following assignability relationships: - -* An intersection type *I* is assignable to a type *T* if any type in *I* is assignable to *T*. -* A type *T* is assignable to an intersection type *I* if *T* is assignable to each type in *I*. - -For purposes of property access and function calls, the apparent members (section [3.11.1](#3.11.1)) of an intersection type are those that are present in one or more of its constituent types, with types that are intersections of the respective apparent members in the constituent types. The following examples illustrate the merging of member types that occurs when intersection types are created from object types. - -```TypeScript -interface A { a: number } -interface B { b: number } - -var ab: A & B = { a: 1, b: 1 }; -var a: A = ab; // A & B assignable to A -var b: B = ab; // A & B assignable to B - -interface X { p: A } -interface Y { p: B } - -var xy: X & Y = { p: ab }; // X & Y has property p of type A & B - -type F1 = (a: string, b: string) => void; -type F2 = (a: number, b: number) => void; - -var f: F1 & F2 = (a: string | number, b: string | number) => { }; -f("hello", "world"); // Ok -f(1, 2); // Ok -f(1, "test"); // Error -``` - -The union and intersection type operators can be applied to type parameters. This capability can for example be used to model functions that merge objects: - -```TypeScript -function extend(first: T, second: U): T & U { - // Extend first with properties of second -} - -var x = extend({ a: "hello" }, { b: 42 }); -var s = x.a; -var n = x.b; -``` - -It is possible to create intersection types for which no values other than null or undefined are possible. For example, intersections of primitive types such as `string & number` fall into this category. - -## 3.6 Type Parameters - -A type parameter represents an actual type that the parameter is bound to in a generic type reference or a generic function call. Type parameters have constraints that establish upper bounds for their actual type arguments. - -Since a type parameter represents a multitude of different type arguments, type parameters have certain restrictions compared to other types. In particular, a type parameter cannot be used as a base class or interface. - -### 3.6.1 Type Parameter Lists - -Class, interface, type alias, and function declarations may optionally include lists of type parameters enclosed in < and > brackets. Type parameters are also permitted in call signatures of object, function, and constructor type literals. - -  *TypeParameters:* -   `<` *TypeParameterList* `>` - -  *TypeParameterList:* -   *TypeParameter* -   *TypeParameterList* `,` *TypeParameter* - -  *TypeParameter:* -   *BindingIdentifier* *Constraintopt* - -  *Constraint:* -   `extends` *Type* - -Type parameter names must be unique. A compile-time error occurs if two or more type parameters in the same *TypeParameterList* have the same name. - -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. - -A type parameter may have an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Type parameters may be referenced in type parameter constraints within the same type parameter list, including even constraint declarations that occur to the left of the type parameter. - -The ***base constraint*** of a type parameter *T* is defined as follows: - -* If *T* has no declared constraint, *T*'s base constraint is the empty object type `{}`. -* If *T*'s declared constraint is a type parameter, *T*'s base constraint is that of the type parameter. -* Otherwise, *T*'s base constraint is *T*'s declared constraint. - -In the example - -```TypeScript -interface G { } -``` - -the base constraint of 'T' is the empty object type and the base constraint of 'U' and 'V' is 'Function'. - -For purposes of determining type relationships (section [3.11](#3.11)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)), type parameters appear to have the members of their base constraint, but no other members. - -It is an error for a type parameter to directly or indirectly be a constraint for itself. For example, both of the following declarations are invalid: - -```TypeScript -interface A { } - -interface B { } -``` - -### 3.6.2 Type Argument Lists - -A type reference (section [3.8.2](#3.8.2)) to a generic type must include a list of type arguments enclosed in angle brackets and separated by commas. Similarly, a call (section [4.15](#4.15)) to a generic function may explicitly include a type argument list instead of relying on type inference. - -  *TypeArguments:* -   `<` *TypeArgumentList* `>` - -  *TypeArgumentList:* -   *TypeArgument* -   *TypeArgumentList* `,` *TypeArgument* - -  *TypeArgument:* -   *Type* - -Type arguments correspond one-to-one with type parameters of the generic type or function being referenced. A type argument list is required to specify exactly one type argument for each corresponding type parameter, and each type argument for a constrained type parameter is required to ***satisfy*** the constraint of that type parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section [3.11.4](#3.11.4)) the constraint type once type arguments are substituted for type parameters. - -Given the declaration - -```TypeScript -interface G { } -``` - -a type reference of the form 'G<A, B>' places no requirements on 'A' but requires 'B' to be assignable to 'Function'. - -The process of substituting type arguments for type parameters in a generic type or generic signature is known as ***instantiating*** the generic type or signature. Instantiation of a generic type or signature can fail if the supplied type arguments do not satisfy the constraints of their corresponding type parameters. - -### 3.6.3 This-types - -Every class and interface has a ***this-type*** that represents the actual type of instances of the class or interface within the declaration of the class or interface. The this-type is referenced using the keyword `this` in a type position. Within instance methods and constructors of a class, the type of the expression `this` (section [4.2](#4.2)) is the this-type of the class. - -Classes and interfaces support inheritance and therefore the instance represented by `this` in a method isn't necessarily an instance of the containing class—it may in fact be an instance of a derived class or interface. To model this relationship, the this-type of a class or interface is classified as a type parameter. Unlike other type parameters, it is not possible to explicitly pass a type argument for a this-type. Instead, in a type reference to a class or interface type, the type reference *itself* is implicitly passed as a type argument for the this-type. For example: - -```TypeScript -class A { - foo() { - return this; - } -} - -class B extends A { - bar() { - return this; - } -} - -let b: B; -let x = b.foo().bar(); // Fluent pattern works, type of x is B -``` - -In the declaration of `b` above, the type reference `B` is itself passed as a type argument for B's this-type. Thus, the referenced type is an instantiation of class `B` where all occurrences of the type `this` are replaced with `B`, and for that reason the `foo` method of `B` actually returns `B` (as opposed to `A`). - -The this-type of a given class or interface type *C* implicitly has a constraint consisting of a type reference to *C* with *C*'s own type parameters passed as type arguments and with that type reference passed as the type argument for the this-type. - -## 3.7 Named Types - -Classes, interfaces, enums, and type aliases are ***named types*** that are introduced through class declarations (section [8.1](#8.1)), interface declarations (section [7.1](#7.1)), enum declarations ([9.1](#9.1)), and type alias declarations (section [3.10](#3.10)). Classes, interfaces, and type aliases may have type parameters and are then called ***generic types***. Conversely, named types without type parameters are called ***non-generic types***. - -Interface declarations only introduce named types, whereas class declarations introduce named types *and* constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can't declare optional members and interfaces can't declare private or protected members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations. - -Named types are referenced through ***type references*** (section [3.8.2](#3.8.2)) that specify a type name and, if applicable, the type arguments to be substituted for the type parameters of the named type. - -Named types are technically not types—only *references* to named types are. This distinction is particularly evident with generic types: Generic types are "templates" from which multiple *actual* types can be created by writing type references that supply type arguments to substitute in place of the generic type's type parameters. This substitution process is known as ***instantiating*** a generic type. Only once a generic type is instantiated does it denote an actual type. - -TypeScript has a structural type system, and therefore an instantiation of a generic type is indistinguishable from an equivalent manually written expansion. For example, given the declaration - -```TypeScript -interface Pair { first: T1; second: T2; } -``` - -the type reference - -```TypeScript -Pair -``` - -is indistinguishable from the type - -```TypeScript -{ first: string; second: Entity; } -``` - -## 3.8 Specifying Types - -Types are specified either by referencing their keyword or name, or by writing object type literals, array type literals, tuple type literals, function type literals, constructor type literals, or type queries. - -  *Type:* -   *UnionOrIntersectionOrPrimaryType* -   *FunctionType* -   *ConstructorType* - -  *UnionOrIntersectionOrPrimaryType:* -   *UnionType* -   *IntersectionOrPrimaryType* - -  *IntersectionOrPrimaryType:* -   *IntersectionType* -   *PrimaryType* - -  *PrimaryType:* -   *ParenthesizedType* -   *PredefinedType* -   *TypeReference* -   *ObjectType* -   *ArrayType* -   *TupleType* -   *TypeQuery* -   *ThisType* - -  *ParenthesizedType:* -   `(` *Type* `)` - -Parentheses are required around union, intersection, function, or constructor types when they are used as array element types; around union, function, or constructor types in intersection types; and around function or constructor types in union types. For example: - -```TypeScript -(string | number)[] -((x: string) => string) | ((x: number) => number) -(A | B) & (C | D) -``` - -The different forms of type notations are described in the following sections. - -### 3.8.1 Predefined Types - -The `any`, `number`, `boolean`, `string`, `symbol` and `void` keywords reference the Any type and the Number, Boolean, String, Symbol, and Void primitive types respectively. - -  *PredefinedType:* -   `any` -   `number` -   `boolean` -   `string` -   `symbol` -   `void` - -The predefined type keywords are reserved and cannot be used as names of user defined types. - -### 3.8.2 Type References - -A type reference references a named type or type parameter through its name and, in the case of a generic type, supplies a type argument list. - -  *TypeReference:* -   *TypeName* *[no LineTerminator here]* *TypeArgumentsopt* - -  *TypeName:* -   *IdentifierReference* -   *NamespaceName* `.` *IdentifierReference* - -  *NamespaceName:* -   *IdentifierReference* -   *NamespaceName* `.` *IdentifierReference* - -A *TypeReference* consists of a *TypeName* that a references a named type or type parameter. A reference to a generic type must be followed by a list of *TypeArguments* (section [3.6.2](#3.6.2)). - -A *TypeName* is either a single identifier or a sequence of identifiers separated by dots. In a type name, all identifiers but the last one refer to namespaces and the last identifier refers to a named type. - -Resolution of a *TypeName* consisting of a single identifier is described in section [2.4](#2.4). - -Resolution of a *TypeName* of the form *N.X*, where *N* is a *NamespaceName* and *X* is an *IdentifierReference*, proceeds by first resolving the namespace name *N*. If the resolution of *N* is successful and the export member set (sections [10.4](#10.4) and [11.3.4.4](#11.3.4.4)) of the resulting namespace contains a named type *X*, then *N.X* refers to that member. Otherwise, *N.X* is undefined. - -Resolution of a *NamespaceName* consisting of a single identifier is described in section [2.4](#2.4). Identifiers declared in namespace declarations (section [10.1](#10.1)) or import declarations (sections [10.3](#10.3), [11.3.2](#11.3.2), and [11.3.3](#11.3.3)) may be classified as namespaces. - -Resolution of a *NamespaceName* of the form *N.X*, where *N* is a *NamespaceName* and *X* is an *IdentifierReference*, proceeds by first resolving the namespace name *N*. If the resolution of *N* is successful and the export member set (sections [10.4](#10.4) and [11.3.4.4](#11.3.4.4)) of the resulting namespace contains an exported namespace member *X*, then *N.X* refers to that member. Otherwise, *N.X* is undefined. - -A type reference to a generic type is required to specify exactly one type argument for each type parameter of the referenced generic type, and each type argument must be assignable to (section [3.11.4](#3.11.4)) the constraint of the corresponding type parameter or otherwise an error occurs. An example: - -```TypeScript -interface A { a: string; } - -interface B extends A { b: string; } - -interface C extends B { c: string; } - -interface G { - x: T; - y: U; -} - -var v1: G; // Ok -var v2: G<{ a: string }, C>; // Ok, equivalent to G -var v3: G; // Error, A not valid argument for U -var v4: G, C>; // Ok -var v5: G; // Ok -var v6: G; // Error, wrong number of arguments -var v7: G; // Error, no arguments -``` - -A type argument is simply a *Type* and may itself be a type reference to a generic type, as demonstrated by 'v4' in the example above. - -As described in section [3.7](#3.7), a type reference to a generic type *G* designates a type wherein all occurrences of *G*'s type parameters have been replaced with the actual type arguments supplied in the type reference. For example, the declaration of 'v1' above is equivalent to: - -```TypeScript -var v1: { - x: { a: string; } - y: { a: string; b: string; c: string }; -}; -``` - -### 3.8.3 Object Type Literals - -An object type literal defines an object type by specifying the set of members that are statically considered to be present in instances of the type. Object type literals can be given names using interface declarations but are otherwise anonymous. - -  *ObjectType:* -   `{` *TypeBodyopt* `}` - -  *TypeBody:* -   *TypeMemberList* `;`*opt* -   *TypeMemberList* `,`*opt* - -  *TypeMemberList:* -   *TypeMember* -   *TypeMemberList* `;` *TypeMember* -   *TypeMemberList* `,` *TypeMember* - -  *TypeMember:* -   *PropertySignature* -   *CallSignature* -   *ConstructSignature* -   *IndexSignature* -   *MethodSignature* - -The members of an object type literal are specified as a combination of property, call, construct, index, and method signatures. Object type members are described in section [3.9](#3.9). - -### 3.8.4 Array Type Literals - -An array type literal is written as an element type followed by an open and close square bracket. - -  *ArrayType:* -   *PrimaryType* *[no LineTerminator here]* `[` `]` - -An array type literal references an array type (section [3.3.2](#3.3.2)) with the given element type. An array type literal is simply shorthand notation for a reference to the generic interface type 'Array' in the global namespace with the element type as a type argument. - -When union, intersection, function, or constructor types are used as array element types they must be enclosed in parentheses. For example: - -```TypeScript -(string | number)[] -(() => string))[] -``` - -Alternatively, array types can be written using the 'Array<T>' notation. For example, the types above are equivalent to - -```TypeScript -Array -Array<() => string> -``` - -### 3.8.5 Tuple Type Literals - -A tuple type literal is written as a sequence of element types, separated by commas and enclosed in square brackets. - -  *TupleType:* -   `[` *TupleElementTypes* `]` - -  *TupleElementTypes:* -   *TupleElementType* -   *TupleElementTypes* `,` *TupleElementType* - -  *TupleElementType:* -   *Type* - -A tuple type literal references a tuple type (section [3.3.3](#3.3.3)). - -### 3.8.6 Union Type Literals - -A union type literal is written as a sequence of types separated by vertical bars. - -  *UnionType:* -   *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType* - -A union type literal references a union type (section [3.4](#3.4)). - -### 3.8.7 Intersection Type Literals - -An intersection type literal is written as a sequence of types separated by ampersands. - -  *IntersectionType:* -   *IntersectionOrPrimaryType* `&` *PrimaryType* - -An intersection type literal references an intersection type (section [3.5](#3.5)). - -### 3.8.8 Function Type Literals - -A function type literal specifies the type parameters, regular parameters, and return type of a call signature. - -  *FunctionType:* -   *TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type* - -A function type literal is shorthand for an object type containing a single call signature. Specifically, a function type literal of the form - -```TypeScript -< T1, T2, ... > ( p1, p2, ... ) => R -``` - -is exactly equivalent to the object type literal - -```TypeScript -{ < T1, T2, ... > ( p1, p2, ... ) : R } -``` - -Note that function types with multiple call or construct signatures cannot be written as function type literals but must instead be written as object type literals. - -### 3.8.9 Constructor Type Literals - -A constructor type literal specifies the type parameters, regular parameters, and return type of a construct signature. - -  *ConstructorType:* -   `new` *TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type* - -A constructor type literal is shorthand for an object type containing a single construct signature. Specifically, a constructor type literal of the form - -```TypeScript -new < T1, T2, ... > ( p1, p2, ... ) => R -``` - -is exactly equivalent to the object type literal - -```TypeScript -{ new < T1, T2, ... > ( p1, p2, ... ) : R } -``` - -Note that constructor types with multiple construct signatures cannot be written as constructor type literals but must instead be written as object type literals. - -### 3.8.10 Type Queries - -A type query obtains the type of an expression. - -  *TypeQuery:* -   `typeof` *TypeQueryExpression* - -  *TypeQueryExpression:* -   *IdentifierReference* -   *TypeQueryExpression* `.` *IdentifierName* - -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. The expression is processed as an identifier expression (section [4.3](#4.3)) or property access expression (section [4.13](#4.13)), the widened type (section [3.12](#3.12)) of which becomes the result. Similar to other static typing constructs, type queries are erased from the generated JavaScript code and add no run-time overhead. - -Type queries are useful for capturing anonymous types that are generated by various constructs such as object literals, function declarations, and namespace declarations. For example: - -```TypeScript -var a = { x: 10, y: 20 }; -var b: typeof a; -``` - -Above, 'b' is given the same type as 'a', namely `{ x: number; y: number; }`. - -If a declaration includes a type annotation that references the entity being declared through a circular path of type queries or type references containing type queries, the resulting type is the Any type. For example, all of the following variables are given the type Any: - -```TypeScript -var c: typeof c; -var d: typeof e; -var e: typeof d; -var f: Array; -``` - -However, if a circular path of type queries includes at least one *ObjectType*, *FunctionType* or *ConstructorType*, the construct denotes a recursive type: - -```TypeScript -var g: { x: typeof g; }; -var h: () => typeof h; -``` - -Here, 'g' and 'g.x' have the same recursive type, and likewise 'h' and 'h()' have the same recursive type. - -### 3.8.11 This-Type References - -The `this` keyword is used to reference the this-type (section [3.6.3](#3.6.3)) of a class or interface. - -  *ThisType:* -   `this` - -The meaning of a *ThisType* depends on the closest enclosing *FunctionDeclaration*, *FunctionExpression*, *PropertyDefinition*, *ClassElement*, or *TypeMember*, known as the root declaration of the *ThisType*, as follows: - -* When the root declaration is an instance member or constructor of a class, the *ThisType* references the this-type of that class. -* When the root declaration is a member of an interface type, the *ThisType* references the this-type of that interface. -* Otherwise, the *ThisType* is an error. - -Note that in order to avoid ambiguities it is not possible to reference the this-type of a class or interface in a nested object type literal. In the example - -```TypeScript -interface ListItem { - getHead(): this; - getTail(): this; - getHeadAndTail(): { head: this, tail: this }; // Error -} -``` - -the `this` references on the last line are in error because their root declarations are not members of a class or interface. The recommended way to reference the this-type of an outer class or interface in an object type literal is to declare an intermediate generic type and pass `this` as a type argument. For example: - -```TypeScript -type HeadAndTail = { head: T, tail: T }; - -interface ListItem { - getHead(): this; - getTail(): this; - getHeadAndTail(): HeadAndTail; -} -``` - -## 3.9 Specifying Members - -The members of an object type literal (section [3.8.3](#3.8.3)) are specified as a combination of property, call, construct, index, and method signatures. - -### 3.9.1 Property Signatures - -A property signature declares the name and type of a property member. - -  *PropertySignature:* -   *PropertyName* `?`*opt* *TypeAnnotationopt* - -  *TypeAnnotation:* -   `:` *Type* - -The *PropertyName* ([2.2.2](#2.2.2)) of a property signature must be unique within its containing type, and must denote a well-known symbol if it is a computed property name ([2.2.3](#2.2.3)). If the property name is followed by a question mark, the property is optional. Otherwise, the property is required. - -If a property signature omits a *TypeAnnotation*, the Any type is assumed. - -### 3.9.2 Call Signatures - -A call signature defines the type parameters, parameter list, and return type associated with applying a call operation (section [4.15](#4.15)) to an instance of the containing type. A type may ***overload*** call operations by defining multiple different call signatures. - -  *CallSignature:* -   *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt* - -A call signature that includes *TypeParameters* (section [3.6.1](#3.6.1)) is called a ***generic call signature***. Conversely, a call signature with no *TypeParameters* is called a non-generic call signature. - -As well as being members of object type literals, call signatures occur in method signatures (section [3.9.5](#3.9.5)), function expressions (section [4.10](#4.10)), and function declarations (section [6.1](#6.1)). - -An object type containing call signatures is said to be a ***function type***. - -#### 3.9.2.1 Type Parameters - -Type parameters (section [3.6.1](#3.6.1)) in call signatures provide a mechanism for expressing the relationships of parameter and return types in call operations. For example, a signature might introduce a type parameter and use it as both a parameter type and a return type, in effect describing a function that returns a value of the same type as its argument. - -Type parameters may be referenced in parameter types and return type annotations, but not in type parameter constraints, of the call signature in which they are introduced. - -Type arguments (section [3.6.2](#3.6.2)) for call signature type parameters may be explicitly specified in a call operation or may, when possible, be inferred (section [4.15.2](#4.15.2)) from the types of the regular arguments in the call. An ***instantiation*** of a generic call signature for a particular set of type arguments is the call signature formed by replacing each type parameter with its corresponding type argument. - -Some examples of call signatures with type parameters follow below. - -A function taking an argument of any type, returning a value of that same type: - -```TypeScript -(x: T): T -``` - -A function taking two values of the same type, returning an array of that type: - -```TypeScript -(x: T, y: T): T[] -``` - -A function taking two arguments of different types, returning an object with properties 'x' and 'y' of those types: - -```TypeScript -(x: T, y: U): { x: T; y: U; } -``` - -A function taking an array of one type and a function argument, returning an array of another type, where the function argument takes a value of the first array element type and returns a value of the second array element type: - -```TypeScript -(a: T[], f: (x: T) => U): U[] -``` - -#### 3.9.2.2 Parameter List - -A signature's parameter list consists of zero or more required parameters, followed by zero or more optional parameters, finally followed by an optional rest parameter. - -  *ParameterList:* -   *RequiredParameterList* -   *OptionalParameterList* -   *RestParameter* -   *RequiredParameterList* `,` *OptionalParameterList* -   *RequiredParameterList* `,` *RestParameter* -   *OptionalParameterList* `,` *RestParameter* -   *RequiredParameterList* `,` *OptionalParameterList* `,` *RestParameter* - -  *RequiredParameterList:* -   *RequiredParameter* -   *RequiredParameterList* `,` *RequiredParameter* - -  *RequiredParameter:* -   *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* -   *BindingIdentifier* `:` *StringLiteral* - -  *AccessibilityModifier:* -   `public` -   `private` -   `protected` - -  *BindingIdentifierOrPattern:* -   *BindingIdentifier* -   *BindingPattern* - -  *OptionalParameterList:* -   *OptionalParameter* -   *OptionalParameterList* `,` *OptionalParameter* - -  *OptionalParameter:* -   *AccessibilityModifieropt* *BindingIdentifierOrPattern* `?` *TypeAnnotationopt* -   *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* *Initializer* -   *BindingIdentifier* `?` `:` *StringLiteral* - -  *RestParameter:* -   `...` *BindingIdentifier* *TypeAnnotationopt* - -A parameter declaration may specify either an identifier or a binding pattern ([5.2.2](#5.2.2)). The identifiers specified in parameter declarations and binding patterns in a parameter list must be unique within that parameter list. - -The type of a parameter in a signature is determined as follows: - -* If the declaration includes a type annotation, the parameter is of that type. -* Otherwise, if the declaration includes an initializer expression (which is permitted only when the parameter list occurs in conjunction with a function body), the parameter type is the widened form (section [3.12](#3.12)) of the type of the initializer expression. -* Otherwise, if the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section [5.2.3](#5.2.3)). -* Otherwise, if the parameter is a rest parameter, the parameter type is `any[]`. -* Otherwise, the parameter type is `any`. - -A parameter is permitted to include a `public`, `private`, or `protected` modifier only if it occurs in the parameter list of a *ConstructorImplementation* (section [8.3.1](#8.3.1)) and only if it doesn't specify a *BindingPattern*. - -A type annotation for a rest parameter must denote an array type. - -When a parameter type annotation specifies a string literal type, the containing signature is a specialized signature (section [3.9.2.4](#3.9.2.4)). Specialized signatures are not permitted in conjunction with a function body, i.e. the *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, and *ConstructorImplementation* grammar productions do not permit parameters with string literal types. - -A parameter can be marked optional by following its name or binding pattern with a question mark (`?`) or by including an initializer. Initializers (including binding property or element initializers) are permitted only when the parameter list occurs in conjunction with a function body, i.e. only in a *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, or *ConstructorImplementation* grammar production. - -*TODO: Update to reflect [binding parameter cannot be optional in implementation signature](https://github.com/Microsoft/TypeScript/issues/2797)*. - -*TODO: Update to reflect [required parameters support initializers](https://github.com/Microsoft/TypeScript/pull/4022)*. - -#### 3.9.2.3 Return Type - -If present, a call signature's return type annotation specifies the type of the value computed and returned by a call operation. A `void` return type annotation is used to indicate that a function has no return value. - -When a call signature with no return type annotation occurs in a context without a function body, the return type is assumed to be the Any type. - -When a call signature with no return type annotation occurs in a context that has a function body (specifically, a function implementation, a member function implementation, or a member accessor declaration), the return type is inferred from the function body as described in section [6.3](#6.3). - -#### 3.9.2.4 Specialized Signatures - -When a parameter type annotation specifies a string literal type (section [3.2.9](#3.2.9)), the containing signature is considered a specialized signature. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. For example, the declaration - -```TypeScript -interface Document { - createElement(tagName: "div"): HTMLDivElement; - createElement(tagName: "span"): HTMLSpanElement; - createElement(tagName: "canvas"): HTMLCanvasElement; - createElement(tagName: string): HTMLElement; -} -``` - -states that calls to 'createElement' with the string literals "div", "span", and "canvas" return values of type 'HTMLDivElement', 'HTMLSpanElement', and 'HTMLCanvasElement' respectively, and that calls with all other string expressions return values of type 'HTMLElement'. - -When writing overloaded declarations such as the one above it is important to list the non-specialized signature last. This is because overload resolution (section [4.15.1](#4.15.1)) processes the candidates in declaration order and picks the first one that matches. - -Every specialized call or construct signature in an object type must be assignable to at least one non-specialized call or construct signature in the same object type (where a call signature *A* is considered assignable to another call signature *B* if an object type containing only *A* would be assignable to an object type containing only *B*). For example, the 'createElement' property in the example above is of a type that contains three specialized signatures, all of which are assignable to the non-specialized signature in the type. - -### 3.9.3 Construct Signatures - -A construct signature defines the parameter list and return type associated with applying the `new` operator (section [4.14](#4.14)) to an instance of the containing type. A type may overload `new` operations by defining multiple construct signatures with different parameter lists. - -  *ConstructSignature:* -   `new` *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt* - -The type parameters, parameter list, and return type of a construct signature are subject to the same rules as a call signature. - -A type containing construct signatures is said to be a ***constructor type***. - -### 3.9.4 Index Signatures - -An index signature defines a type constraint for properties in the containing type. - -  *IndexSignature:* -   `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation* -   `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation* - -There are two kinds of index signatures: - -* ***String index signatures***, specified using index type `string`, define type constraints for all properties and numeric index signatures in the containing type. Specifically, in a type with a string index signature of type *T*, all properties and numeric index signatures must have types that are assignable to *T*. -* ***Numeric index signatures***, specified using index type `number`, define type constraints for all numerically named properties in the containing type. Specifically, in a type with a numeric index signature of type *T*, all numerically named properties must have types that are assignable to *T*. - -A ***numerically named property*** is a property whose name is a valid numeric literal. Specifically, a property with a name *N* for which ToString(ToNumber(*N*)) is identical to *N*, where ToString and ToNumber are the abstract operations defined in ECMAScript specification. - -An object type can contain at most one string index signature and one numeric index signature. - -Index signatures affect the determination of the type that results from applying a bracket notation property access to an instance of the containing type, as described in section [4.13](#4.13). - -### 3.9.5 Method Signatures - -A method signature is shorthand for declaring a property of a function type. - -  *MethodSignature:* -   *PropertyName* `?`*opt* *CallSignature* - -If the *PropertyName* is a computed property name ([2.2.3](#2.2.3)), it must specify a well-known symbol. If the *PropertyName* is followed by a question mark, the property is optional. Otherwise, the property is required. Only object type literals and interfaces can declare optional properties. - -A method signature of the form - -```TypeScript -f < T1, T2, ... > ( p1, p2, ... ) : R -``` - -is equivalent to the property declaration - -```TypeScript -f : { < T1, T2, ... > ( p1, p2, ... ) : R } -``` - -A literal type may ***overload*** a method by declaring multiple method signatures with the same name but differing parameter lists. Overloads must either all be required (question mark omitted) or all be optional (question mark included). A set of overloaded method signatures correspond to a declaration of a single property with a type composed from an equivalent set of call signatures. Specifically - -```TypeScript -f < T1, T2, ... > ( p1, p2, ... ) : R ; -f < U1, U2, ... > ( q1, q2, ... ) : S ; -... -``` - -is equivalent to - -```TypeScript -f : { - < T1, T2, ... > ( p1, p2, ... ) : R ; - < U1, U2, ... > ( q1, q2, ... ) : S ; - ... -} ; -``` - -In the following example of an object type - -```TypeScript -{ - func1(x: number): number; // Method signature - func2: (x: number) => number; // Function type literal - func3: { (x: number): number }; // Object type literal -} -``` - -the properties 'func1', 'func2', and 'func3' are all of the same type, namely an object type with a single call signature taking a number and returning a number. Likewise, in the object type - -```TypeScript -{ - func4(x: number): number; - func4(s: string): string; - func5: { - (x: number): number; - (s: string): string; - }; -} -``` - -the properties 'func4' and 'func5' are of the same type, namely an object type with two call signatures taking and returning number and string respectively. - -## 3.10 Type Aliases - -A type alias declaration introduces a ***type alias*** in the containing declaration space. - -  *TypeAliasDeclaration:* -   `type` *BindingIdentifier* *TypeParametersopt* `=` *Type* `;` - -A type alias serves as an alias for the type specified in the type alias declaration. Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types. - -A type alias may optionally have type parameters (section [3.6.1](#3.6.1)) that serve as placeholders for actual types to be provided when the type alias is referenced in type references. A type alias with type parameters is called a ***generic type alias***. The type parameters of a generic type alias declaration are in scope and may be referenced in the aliased *Type*. - -Type aliases are referenced using type references ([3.8.2](#3.8.2)). Type references to generic type aliases produce instantiations of the aliased type with the given type arguments. Writing a reference to a non-generic type alias has exactly the same effect as writing the aliased type itself, and writing a reference to a generic type alias has exactly the same effect as writing the resulting instantiation of the aliased type. - -The *BindingIdentifier* of a type alias declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). - -It is an error for the type specified in a type alias to depend on that type alias. Types have the following dependencies: - -* A type alias *directly depends on* the type it aliases. -* A type reference *directly depends on* the referenced type and each of the type arguments, if any. -* A union or intersection type *directly depends on* each of the constituent types. -* An array type *directly depends on* its element type. -* A tuple type *directly depends on* each of its element types. -* A type query *directly depends on* the type of the referenced entity. - -Given this definition, the complete set of types upon which a type depends is the transitive closure of the *directly depends on* relationship. Note that object type literals, function type literals, and constructor type literals do not depend on types referenced within them and are therefore permitted to circularly reference themselves through type aliases. - -Some examples of type alias declarations: - -```TypeScript -type StringOrNumber = string | number; -type Text = string | { text: string }; -type NameLookup = Dictionary; -type ObjectStatics = typeof Object; -type Callback = (data: T) => void; -type Pair = [T, T]; -type Coordinates = Pair; -type Tree = T | { left: Tree, right: Tree }; -``` - -Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface type - -```TypeScript -interface Point { - x: number; - y: number; -} -``` - -could be written as the type alias - -```TypeScript -type Point = { - x: number; - y: number; -}; -``` - -However, doing so means the following capabilities are lost: - -* An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot. -* An interface can have multiple merged declarations, but a type alias for an object type literal cannot. - -## 3.11 Type Relationships - -Types in TypeScript have identity, subtype, supertype, and assignment compatibility relationships as defined in the following sections. - -### 3.11.1 Apparent Members - -The ***apparent members*** of a type are the members observed in subtype, supertype, and assignment compatibility relationships, as well as in the type checking of property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)). The apparent members of a type are determined as follows: - -* The apparent members of the primitive type Number and all enum types are the apparent members of the global interface type 'Number'. -* The apparent members of the primitive type Boolean are the apparent members of the global interface type 'Boolean'. -* The apparent members of the primitive type String and all string literal types are the apparent members of the global interface type 'String'. -* The apparent members of a type parameter are the apparent members of the constraint (section [3.6.1](#3.6.1)) of that type parameter. -* The apparent members of an object type *T* are the combination of the following: - * The declared and/or inherited members of *T*. - * The properties of the global interface type 'Object' that aren't hidden by properties with the same name in *T*. - * If *T* has one or more call or construct signatures, the properties of the global interface type 'Function' that aren't hidden by properties with the same name in *T*. -* The apparent members of a union type *U* are determined as follows: - * When all constituent types of *U* have an apparent property named *N*, *U* has an apparent property named *N* of a union type of the respective property types. - * When all constituent types of *U* have an apparent call signature with a parameter list *P*, *U* has an apparent call signature with the parameter list *P* and a return type that is a union of the respective return types. The call signatures appear in the same order as in the first constituent type. - * When all constituent types of *U* have an apparent construct signature with a parameter list *P*, *U* has an apparent construct signature with the parameter list *P* and a return type that is a union of the respective return types. The construct signatures appear in the same order as in the first constituent type. - * When all constituent types of *U* have an apparent string index signature, *U* has an apparent string index signature of a union type of the respective string index signature types. - * When all constituent types of *U* have an apparent numeric index signature, *U* has an apparent numeric index signature of a union type of the respective numeric index signature types. -* The apparent members of an intersection type *I* are determined as follows: - * When one of more constituent types of *I* have an apparent property named *N*, *I* has an apparent property named *N* of an intersection type of the respective property types. - * When one or more constituent types of *I* have a call signature *S*, *I* has the apparent call signature *S*. The signatures are ordered as a concatenation of the signatures of each constituent type in the order of the constituent types within *I*. - * When one or more constituent types of *I* have a construct signature *S*, *I* has the apparent construct signature *S*. The signatures are ordered as a concatenation of the signatures of each constituent type in the order of the constituent types within *I*. - * When one or more constituent types of *I* have an apparent string index signature, *I* has an apparent string index signature of an intersection type of the respective string index signature types. - * When one or more constituent types of *I* have an apparent numeric index signature, *I* has an apparent numeric index signature of an intersection type of the respective numeric index signature types. - -If a type is not one of the above, it is considered to have no apparent members. - -In effect, a type's apparent members make it a subtype of the 'Object' or 'Function' interface unless the type defines members that are incompatible with those of the 'Object' or 'Function' interface—which, for example, occurs if the type defines a property with the same name as a property in the 'Object' or 'Function' interface but with a type that isn't a subtype of that in the 'Object' or 'Function' interface. - -Some examples: - -```TypeScript -var o: Object = { x: 10, y: 20 }; // Ok -var f: Function = (x: number) => x * x; // Ok -var err: Object = { toString: 0 }; // Error -``` - -The last assignment is an error because the object literal has a 'toString' method that isn't compatible with that of 'Object'. - -### 3.11.2 Type and Member Identity - -Two types are considered ***identical*** when - -* they are both the Any type, -* they are the same primitive type, -* they are the same type parameter, -* they are union types with identical sets of constituent types, or -* they are intersection types with identical sets of constituent types, or -* they are object types with identical sets of members. - -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, -* they are identical call signatures, -* they are identical construct signatures, or -* they are index signatures of identical kind with identical types. - -Two call or construct signatures are considered identical when they have the same number of type parameters with identical type parameter constraints and, after substituting type Any for the type parameters introduced by the signatures, identical number of parameters with identical kind (required, optional or rest) and types, and identical return types. - -Note that, except for primitive types and classes with private or protected members, it is structure, not naming, of types that determines identity. Also, note that parameter names are not significant when determining identity of signatures. - -Private and protected properties match only if they originate in the same declaration and have identical types. Two distinct types might contain properties that originate in the same declaration if the types are separate parameterized references to the same generic class. In the example - -```TypeScript -class C { private x: T; } - -interface X { f(): string; } - -interface Y { f(): string; } - -var a: C; -var b: C; -``` - -the variables 'a' and 'b' are of identical types because the two type references to 'C' create types with a private member 'x' that originates in the same declaration, and because the two private 'x' members have types with identical sets of members once the type arguments 'X' and 'Y' are substituted. - -### 3.11.3 Subtypes and Supertypes - -*S* is a ***subtype*** of a type *T*, and *T* is a ***supertype*** of *S*, if *S* has no excess properties with respect to *T* ([3.11.5](#3.11.5)) and one of the following is true: - -* *S* and *T* are identical types. -* *T* is the Any type. -* *S* is the Undefined type. -* *S* is the Null type and *T* is not the Undefined type. -* *S* is an enum type and *T* is the primitive type Number. -* *S* is a string literal type and *T* is the primitive type String. -* *S* is a union type and each constituent type of *S* is a subtype of *T*. -* *S* is an intersection type and at least one constituent type of *S* is a subtype of *T*. -* *T* is a union type and *S* is a subtype of at least one constituent type of *T*. -* *T* is an intersection type and *S* is a subtype of each constituent type of *T*. -* *S* is a type parameter and the constraint of *S* is a subtype of *T*. -* *S* is an object type, an intersection type, an enum type, or the Number, Boolean, or String primitive type, *T* is an object type, and for each member *M* in *T*, one of the following is true: - * *M* is a property and *S* has an apparent property *N* where - * *M* and *N* have the same name, - * the type of *N* is a subtype of that of *M*, - * if *M* is a required property, *N* is also a required property, and - * *M* and *N* are both public, *M* and *N* are both private and originate in the same declaration, *M* and *N* are both protected and originate in the same declaration, or *M* is protected and *N* is declared in a class derived from the class in which *M* is declared. - * *M* is a non-specialized call or construct signature and *S* has an apparent call or construct signature *N* where, when *M* and *N* are instantiated using type Any as the type argument for all type parameters declared by *M* and *N* (if any), - * the signatures are of the same kind (call or construct), - * *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*, - * for parameter positions that are present in both signatures, each parameter type in *N* is a subtype or supertype of the corresponding parameter type in *M*, and - * the result type of *M* is Void, or the result type of *N* is a subtype of that of *M*. - * *M* is a string index signature of type *U*, and *U* is the Any type or *S* has an apparent string index signature of a type that is a subtype of *U*. - * *M* is a numeric index signature of type *U*, and *U* is the Any type or *S* has an apparent string or numeric index signature of a type that is a subtype of *U*. - -When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. - -Note that specialized call and construct signatures (section [3.9.2.4](#3.9.2.4)) are not significant when determining subtype and supertype relationships. - -Also note that type parameters are not considered object types. Thus, the only subtypes of a type parameter *T* are *T* itself and other type parameters that are directly or indirectly constrained to *T*. - -### 3.11.4 Assignment Compatibility - -Types are required to be assignment compatible in certain circumstances, such as expression and variable types in assignment statements and argument and parameter types in function calls. - -*S* is ***assignable to*** a type *T*, and *T* is ***assignable from*** *S*, if *S* has no excess properties with respect to *T* ([3.11.5](#3.11.5)) and one of the following is true: - -* *S* and *T* are identical types. -* *S* or *T* is the Any type. -* *S* is the Undefined type. -* *S* is the Null type and *T* is not the Undefined type. -* *S* or *T* is an enum type and the other is the primitive type Number. -* *S* is a string literal type and *T* is the primitive type String. -* *S* is a union type and each constituent type of *S* is assignable to *T*. -* *S* is an intersection type and at least one constituent type of *S* is assignable to *T*. -* *T* is a union type and *S* is assignable to at least one constituent type of *T*. -* *T* is an intersection type and *S* is assignable to each constituent type of *T*. -* *S* is a type parameter and the constraint of *S* is assignable to *T*. -* *S* is an object type, an intersection type, an enum type, or the Number, Boolean, or String primitive type, *T* is an object type, and for each member *M* in *T*, one of the following is true: - * *M* is a property and *S* has an apparent property *N* where - * *M* and *N* have the same name, - * the type of *N* is assignable to that of *M*, - * if *M* is a required property, *N* is also a required property, and - * *M* and *N* are both public, *M* and *N* are both private and originate in the same declaration, *M* and *N* are both protected and originate in the same declaration, or *M* is protected and *N* is declared in a class derived from the class in which *M* is declared. - * *M* is an optional property and *S* has no apparent property of the same name as *M*. - * *M* is a non-specialized call or construct signature and *S* has an apparent call or construct signature *N* where, when *M* and *N* are instantiated using type Any as the type argument for all type parameters declared by *M* and *N* (if any), - * the signatures are of the same kind (call or construct), - * *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*, - * for parameter positions that are present in both signatures, each parameter type in *N* is assignable to or from the corresponding parameter type in *M*, and - * the result type of *M* is Void, or the result type of *N* is assignable to that of *M*. - * *M* is a string index signature of type *U*, and *U* is the Any type or *S* has an apparent string index signature of a type that is assignable to *U*. - * *M* is a numeric index signature of type *U*, and *U* is the Any type or *S* has an apparent string or numeric index signature of a type that is assignable to *U*. - -When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. - -Note that specialized call and construct signatures (section [3.9.2.4](#3.9.2.4)) are not significant when determining assignment compatibility. - -The assignment compatibility and subtyping rules differ only in that - -* the Any type is assignable to, but not a subtype of, all types, -* the primitive type Number is assignable to, but not a subtype of, all enum types, and -* an object type without a particular property is assignable to an object type in which that property is optional. - -The assignment compatibility rules imply that, when assigning values or passing parameters, optional properties must either be present and of a compatible type, or not be present at all. For example: - -```TypeScript -function foo(x: { id: number; name?: string; }) { } - -foo({ id: 1234 }); // Ok -foo({ id: 1234, name: "hello" }); // Ok -foo({ id: 1234, name: false }); // Error, name of wrong type -foo({ name: "hello" }); // Error, id required but missing -``` - -### 3.11.5 Excess Properties - -The subtype and assignment compatibility relationships require that source types have no excess properties with respect to their target types. The purpose of this check is to detect excess or misspelled properties in object literals. - -A source type *S* is considered to have excess properties with respect to a target type *T* if - -* *S* is a fresh object literal type, as defined below, and -* *S* has one or more properties that aren't expected in *T*. - -A property *P* is said to be expected in a type *T* if one of the following is true: - -* *T* is not an object, union, or intersection type. -* *T* is an object type and - * *T* has a property with the same name as *P*, - * *T* has a string or numeric index signature, - * *T* has no properties, or - * *T* is the global type 'Object'. -* *T* is a union or intersection type and *P* is expected in at least one of the constituent types of *T*. - -The type inferred for an object literal (as described in section [4.5](#4.5)) is considered a ***fresh object literal type***. The freshness disappears when an object literal type is widened ([3.12](#3.12)) or is the type of the expression in a type assertion ([4.16](#4.16)). - -Consider the following example: - -```TypeScript -interface CompilerOptions { - strict?: boolean; - sourcePath?: string; - targetPath?: string; -} - -var options: CompilerOptions = { - strict: true, - sourcepath: "./src", // Error, excess or misspelled property - targetpath: "./bin" // Error, excess or misspelled property -}; -``` - -The 'CompilerOptions' type contains only optional properties, so without the excess property check, *any* object literal would be assignable to the 'options' variable (because a misspelled property would just be considered an excess property of a different name). - -In cases where excess properties are expected, an index signature can be added to the target type as an indicator of intent: - -```TypeScript -interface InputElement { - name: string; - visible?: boolean; - [x: string]: any; // Allow additional properties of any type -} - -var address: InputElement = { - name: "Address", - visible: true, - help: "Enter address here", // Allowed because of index signature - shortcut: "Alt-A" // Allowed because of index signature -}; -``` - -### 3.11.6 Contextual Signature Instantiation - -During type argument inference in a function call (section [4.15.2](#4.15.2)) it is in certain circumstances necessary to instantiate a generic call signature of an argument expression in the context of a non-generic call signature of a parameter such that further inferences can be made. A generic call signature *A* is ***instantiated in the context of*** non-generic call signature *B* as follows: - -* Using the process described in [3.11.7](#3.11.7), inferences for *A*'s type parameters are made from each parameter type in *B* to the corresponding parameter type in *A* for those parameter positions that are present in both signatures, where rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. -* The inferred type argument for each type parameter is the union type of the set of inferences made for that type parameter. However, if the union type does not satisfy the constraint of the type parameter, the inferred type argument is instead the constraint. - -### 3.11.7 Type Inference - -In certain contexts, inferences for a given set of type parameters are made *from* a type *S*, in which those type parameters do not occur, *to* another type *T*, in which those type parameters do occur. Inferences consist of a set of candidate type arguments collected for each of the type parameters. The inference process recursively relates *S* and *T* to gather as many inferences as possible: - -* If *T* is one of the type parameters for which inferences are being made, *S* is added to the set of inferences for that type parameter. -* Otherwise, if *S* and *T* are references to the same generic type, inferences are made from each type argument in *S* to each corresponding type argument in *T*. -* Otherwise, if *S* and *T* are tuple types with the same number of elements, inferences are made from each element type in *S* to each corresponding element type in *T*. -* Otherwise, if *T* is a union or intersection type: - * First, inferences are made from *S* to each constituent type in *T* that isn't simply one of the type parameters for which inferences are being made. - * If the first step produced no inferences then if T is a union type and exactly one constituent type in *T* is simply a type parameter for which inferences are being made, inferences are made from *S* to that type parameter. -* Otherwise, if *S* is a union or intersection type, inferences are made from each constituent type in *S* to *T*. -* Otherwise, if *S* and *T* are object types, then for each member *M* in *T*: - * If *M* is a property and *S* contains a property *N* with the same name as *M*, inferences are made from the type of *N* to the type of *M*. - * If *M* is a call signature and a corresponding call signature *N* exists in *S*, *N* is instantiated with the Any type as an argument for each type parameter (if any) and inferences are made from parameter types in *N* to the corresponding parameter types in *M* for positions that are present in both signatures, and from the return type of *N* to the return type of *M*. - * If *M* is a construct signature and a corresponding construct signature *N* exists in *S*, *N* is instantiated with the Any type as an argument for each type parameter (if any) and inferences are made from parameter types in *N* to the corresponding parameter types in *M* for positions that are present in both signatures, and from the return type of *N* to the return type of *M*. - * If *M* is a string index signature and *S* contains a string index signature *N*, inferences are made from the type of *N* to the type of *M*. - * If *M* is a numeric index signature and *S* contains a numeric index signature *N*, inferences are made from the type of *N* to the type of *M*. - * If *M* is a numeric index signature and *S* contains a string index signature *N*, inferences are made from the type of *N* to the type of *M*. - -When comparing call or construct signatures, signatures in *S* correspond to signatures of the same kind in *T* pairwise in declaration order. If *S* and *T* have different numbers of a given kind of signature, the excess *first* signatures in declaration order of the longer list are ignored. - -*TODO: Update to reflect [improved union and intersection type inference](https://github.com/Microsoft/TypeScript/pull/5738)*. - -### 3.11.8 Recursive Types - -Classes and interfaces can reference themselves in their internal structure, in effect creating recursive types with infinite nesting. For example, the type - -```TypeScript -interface A { next: A; } -``` - -contains an infinitely nested sequence of 'next' properties. Types such as this are perfectly valid but require special treatment when determining type relationships. Specifically, when comparing types *S* and *T* for a given relationship (identity, subtype, or assignability), the relationship in question is assumed to be true for every directly or indirectly nested occurrence of the same *S* and the same *T* (where same means originating in the same declaration and, if applicable, having identical type arguments). For example, consider the identity relationship between 'A' above and 'B' below: - -```TypeScript -interface B { next: C; } - -interface C { next: D; } - -interface D { next: B; } -``` - -To determine whether 'A' and 'B' are identical, first the 'next' properties of type 'A' and 'C' are compared. That leads to comparing the 'next' properties of type 'A' and 'D', which leads to comparing the 'next' properties of type 'A' and 'B'. Since 'A' and 'B' are already being compared this relationship is by definition true. That in turn causes the other comparisons to be true, and therefore the final result is true. - -When this same technique is used to compare generic type references, two type references are considered the same when they originate in the same declaration and have identical type arguments. - -In certain circumstances, generic types that directly or indirectly reference themselves in a recursive fashion can lead to infinite series of distinct instantiations. For example, in the type - -```TypeScript -interface List { - data: T; - next: List; - owner: List>; -} -``` - -'List<T>' has a member 'owner' of type 'List<List<T>>', which has a member 'owner' of type 'List<List<List<T>>>', which has a member 'owner' of type 'List<List<List<List<T>>>>' and so on, ad infinitum. Since type relationships are determined structurally, possibly exploring the constituent types to their full depth, in order to determine type relationships involving infinitely expanding generic types it may be necessary for the compiler to terminate the recursion at some point with the assumption that no further exploration will change the outcome. - -## 3.12 Widened Types - -In several situations TypeScript infers types from context, alleviating the need for the programmer to explicitly specify types that appear obvious. For example - -```TypeScript -var name = "Steve"; -``` - -infers the type of 'name' to be the String primitive type since that is the type of the value used to initialize it. When inferring the type of a variable, property or function result from an expression, the ***widened*** form of the source type is used as the inferred type of the target. The widened form of a type is the type in which all occurrences of the Null and Undefined types have been replaced with the type `any`. - -The following example shows the results of widening types to produce inferred variable types. - -```TypeScript -var a = null; // var a: any -var b = undefined; // var b: any -var c = { x: 0, y: null }; // var c: { x: number, y: any } -var d = [ null, undefined ]; // var d: any[] -``` - -
- -#
4 Expressions - -This chapter describes the manner in which TypeScript provides type inference and type checking for JavaScript expressions. TypeScript's type analysis occurs entirely at compile-time and adds no run-time overhead to expression evaluation. - -TypeScript's typing rules define a type for every expression construct. For example, the type of the literal 123 is the Number primitive type, and the type of the object literal { a: 10, b: "hello" } is { a: number; b: string; }. The sections in this chapter describe these rules in detail. - -In addition to type inference and type checking, TypeScript augments JavaScript expressions with the following constructs: - -* Optional parameter and return type annotations in function expressions and arrow functions. -* Type arguments in function calls. -* Type assertions. - -Unless otherwise noted in the sections that follow, TypeScript expressions and the JavaScript expressions generated from them are identical. - -## 4.1 Values and References - -Expressions are classified as ***values*** or ***references***. References are the subset of expressions that are permitted as the target of an assignment. Specifically, references are combinations of identifiers (section [4.3](#4.3)), parentheses (section [4.8](#4.8)), and property accesses (section [4.13](#4.13)). All other expression constructs described in this chapter are classified as values. - -## 4.2 The this Keyword - -The type of `this` in an expression depends on the location in which the reference takes place: - -* In a constructor, instance member function, instance member accessor, or instance member variable initializer, `this` is of the this-type (section [3.6.3](#3.6.3)) of the containing class. -* In a static member function or static member accessor, the type of `this` is the constructor function type of the containing class. -* In a function declaration or a function expression, `this` is of type Any. -* In the global namespace, `this` is of type Any. - -In all other contexts it is a compile-time error to reference `this`. - -Note that an arrow function (section [4.11](#4.11)) has no `this` parameter but rather preserves the `this` of its enclosing context. - -## 4.3 Identifiers - -When an expression is an *IdentifierReference*, the expression refers to the most nested namespace, class, enum, function, variable, or parameter with that name whose scope (section [2.4](#2.4)) includes the location of the reference. The type of such an expression is the type associated with the referenced entity: - -* For a namespace, the object type associated with the namespace instance. -* For a class, the constructor type associated with the constructor function object. -* For an enum, the object type associated with the enum object. -* For a function, the function type associated with the function object. -* For a variable, the type of the variable. -* For a parameter, the type of the parameter. - -An identifier expression that references a variable or parameter is classified as a reference. An identifier expression that references any other kind of entity is classified as a value (and therefore cannot be the target of an assignment). - -## 4.4 Literals - -Literals are typed as follows: - -* The type of the `null` literal is the Null primitive type. -* The type of the literals `true` and `false` is the Boolean primitive type. -* The type of numeric literals is the Number primitive type. -* The type of string literals is the String primitive type. -* The type of regular expression literals is the global interface type 'RegExp'. - -## 4.5 Object Literals - -Object literals are extended to support type annotations in methods and get and set accessors. - -  *PropertyDefinition:* *( Modified )* -   *IdentifierReference* -   *CoverInitializedName* -   *PropertyName* `:` *AssignmentExpression* -   *PropertyName* *CallSignature* `{` *FunctionBody* `}` -   *GetAccessor* -   *SetAccessor* - -  *GetAccessor:* -   `get` *PropertyName* `(` `)` *TypeAnnotationopt* `{` *FunctionBody* `}` - -  *SetAccessor:* -   `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotationopt* `)` `{` *FunctionBody* `}` - -The type of an object literal is an object type with the set of properties specified by the property assignments in the object literal. A get and set accessor may specify the same property name, but otherwise it is an error to specify multiple property assignments for the same property. - -A shorthand property assignment of the form - -```TypeScript -prop -``` - -is equivalent to - -```TypeScript -prop : prop -``` - -Likewise, a property assignment of the form - -```TypeScript -f ( ... ) { ... } -``` - -is equivalent to - -```TypeScript -f : function ( ... ) { ... } -``` - -Each property assignment in an object literal is processed as follows: - -* If the object literal is contextually typed and the contextual type contains a property with a matching name, the property assignment is contextually typed by the type of that property. -* Otherwise, if the object literal is contextually typed, if the contextual type contains a numeric index signature, and if the property assignment specifies a numeric property name, the property assignment is contextually typed by the type of the numeric index signature. -* Otherwise, if the object literal is contextually typed and the contextual type contains a string index signature, the property assignment is contextually typed by the type of the string index signature. -* Otherwise, the property assignment is processed without a contextual type. - -The type of a property introduced by a property assignment of the form *Name* `:` *Expr* is the type of *Expr*. - -A get accessor declaration is processed in the same manner as an ordinary function declaration (section [6.1](#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. When both a get and set accessor is declared for a property: - -* If both accessors include type annotations, the specified types must be identical. -* If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. -* If neither accessor includes a type annotation, the inferred return type of the get accessor becomes the parameter type of the set accessor. - -If a get accessor is declared for a property, the return type of the get accessor becomes the type of the property. If only a set accessor is declared for a property, the parameter type (which may be type Any if no type annotation is present) of the set accessor becomes the type of the property. - -When an object literal is contextually typed by a type that includes a string index signature, the resulting type of the object literal includes a string index signature with the union type of the types of the properties declared in the object literal, or the Undefined type if the object literal is empty. Likewise, when an object literal is contextually typed by a type that includes a numeric index signature, the resulting type of the object literal includes a numeric index signature with the union type of the types of the numerically named properties (section [3.9.4](#3.9.4)) declared in the object literal, or the Undefined type if the object literal declares no numerically named properties. - -If the *PropertyName* of a property assignment is a computed property name that doesn't denote a well-known symbol ([2.2.3](#2.2.3)), the construct is considered a ***dynamic property assignment***. The following rules apply to dynamic property assignments: - -* A dynamic property assignment does not introduce a property in the type of the object literal. -* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type. -* The name associated with a dynamic property assignment is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type. - -## 4.6 Array Literals - -An array literal - -```TypeScript -[ expr1, expr2, ..., exprN ] -``` - -denotes a value of an array type (section [3.3.2](#3.3.2)) or a tuple type (section [3.3.3](#3.3.3)) depending on context. - -Each element expression in a non-empty array literal is processed as follows: - -* If the array literal contains no spread elements, and if the array literal is contextually typed (section [4.23](#4.23)) by a type *T* and *T* has a property with the numeric name *N*, where *N* is the index of the element expression in the array literal, the element expression is contextually typed by the type of that property. -* Otherwise, if the array literal is contextually typed by a type *T* with a numeric index signature, the element expression is contextually typed by the type of the numeric index signature. -* Otherwise, the element expression is not contextually typed. - -The resulting type an array literal expression is determined as follows: - -* If the array literal is empty, the resulting type is an array type with the element type Undefined. -* Otherwise, if the array literal contains no spread elements and is contextually typed by a tuple-like type (section [3.3.3](#3.3.3)), the resulting type is a tuple type constructed from the types of the element expressions. -* Otherwise, if the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section [4.21.1](#4.21.1)), the resulting type is a tuple type constructed from the types of the element expressions. -* Otherwise, the resulting type is an array type with an element type that is the union of the types of the non-spread element expressions and the numeric index signature types of the spread element expressions. - -A spread element must specify an expression of an array-like type (section [3.3.2](#3.3.2)), or otherwise an error occurs. - -*TODO: The compiler currently doesn't support applying the spread operator to a string (to spread the individual characters of a string into a string array). This will eventually be allowed, but only when the code generation target is ECMAScript 2015 or later*. - -*TODO: Document spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array literal*. - -The rules above mean that an array literal is always of an array type, unless it is contextually typed by a tuple-like type. For example - -```TypeScript -var a = [1, 2]; // number[] -var b = ["hello", true]; // (string | boolean)[] -var c: [number, string] = [3, "three"]; // [number, string] -``` - -When the output target is ECMAScript 3 or 5, array literals containing spread elements are rewritten to invocations of the `concat` method. For example, the assignments - -```TypeScript -var a = [2, 3, 4]; -var b = [0, 1, ...a, 5, 6]; -``` - -are rewritten to - -```TypeScript -var a = [2, 3, 4]; -var b = [0, 1].concat(a, [5, 6]); -``` - -## 4.7 Template Literals - -*TODO: [Template literals](https://github.com/Microsoft/TypeScript/pull/960)*. - -## 4.8 Parentheses - -A parenthesized expression - -```TypeScript -( expr ) -``` - -has the same type and classification as the contained expression itself. Specifically, if the contained expression is classified as a reference, so is the parenthesized expression. - -## 4.9 The super Keyword - -The `super` keyword can be used in expressions to reference base class properties and the base class constructor. - -### 4.9.1 Super Calls - -Super calls consist of the keyword `super` followed by an argument list enclosed in parentheses. Super calls are only permitted in constructors of derived classes, as described in section [8.3.2](#8.3.2). - -A super call invokes the constructor of the base class on the instance referenced by `this`. A super call is processed as a function call (section [4.15](#4.15)) using the construct signatures of the base class constructor function type as the initial set of candidate signatures for overload resolution. Type arguments cannot be explicitly specified in a super call. If the base class is a generic class, the type arguments used to process a super call are always those specified in the `extends` clause that references the base class. - -The type of a super call expression is Void. - -The JavaScript code generated for a super call is specified in section [8.7.2](#8.7.2). - -### 4.9.2 Super Property Access - -A super property access consists of the keyword `super` followed by a dot and an identifier. Super property accesses are used to access base class member functions from derived classes and are permitted in contexts where `this` (section [4.2](#4.2)) references a derived class instance or a derived class constructor function. Specifically: - -* 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. - -Super property accesses are not permitted in other contexts, and it is not possible to access other kinds of base class members in a super property access. Note that super property accesses are not permitted inside function expressions nested in the above constructs because `this` is of type Any in such function expressions. - -Super property accesses are typically used to access overridden base class member functions from derived class member functions. For an example of this, see section [8.4.2](#8.4.2). - -The JavaScript code generated for a super property access is specified in section [8.7.2](#8.7.2). - -*TODO: Update section to include [bracket notation in super property access](https://github.com/Microsoft/TypeScript/issues/3970)*. - -## 4.10 Function Expressions - -Function expressions are extended from JavaScript to optionally include parameter and return type annotations. - -  *FunctionExpression:* *( Modified )* -   `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}` - -The descriptions of function declarations provided in chapter [6](#6) apply to function expressions as well, except that function expressions do not support overloading. - -The type of a function expression is an object type containing a single call signature with parameter and return types inferred from the function expression's signature and body. - -When a function expression with no type parameters and no parameter type annotations is contextually typed (section [4.23](#4.23)) by a type *T* and a contextual signature *S* can be extracted from *T*, the function expression is processed as if it had explicitly specified parameter type annotations as they exist in *S*. Parameters are matched by position and need not have matching names. If the function expression has fewer parameters than *S*, the additional parameters in *S* are ignored. If the function expression has more parameters than *S*, the additional parameters are all considered to have type Any. - -Likewise, when a function expression with no return type annotation is contextually typed (section [4.23](#4.23)) by a function type *T* and a contextual signature *S* can be extracted from *T*, expressions in contained return statements (section [5.10](#5.10)) are contextually typed by the return type of *S*. - -A contextual signature *S* is extracted from a function type *T* as follows: - -* If *T* is a function type with exactly one call signature, and if that call signature is non-generic, *S* is that signature. -* If *T* is a union type, let *U* be the set of element types in *T* that have call signatures. If each type in *U* has exactly one call signature and that call signature is non-generic, and if all of the signatures are identical ignoring return types, then *S* is a signature with the same parameters and a union of the return types. -* Otherwise, no contextual signature can be extracted from *T*. - -In the example - -```TypeScript -var f: (s: string) => string = function (s) { - return s.toLowerCase(); -}; -``` - -the function expression is contextually typed by the type of 'f', and since the function expression has no type parameters or type annotations its parameter type information is extracted from the contextual type, thus inferring the type of 's' to be the String primitive type. - -## 4.11 Arrow Functions - -Arrow functions are extended from JavaScript to optionally include parameter and return type annotations. - -  *ArrowFormalParameters:* *( Modified )* -   *CallSignature* - -The descriptions of function declarations provided in chapter [6](#6) apply to arrow functions as well, except that arrow functions do not support overloading. - -The type of an arrow function is determined in the same manner as a function expression (section [4.10](#4.10)). Likewise, parameters of an arrow function and return statements in the body of an arrow function are contextually typed in the same manner as for function expressions. - -When an arrow function with an expression body and no return type annotation is contextually typed (section [4.23](#4.23)) by a function type *T* and a contextual signature *S* can be extracted from *T*, the expression body is contextually typed by the return type of *S*. - -An arrow function expression of the form - -```TypeScript -( ... ) => expr -``` - -is exactly equivalent to - -```TypeScript -( ... ) => { return expr ; } -``` - -Furthermore, arrow function expressions of the forms - -```TypeScript -id => { ... } -id => expr -``` - -are exactly equivalent to - -```TypeScript -( id ) => { ... } -( id ) => expr -``` - -Thus, the following examples are all equivalent: - -```TypeScript -(x) => { return Math.sin(x); } -(x) => Math.sin(x) -x => { return Math.sin(x); } -x => Math.sin(x) -``` - -A function expression introduces a new dynamically bound `this`, whereas an arrow function expression preserves the `this` of its enclosing context. Arrow function expressions are particularly useful for writing callbacks, which otherwise often have an undefined or unexpected `this`. - -In the example - -```TypeScript -class Messenger { - message = "Hello World"; - start() { - setTimeout(() => alert(this.message), 3000); - } -}; - -var messenger = new Messenger(); -messenger.start(); -``` - -the use of an arrow function expression causes the callback to have the same `this` as the surrounding 'start' method. Writing the callback as a standard function expression it becomes necessary to manually arrange access to the surrounding `this`, for example by copying it into a local variable: - -```TypeScript -class Messenger { - message = "Hello World"; - start() { - var _this = this; - setTimeout(function() { alert(_this.message); }, 3000); - } -}; - -var messenger = new Messenger(); -messenger.start(); -``` - -The TypeScript compiler applies this type of transformation to rewrite arrow function expressions into standard function expressions. - -A construct of the form - -```TypeScript -< T > ( ... ) => { ... } -``` - -could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. It is resolved as the former, but parentheses can be used to select the latter meaning: - -```TypeScript -< T > ( ( ... ) => { ... } ) -``` - -## 4.12 Class Expressions - -*TODO: Document [class expressions](https://github.com/Microsoft/TypeScript/issues/497)*. - -## 4.13 Property Access - -A property access uses either dot notation or bracket notation. A property access expression is always classified as a reference. - -A dot notation property access of the form - -```TypeScript -object . name -``` - -where *object* is an expression and *name* is an identifier (including, possibly, a reserved word), is used to access the property with the given name on the given object. A dot notation property access is processed as follows at compile-time: - -* If *object* is of type Any, any *name* is permitted and the property access is of type Any. -* Otherwise, if *name* denotes an accessible apparent property (section [3.11.1](#3.11.1)) in the widened type (section [3.12](#3.12)) of *object*, the property access is of the type of that property. Public members are always accessible, but private and protected members of a class have restricted accessibility, as described in [8.2.2](#8.2.2). -* Otherwise, the property access is invalid and a compile-time error occurs. - -A bracket notation property access of the form - -```TypeScript -object [ index ] -``` - -where *object* and *index* are expressions, is used to access the property with the name computed by the index expression on the given object. A bracket notation property access is processed as follows at compile-time: - -* If *index* is a string literal or a numeric literal and *object* has an apparent property (section [3.11.1](#3.11.1)) with the name given by that literal (converted to its string representation in the case of a numeric literal), the property access is of the type of that property. -* Otherwise, if *object* has an apparent numeric index signature and *index* is of type Any, the Number primitive type, or an enum type, the property access is of the type of that index signature. -* Otherwise, if *object* has an apparent string index signature and *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature. -* Otherwise, if *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. -* Otherwise, the property access is invalid and a compile-time error occurs. - -*TODO: Indexing with [symbols](https://github.com/Microsoft/TypeScript/pull/1978)*. - -The rules above mean that properties are strongly typed when accessed using bracket notation with the literal representation of their name. For example: - -```TypeScript -var type = { - name: "boolean", - primitive: true -}; - -var s = type["name"]; // string -var b = type["primitive"]; // boolean -``` - -Tuple types assign numeric names to each of their elements and elements are therefore strongly typed when accessed using bracket notation with a numeric literal: - -```TypeScript -var data: [string, number] = ["five", 5]; -var s = data[0]; // string -var n = data[1]; // number -``` - -## 4.14 The new Operator - -A `new` operation has one of the following forms: - -```TypeScript -new C -new C ( ... ) -new C < ... > ( ... ) -``` - -where *C* is an expression. The first form is equivalent to supplying an empty argument list. *C* must be of type Any or of an object type with one or more construct or call signatures. The operation is processed as follows at compile-time: - -* If *C* is of type Any, any argument list is permitted and the result of the operation is of type Any. -* If *C* has one or more apparent construct signatures (section [3.11.1](#3.11.1)), 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. -* If *C* has no apparent construct signatures but one or more apparent 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. - -## 4.15 Function Calls - -Function calls are extended from JavaScript to support optional type arguments. - -  *Arguments:* *( Modified )* -   *TypeArgumentsopt* `(` *ArgumentListopt* `)` - -A function call takes one of the forms - -```TypeScript -func ( ... ) -func < ... > ( ... ) -``` - -where *func* is an expression of a function type or of type Any. The function expression is followed by an optional type argument list (section [3.6.2](#3.6.2)) and an argument list. - -If *func* 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***. In an untyped function call no type arguments are permitted, argument expressions can be of any type and number, no contextual types are provided for the argument expressions, and the result is always of type Any. - -If *func* has apparent call signatures (section [3.11.1](#3.11.1)) the call is a ***typed function call***. TypeScript employs ***overload resolution*** in typed function calls in order to support functions with multiple call signatures. Furthermore, TypeScript may perform ***type argument inference*** to automatically determine type arguments in generic function calls. - -### 4.15.1 Overload Resolution - -The purpose of overload resolution in a function call is to ensure that at least one signature is applicable, to provide contextual types for the arguments, and to determine the result type of the function call, which could differ between the multiple applicable signatures. Overload resolution has no impact on the run-time behavior of a function call. Since JavaScript doesn't support function overloading, all that matters at run-time is the name of the function. - -*TODO: Describe use of [wildcard function types](https://github.com/Microsoft/TypeScript/issues/3970) in overload resolution*. - -The compile-time processing of a typed function call consists of the following steps: - -* First, a list of candidate signatures is constructed from the call signatures in the function type in declaration order. For classes and interfaces, inherited signatures are considered to follow explicitly declared signatures in `extends` clause order. - * A non-generic signature is a candidate when - * the function call has no type arguments, and - * the signature is applicable with respect to the argument list of the function call. - * A generic signature is a candidate in a function call without type arguments when - * type inference (section [4.15.2](#4.15.2)) succeeds for each type parameter, - * once the inferred type arguments are substituted for their associated type parameters, the signature is applicable with respect to the argument list of the function call. - * A generic signature is a candidate in a function call with type arguments when - * The signature has the same number of type parameters as were supplied in the type argument list, - * the type arguments satisfy their constraints, and - * once the type arguments are substituted for their associated type parameters, the signature is applicable with respect to the argument list of the function call. -* If the list of candidate signatures is empty, the function call is an error. -* Otherwise, 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. - -A signature is said to be an ***applicable signature*** with respect to an argument list when - -* the number of arguments is not less than the number of required parameters, -* the number of arguments is not greater than the number of parameters, and -* for each argument expression *e* and its corresponding parameter *P,* when *e* is contextually typed (section [4.23](#4.23)) by the type of *P*, no errors ensue and the type of *e* is assignable to (section [3.11.4](#3.11.4)) the type of *P*. - -*TODO: [Spread operator in function calls](https://github.com/Microsoft/TypeScript/pull/1931) and spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into a function call*. - -### 4.15.2 Type Argument Inference - -Given a signature < *T1* , *T2* , … , *Tn* > ( *p1* : *P1* , *p2* : *P2* , … , *pm* : *Pm* ), where each parameter type *P* references zero or more of the type parameters *T*, and an argument list ( *e1* , *e2* , … , *em* ), the task of type argument inference is to find a set of type arguments *A1*…*An* to substitute for *T1*…*Tn* such that the argument list becomes an applicable signature. - -*TODO: Update [type argument inference and overload resolution rules](https://github.com/Microsoft/TypeScript/issues/1186)*. - -Type argument inference produces a set of candidate types for each type parameter. Given a type parameter *T* and set of candidate types, the actual inferred type argument is determined as follows: - -* If the set of candidate argument types is empty, the inferred type argument for *T* is *T*'s constraint. -* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the widened form (section [3.12](#3.12)) of the first such candidate type. If *C* satisfies *T*'s constraint, the inferred type argument for *T* is *C*. Otherwise, the inferred type argument for *T* is *T*'s constraint. -* Otherwise, if no candidate type is a supertype of all of the other candidate types, type inference has fails and no type argument is inferred for *T*. - -In order to compute candidate types, the argument list is processed as follows: - -* Initially all inferred type arguments are considered ***unfixed*** with an empty set of candidate types. -* Proceeding from left to right, each argument expression *e* is ***inferentially typed*** by its corresponding parameter type *P*, possibly causing some inferred type arguments to become ***fixed***, and candidate type inferences (section [3.11.7](#3.11.7)) are made for unfixed inferred type arguments from the type computed for *e* to *P*. - -The process of inferentially typing an expression *e* by a type *T* is the same as that of contextually typing *e* by *T*, with the following exceptions: - -* Where expressions contained within *e* would be contextually typed, they are instead inferentially typed. -* When a function expression is inferentially typed (section [4.10](#4.10)) and a type assigned to a parameter in that expression references type parameters for which inferences are being made, the corresponding inferred type arguments to become ***fixed*** and no further candidate inferences are made for them. -* If *e* is an expression of a function type that contains exactly one generic call signature and no other members, and *T* is a function type with exactly one non-generic call signature and no other members, then any inferences made for type parameters referenced by the parameters of *T*'s call signature are ***fixed***, and *e*'s type is changed to a function type with *e*'s call signature instantiated in the context of *T*'s call signature (section [3.11.6](#3.11.6)). - -An example: - -```TypeScript -function choose(x: T, y: T): T { - return Math.random() < 0.5 ? x : y; -} - -var x = choose(10, 20); // Ok, x of type number -var y = choose("Five", 5); // Error -``` - -In the first call to 'choose', two inferences are made from 'number' to 'T', one for each parameter. Thus, 'number' is inferred for 'T' and the call is equivalent to - -```TypeScript -var x = choose(10, 20); -``` - -In the second call to 'choose', an inference is made from type 'string' to 'T' for the first parameter and an inference is made from type 'number' to 'T' for the second parameter. Since neither 'string' nor 'number' is a supertype of the other, type inference fails. That in turn means there are no applicable signatures and the function call is an error. - -In the example - -```TypeScript -function map(a: T[], f: (x: T) => U): U[] { - var result: U[] = []; - for (var i = 0; i < a.length; i++) result.push(f(a[i])); - return result; -} - -var names = ["Peter", "Paul", "Mary"]; -var lengths = map(names, s => s.length); -``` - -inferences for 'T' and 'U' in the call to 'map' are made as follows: For the first parameter, inferences are made from the type 'string[]' (the type of 'names') to the type 'T[]', inferring 'string' for 'T'. For the second parameter, inferential typing of the arrow expression 's => s.length' causes 'T' to become fixed such that the inferred type 'string' can be used for the parameter 's'. The return type of the arrow expression can then be determined, and inferences are made from the type '(s: string) => number' to the type '(x: T) => U', inferring 'number' for 'U'. Thus the call to 'map' is equivalent to - -```TypeScript -var lengths = map(names, s => s.length); -``` - -and the resulting type of 'lengths' is therefore 'number[]'. - -In the example - -```TypeScript -function zip(x: S[], y: T[], combine: (x: S) => (y: T) => U): U[] { - var len = Math.max(x.length, y.length); - var result: U[] = []; - for (var i = 0; i < len; i++) result.push(combine(x[i])(y[i])); - return result; -} - -var names = ["Peter", "Paul", "Mary"]; -var ages = [7, 9, 12]; -var pairs = zip(names, ages, s => n => ({ name: s, age: n })); -``` - -inferences for 'S', 'T' and 'U' in the call to 'zip' are made as follows: Using the first two parameters, inferences of 'string' for 'S' and 'number' for 'T' are made. For the third parameter, inferential typing of the outer arrow expression causes 'S' to become fixed such that the inferred type 'string' can be used for the parameter 's'. When a function expression is inferentially typed, its return expression(s) are also inferentially typed. Thus, the inner arrow function is inferentially typed, causing 'T' to become fixed such that the inferred type 'number' can be used for the parameter 'n'. The return type of the inner arrow function can then be determined, which in turn determines the return type of the function returned from the outer arrow function, and inferences are made from the type '(s: string) => (n: number) => { name: string; age: number }' to the type '(x: S) => (y: T) => R', inferring '{ name: string; age: number }' for 'R'. Thus the call to 'zip' is equivalent to - -```TypeScript -var pairs = zip( - names, ages, s => n => ({ name: s, age: n })); -``` - -and the resulting type of 'pairs' is therefore '{ name: string; age: number }[]'. - -### 4.15.3 Grammar Ambiguities - -The inclusion of type arguments in the *Arguments* production (section [4.15](#4.15)) gives rise to certain ambiguities in the grammar for expressions. For example, the statement - -```TypeScript -f(g(7)); -``` - -could be interpreted as a call to 'f' with two arguments, 'g < A' and 'B > (7)'. Alternatively, it could be interpreted as a call to 'f' with one argument, which is a call to a generic function 'g' with two type arguments and one regular argument. - -The grammar ambiguity is resolved as follows: In a context where one possible interpretation of a sequence of tokens is an *Arguments* production, if the initial sequence of tokens forms a syntactically correct *TypeArguments* production and is followed by a '`(`' token, then the sequence of tokens is processed an *Arguments* production, and any other possible interpretation is discarded. Otherwise, the sequence of tokens is not considered an *Arguments* production. - -This rule means that the call to 'f' above is interpreted as a call with one argument, which is a call to a generic function 'g' with two type arguments and one regular argument. However, the statements - -```TypeScript -f(g < A, B > 7); -f(g < A, B > +(7)); -``` - -are both interpreted as calls to 'f' with two arguments. - -## 4.16 Type Assertions - -TypeScript extends the JavaScript expression grammar with the ability to assert a type for an expression: - -  *UnaryExpression:* *( Modified )* -   … -   `<` *Type* `>` *UnaryExpression* - -A type assertion expression consists of a type enclosed in `<` and `>` followed by a unary expression. Type assertion expressions are purely a compile-time construct. Type assertions are *not* checked at run-time and have no impact on the emitted JavaScript (and therefore no run-time cost). The type and the enclosing `<` and `>` are simply removed from the generated code. - -In a type assertion expression of the form < *T* > *e*, *e* is contextually typed (section [4.23](#4.23)) by *T* and the resulting type of* e* is required to be assignable to *T*, or *T* is required to be assignable to the widened form of the resulting type of *e*, or otherwise a compile-time error occurs. The type of the result is *T*. - -Type assertions check for assignment compatibility in both directions. Thus, type assertions allow type conversions that *might* be correct, but aren't *known* to be correct. In the example - -```TypeScript -class Shape { ... } - -class Circle extends Shape { ... } - -function createShape(kind: string): Shape { - if (kind === "circle") return new Circle(); - ... -} - -var circle = createShape("circle"); -``` - -the type annotations indicate that the 'createShape' function *might* return a 'Circle' (because 'Circle' is a subtype of 'Shape'), but isn't *known* to do so (because its return type is 'Shape'). Therefore, a type assertion is needed to treat the result as a 'Circle'. - -As mentioned above, type assertions are not checked at run-time and it is up to the programmer to guard against errors, for example using the `instanceof` operator: - -```TypeScript -var shape = createShape(shapeKind); -if (shape instanceof Circle) { - var circle = shape; - ... -} -``` - -*TODO: Document [as operator](https://github.com/Microsoft/TypeScript/pull/3564)*. - -## 4.17 JSX Expressions - -*TODO: Document [JSX expressions](https://github.com/Microsoft/TypeScript/issues/3203)*. - -## 4.18 Unary Operators - -The subsections that follow specify the compile-time processing rules of the unary operators. In general, if the operand of a unary operator does not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type Any in further processing. - -### 4.18.1 The ++ and -- operators - -These operators, in prefix or postfix form, require their operand to be of type Any, the Number primitive type, or an enum type, and classified as a reference (section [4.1](#4.1)). They produce a result of the Number primitive type. - -### 4.18.2 The +, –, and ~ operators - -These operators permit their operand to be of any type and produce a result of the Number primitive type. - -The unary + operator can conveniently be used to convert a value of any type to the Number primitive type: - -```TypeScript -function getValue() { ... } - -var n = +getValue(); -``` - -The example above converts the result of 'getValue()' to a number if it isn't a number already. The type inferred for 'n' is the Number primitive type regardless of the return type of 'getValue'. - -### 4.18.3 The ! operator - -The ! operator permits its operand to be of any type and produces a result of the Boolean primitive type. - -Two unary ! operators in sequence can conveniently be used to convert a value of any type to the Boolean primitive type: - -```TypeScript -function getValue() { ... } - -var b = !!getValue(); -``` - -The example above converts the result of 'getValue()' to a Boolean if it isn't a Boolean already. The type inferred for 'b' is the Boolean primitive type regardless of the return type of 'getValue'. - -### 4.18.4 The delete Operator - -The 'delete' operator takes an operand of any type and produces a result of the Boolean primitive type. - -### 4.18.5 The void Operator - -The 'void' operator takes an operand of any type and produces the value 'undefined'. The type of the result is the Undefined type ([3.2.7](#3.2.7)). - -### 4.18.6 The typeof Operator - -The 'typeof' operator takes an operand of any type and produces a value of the String primitive type. In positions where a type is expected, 'typeof' can also be used in a type query (section [3.8.10](#3.8.10)) to produce the type of an expression. - -```TypeScript -var x = 5; -var y = typeof x; // Use in an expression -var z: typeof x; // Use in a type query -``` - -In the example above, 'x' is of type 'number', 'y' is of type 'string' because when used in an expression, 'typeof' produces a value of type string (in this case the string "number"), and 'z' is of type 'number' because when used in a type query, 'typeof' obtains the type of an expression. - -## 4.19 Binary Operators - -The subsections that follow specify the compile-time processing rules of the binary operators. In general, if the operands of a binary operator do not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type any in further processing. Tables that summarize the compile-time processing rules for operands of the Any type, the Boolean, Number, and String primitive types, and all other types (the Other column in the tables) are provided. - -### 4.19.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators - -These operators require their operands to be of type Any, the Number primitive type, or an enum type. Operands of an enum type are treated as having the primitive type Number. If one operand is the `null` or `undefined` value, it is treated as having the type of the other operand. The result is always of the Number primitive type. - -||Any|Boolean|Number|String|Other| -|:---:|:---:|:---:|:---:|:---:|:---:| -|Any|Number||Number||| -|Boolean|||||| -|Number|Number||Number||| -|String|||||| -|Other|||||| - -*TODO: Document the [exponentation operator](https://github.com/Microsoft/TypeScript/issues/4812)*. - -### 4.19.2 The + operator - -The binary + operator requires both operands to be of the Number primitive type or an enum type, or at least one of the operands to be of type Any or the String primitive type. Operands of an enum type are treated as having the primitive type Number. If one operand is the `null` or `undefined` value, it is treated as having the type of the other operand. If both operands are of the Number primitive type, the result is of the Number primitive type. If one or both operands are of the String primitive type, the result is of the String primitive type. Otherwise, the result is of type Any. - -||Any|Boolean|Number|String|Other| -|:---:|:---:|:---:|:---:|:---:|:---:| -|Any|Any|Any|Any|String|Any| -|Boolean|Any|||String|| -|Number|Any||Number|String|| -|String|String|String|String|String|String| -|Other|Any|||String|| - -A value of any type can converted to the String primitive type by adding an empty string: - -```TypeScript -function getValue() { ... } - -var s = getValue() + ""; -``` - -The example above converts the result of 'getValue()' to a string if it isn't a string already. The type inferred for 's' is the String primitive type regardless of the return type of 'getValue'. - -### 4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators - -These operators require one or both of the operand types to be assignable to the other. The result is always of the Boolean primitive type. - -||Any|Boolean|Number|String|Other| -|:---:|:---:|:---:|:---:|:---:|:---:| -|Any|Boolean|Boolean|Boolean|Boolean|Boolean| -|Boolean|Boolean|Boolean|||| -|Number|Boolean||Boolean||| -|String|Boolean|||Boolean|| -|Other|Boolean||||Boolean| - -### 4.19.4 The instanceof operator - -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 or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type. - -Note that object types containing one or more call or construct signatures are automatically subtypes of the 'Function' interface type, as described in section [3.3](#3.3). - -### 4.19.5 The in operator - -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. - -### 4.19.6 The && operator - -The && operator permits the operands to be of any type and produces a result of the same type as the second operand. - -||Any|Boolean|Number|String|Other| -|:---:|:---:|:---:|:---:|:---:|:---:| -|Any|Any|Boolean|Number|String|Other| -|Boolean|Any|Boolean|Number|String|Other| -|Number|Any|Boolean|Number|String|Other| -|String|Any|Boolean|Number|String|Other| -|Other|Any|Boolean|Number|String|Other| - -### 4.19.7 The || operator - -The || operator permits the operands to be of any type. - -If the || expression is contextually typed (section [4.23](#4.23)), the operands are contextually typed by the same type. Otherwise, the left operand is not contextually typed and the right operand is contextually typed by the type of the left operand. - -The type of the result is the union type of the two operand types. - -||Any|Boolean|Number|String|Other| -|:---:|:---:|:---:|:---:|:---:|:---:| -|Any|Any|Any|Any|Any|Any| -|Boolean|Any|Boolean|N | B|S | B|B | O| -|Number|Any|N | B|Number|S | N|N | O| -|String|Any|S | B|S | N|String|S | O| -|Other|Any|B | O|N | O|S | O|Other| - -## 4.20 The Conditional Operator - -In a conditional expression of the form - -```TypeScript -test ? expr1 : expr2 -``` - -the *test* expression may be of any type. - -If the conditional expression is contextually typed (section [4.23](#4.23)), *expr1* and *expr2* are contextually typed by the same type. Otherwise, *expr1* and *expr2* are not contextually typed. - -The type of the result is the union type of the types of *expr1* and *expr2*. - -## 4.21 Assignment Operators - -An assignment of the form - -```TypeScript -v = expr -``` - -requires *v* to be classified as a reference (section [4.1](#4.1)) or as an assignment pattern (section [4.21.1](#4.21.1)). The *expr* expression is contextually typed (section [4.23](#4.23)) by the type of *v*, and the type of *expr* must be assignable to (section [3.11.4](#3.11.4)) the type of *v*, or otherwise a compile-time error occurs. The result is a value with the type of *expr*. - -A compound assignment of the form - -```TypeScript -v ??= expr -``` - -where ??= is one of the compound assignment operators - -```TypeScript -*= /= %= += -= <<= >>= >>>= &= ^= |= -``` - -is subject to the same requirements, and produces a value of the same type, as the corresponding non-compound operation. A compound assignment furthermore requires *v* to be classified as a reference (section [4.1](#4.1)) and the type of the non-compound operation to be assignable to the type of *v*. Note that *v* is not permitted to be an assignment pattern in a compound assignment. - -### 4.21.1 Destructuring Assignment - -A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern as defined by the *AssignmentPattern* production in the ECMAScript 2015 specification. - -In a destructuring assignment expression, the type of the expression on the right must be assignable to the assignment target on the left. An expression of type *S* is considered assignable to an assignment target *V* if one of the following is true: - -* *V* is variable and *S* is assignable to the type of *V*. -* *V* is an object assignment pattern and, for each assignment property *P* in *V*, - * *S* is the type Any, or - * *S* has an apparent property with the property name specified in *P* of a type that is assignable to the target given in *P*, or - * *P* specifies a numeric property name and *S* has a numeric index signature of a type that is assignable to the target given in *P*, or - * *S* has a string index signature of a type that is assignable to the target given in *P*. -* *V* is an array assignment pattern, *S* is the type Any or an array-like type (section [3.3.2](#3.3.2)), and, for each assignment element *E* in *V*, - * *S* is the type Any, or - * *S* is a tuple-like type (section [3.3.3](#3.3.3)) with a property named *N* of a type that is assignable to the target given in *E*, where *N* is the numeric index of *E* in the array assignment pattern, or - * *S* is not a tuple-like type and the numeric index signature type of *S* is assignable to the target given in *E*. - -*TODO: [Update to specify behavior when assignment element E is a rest element](https://github.com/Microsoft/TypeScript/issues/2713)*. - -In an assignment property or element that includes a default value, the type of the default value must be assignable to the target given in the assignment property or element. - -When the output target is ECMAScript 2015 or higher, destructuring variable assignments remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring variable assignments are rewritten to series of simple assignments. For example, the destructuring assignment - -```TypeScript -var x = 1; -var y = 2; -[x, y] = [y, x]; -``` - -is rewritten to the simple variable assignments - -```TypeScript -var x = 1; -var y = 2; -_a = [y, x], x = _a[0], y = _a[1]; -var _a; -``` - -## 4.22 The Comma Operator - -The comma operator permits the operands to be of any type and produces a result that is of the same type as the second operand. - -## 4.23 Contextually Typed Expressions - -Type checking of an expression is improved in several contexts by factoring in the type of the destination of the value computed by the expression. In such situations, the expression is said to be ***contextually typed*** by the type of the destination. An expression is contextually typed in the following circumstances: - -* In a variable, parameter, binding property, binding element, or member declaration, an initializer expression is contextually typed by - * the type given in the declaration's type annotation, if any, or otherwise - * for a parameter, the type provided by a contextual signature (section [4.10](#4.10)), if any, or otherwise - * the type implied by the binding pattern in the declaration (section [5.2.3](#5.2.3)), if any. -* In the body of a function declaration, function expression, arrow function, method declaration, or get accessor declaration that has a return type annotation, return expressions are contextually typed by the type given in the return type annotation. -* In the body of a function expression or arrow function that has no return type annotation, if the function expression or arrow function is contextually typed by a function type with exactly one call signature, and if that call signature is non-generic, return expressions are contextually typed by the return type of that call signature. -* In the body of a constructor declaration, return expressions are contextually typed by the containing class type. -* In the body of a get accessor with no return type annotation, if a matching set accessor exists and that set accessor has a parameter type annotation, return expressions are contextually typed by the type given in the set accessor's parameter type annotation. -* In a typed function call, argument expressions are contextually typed by their corresponding parameter types. -* In a contextually typed object literal, each property value expression is contextually typed by - * the type of the property with a matching name in the contextual type, if any, or otherwise - * for a numerically named property, the numeric index type of the contextual type, if any, or otherwise - * the string index type of the contextual type, if any. -* In a contextually typed array literal expression containing no spread elements, an element expression at index *N* is contextually typed by - * the type of the property with the numeric name *N* in the contextual type, if any, or otherwise - * the numeric index type of the contextual type, if any. -* In a contextually typed array literal expression containing one or more spread elements, an element expression at index *N* is contextually typed by the numeric index type of the contextual type, if any. -* In a contextually typed parenthesized expression, the contained expression is contextually typed by the same type. -* In a type assertion, the expression is contextually typed by the indicated type. -* In a || operator expression, if the expression is contextually typed, the operands are contextually typed by the same type. Otherwise, the right expression is contextually typed by the type of the left expression. -* In a contextually typed conditional operator expression, the operands are contextually typed by the same type. -* In an assignment expression, the right hand expression is contextually typed by the type of the left hand expression. - -In the following example - -```TypeScript -interface EventObject { - x: number; - y: number; -} - -interface EventHandlers { - mousedown?: (event: EventObject) => void; - mouseup?: (event: EventObject) => void; - mousemove?: (event: EventObject) => void; -} - -function setEventHandlers(handlers: EventHandlers) { ... } - -setEventHandlers({ - mousedown: e => { startTracking(e.x, e.y); }, - mouseup: e => { endTracking(); } -}); -``` - -the object literal passed to 'setEventHandlers' is contextually typed to the 'EventHandlers' type. This causes the two property assignments to be contextually typed to the unnamed function type '(event: EventObject) => void', which in turn causes the 'e' parameters in the arrow function expressions to automatically be typed as 'EventObject'. - -## 4.24 Type Guards - -Type guards are particular expression patterns involving the 'typeof' and 'instanceof' operators that cause the types of variables or parameters to be ***narrowed*** to more specific types. For example, in the code below, knowledge of the static type of 'x' in combination with a 'typeof' check makes it safe to narrow the type of 'x' to string in the first branch of the 'if' statement and number in the second branch of the 'if' statement. - -```TypeScript -function foo(x: number | string) { - if (typeof x === "string") { - return x.length; // x has type string here - } - else { - return x + 1; // x has type number here - } -} -``` - -The type of a variable or parameter is narrowed in the following situations: - -* In the true branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when true*, provided no part of the 'if' statement contains assignments to the variable or parameter. -* In the false branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when false*, provided no part of the 'if' statement contains assignments to the variable or parameter. -* In the true expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when true*, provided no part of the conditional expression contains assignments to the variable or parameter. -* In the false expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when false*, provided no part of the conditional expression contains assignments to the variable or parameter. -* In the right operand of a && operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when true*, provided neither operand contains assignments to the variable or parameter. -* In the right operand of a || operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when false*, provided neither operand contains assignments to the variable or parameter. - -A type guard is simply an expression that follows a particular pattern. The process of narrowing the type of a variable *x* by a type guard *when true* or *when false* depends on the type guard as follows: - -* A type guard of the form `x instanceof C`, where *x* is not of type Any, *C* is of a subtype of the global type 'Function', and *C* has a property named 'prototype' - * *when true*, narrows the type of *x* to the type of the 'prototype' property in *C* provided it is a subtype of the type of *x*, or, if the type of *x* is a union type, removes from the type of *x* all constituent types that aren't subtypes of the type of the 'prototype' property in *C*, or - * *when false*, has no effect on the type of *x*. -* A type guard of the form `typeof x === s`, where *s* is a string literal with the value 'string', 'number', or 'boolean', - * *when true*, narrows the type of *x* to the given primitive type provided it is a subtype of the type of *x*, or, if the type of *x* is a union type, removes from the type of *x* all constituent types that aren't subtypes of the given primitive type, or - * *when false*, removes the primitive type from the type of *x*. -* A type guard of the form `typeof x === s`, where *s* is a string literal with any value but 'string', 'number', or 'boolean', - * *when true*, if *x* is a union type, removes from the type of *x* all constituent types that are subtypes of the string, number, or boolean primitive type, or - * *when false*, has no effect on the type of *x*. -* A type guard of the form `typeof x !== s`, where *s* is a string literal, - * *when true*, narrows the type of x by `typeof x === s` *when false*, or - * *when false*, narrows the type of x by `typeof x === s` *when true*. -* A type guard of the form `!expr` - * *when true*, narrows the type of *x* by *expr* *when false*, or - * *when false*, narrows the type of *x* by *expr* *when true*. -* A type guard of the form `expr1 && expr2` - * *when true*, narrows the type of *x* by *expr1* *when true* and then by *expr2* *when true*, or - * *when false*, narrows the type of *x* to *T1* | *T2*, where *T1* is the type of *x* narrowed by *expr1* *when false*, and *T2* is the type of *x* narrowed by *expr1* *when true* and then by *expr2* *when false*. -* A type guard of the form `expr1 || expr2` - * *when true*, narrows the type of *x* to *T1* | *T2*, where *T1* is the type of *x* narrowed by *expr1* *when true*, and *T2* is the type of *x* narrowed by *expr1* *when false* and then by *expr2* *when true*, or - * *when false*, narrows the type of *x* by *expr1* *when false* and then by *expr2* *when false*. -* A type guard of any other form has no effect on the type of *x*. - -In the rules above, when a narrowing operation would remove all constituent types from a union type, the operation has no effect on the union type. - -Note that type guards affect types of variables and parameters only and have no effect on members of objects such as properties. Also note that it is possible to defeat a type guard by calling a function that changes the type of the guarded variable. - -*TODO: Document [user defined type guard functions](https://github.com/Microsoft/TypeScript/issues/1007)*. - -In the example - -```TypeScript -function isLongString(obj: any) { - return typeof obj === "string" && obj.length > 100; -} -``` - -the `obj` parameter has type `string` in the right operand of the && operator. - -In the example - -```TypeScript -function processValue(value: number | (() => number)) { - var x = typeof value !== "number" ? value() : value; - // Process number in x -} -``` - -the value parameter has type `() => number` in the first conditional expression and type `number` in the second conditional expression, and the inferred type of x is `number`. - -In the example - -```TypeScript -function f(x: string | number | boolean) { - if (typeof x === "string" || typeof x === "number") { - var y = x; // Type of y is string | number - } - else { - var z = x; // Type of z is boolean - } -} -``` - -the type of x is `string | number | boolean` in the left operand of the || operator, `number | boolean` in the right operand of the || operator, `string | number` in the first branch of the if statement, and `boolean` in the second branch of the if statement. - -In the example - -```TypeScript -class C { - data: string | string[]; - getData() { - var data = this.data; - return typeof data === "string" ? data : data.join(" "); - } -} -``` - -the type of the `data` variable is `string` in the first conditional expression and `string[]` in the second conditional expression, and the inferred type of `getData` is `string`. Note that the `data` property must be copied to a local variable for the type guard to have an effect. - -In the example - -```TypeScript -class NamedItem { - name: string; -} - -function getName(obj: Object) { - return obj instanceof NamedItem ? obj.name : "unknown"; -} -``` - -the type of `obj` is narrowed to `NamedItem` in the first conditional expression, and the inferred type of the `getName` function is `string`. - -
- -#
5 Statements - -This chapter describes the static type checking TypeScript provides for JavaScript statements. TypeScript itself does not introduce any new statement constructs, but it does extend the grammar for local declarations to include interface, type alias, and enum declarations. - -## 5.1 Blocks - -Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 2015 grammar). - -  *Declaration:* *( Modified )* -   … -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *EnumDeclaration* - -Local class, interface, type alias, and enum declarations are block scoped, similar to let and const declarations. - -## 5.2 Variable Statements - -Variable statements are extended to include optional type annotations. - -  *VariableDeclaration:* *( Modified )* -   *SimpleVariableDeclaration* -   *DestructuringVariableDeclaration* - -A variable declaration is either a simple variable declaration or a destructuring variable declaration. - -### 5.2.1 Simple Variable Declarations - -A ***simple variable declaration*** introduces a single named variable and optionally assigns it an initial value. - -  *SimpleVariableDeclaration:* -   *BindingIdentifier* *TypeAnnotationopt* *Initializeropt* - -The type *T* of a variable introduced by a simple variable declaration is determined as follows: - -* If the declaration includes a type annotation, *T* is that type. -* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.12](#3.12)) of the type of the initializer expression. -* Otherwise, *T* is the Any type. - -When a variable declaration specifies both a type annotation and an initializer expression, the type of the initializer expression is required to be assignable to (section [3.11.4](#3.11.4)) the type given in the type annotation. - -Multiple declarations for the same variable name in the same declaration space are permitted, provided that each declaration associates the same type with the variable. - -When a variable declaration has a type annotation, it is an error for that type annotation to use the `typeof` operator to reference the variable being declared. - -Below are some examples of simple variable declarations and their associated types. - -```TypeScript -var a; // any -var b: number; // number -var c = 1; // number -var d = { x: 1, y: "hello" }; // { x: number; y: string; } -var e: any = "test"; // any -``` - -The following is permitted because all declarations of the single variable 'x' associate the same type (Number) with 'x'. - -```TypeScript -var x = 1; -var x: number; -if (x == 1) { - var x = 2; -} -``` - -In the following example, all five variables are of the same type, '{ x: number; y: number; }'. - -```TypeScript -interface Point { x: number; y: number; } - -var a = { x: 0, y: undefined }; -var b: Point = { x: 0, y: undefined }; -var c = { x: 0, y: undefined }; -var d: { x: number; y: number; } = { x: 0, y: undefined }; -var e = <{ x: number; y: number; }> { x: 0, y: undefined }; -``` - -### 5.2.2 Destructuring Variable Declarations - -A ***destructuring variable declaration*** introduces zero or more named variables and initializes them with values extracted from properties of an object or elements of an array. - -  *DestructuringVariableDeclaration:* -   *BindingPattern* *TypeAnnotationopt* *Initializer* - -Each binding property or element that specifies an identifier introduces a variable by that name. The type of the variable is the widened form (section [3.12](#3.12)) of the type associated with the binding property or element, as defined in the following. - -*TODO: Document destructuring an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array*. - -The type *T* associated with a destructuring variable declaration is determined as follows: - -* If the declaration includes a type annotation, *T* is that type. -* Otherwise, if the declaration includes an initializer expression, *T* is the type of that initializer expression. -* Otherwise, *T* is the Any type. - -The type *T* associated with a binding property is determined as follows: - -* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element. -* If *S* is the Any type: - * If the binding property specifies an initializer expression, *T* is the type of that initializer expression. - * Otherwise, *T* is the Any type. -* Let *P* be the property name specified in the binding property. -* If *S* has an apparent property with the name *P*, *T* is the type of that property. -* Otherwise, if *S* has a numeric index signature and *P* is a numerical name, *T* is the type of the numeric index signature. -* Otherwise, if *S* has a string index signature, *T* is the type of the string index signature. -* Otherwise, no type is associated with the binding property and an error occurs. - -The type *T* associated with a binding element is determined as follows: - -* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element. -* If *S* is the Any type: - * If the binding element specifies an initializer expression, *T* is the type of that initializer expression. - * Otherwise, *T* is the Any type. -* If *S* is not an array-like type (section [3.3.2](#3.3.2)), no type is associated with the binding property and an error occurs. -* If the binding element is a rest element, *T* is an array type with an element type *E*, where *E* is the type of the numeric index signature of *S*. -* Otherwise, if *S* is a tuple-like type (section [3.3.3](#3.3.3)): - * Let *N* be the zero-based index of the binding element in the array binding pattern. - * If *S* has a property with the numerical name *N*, *T* is the type of that property. - * Otherwise, no type is associated with the binding element and an error occurs. -* Otherwise, if *S* has a numeric index signature, *T* is the type of the numeric index signature. -* Otherwise, no type is associated with the binding element and an error occurs. - -When a destructuring variable declaration, binding property, or binding element specifies an initializer expression, the type of the initializer expression is required to be assignable to the widened form of the type associated with the destructuring variable declaration, binding property, or binding element. - -*TODO: Update rules to reflect [improved checking of destructuring with literal initializers](https://github.com/Microsoft/TypeScript/pull/4598)*. - -When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code. - -When the output target is ECMAScript 3 or 5, destructuring variable declarations are rewritten to simple variable declarations. For example, an object destructuring declaration of the form - -```TypeScript -var { x, p: y, q: z = false } = getSomeObject(); -``` - -is rewritten to the simple variable declarations - -```TypeScript -var _a = getSomeObject(), - x = _a.x, - y = _a.p, - _b = _a.q, - z = _b === void 0 ? false : _b; -``` - -The '_a' and '_b' temporary variables exist to ensure the assigned expression is evaluated only once, and the expression 'void 0' simply denotes the JavaScript value 'undefined'. - -Similarly, an array destructuring declaration of the form - -```TypeScript -var [x, y, z = 10] = getSomeArray(); -``` - -is rewritten to the simple variable declarations - -```TypeScript -var _a = getSomeArray(), - x = _a[0], - y = _a[1], - _b = _a[2], - z = _b === void 0 ? 10 : _b; -``` - -Combining both forms of destructuring, the example - -```TypeScript -var { x, p: [y, z = 10] = getSomeArray() } = getSomeObject(); -``` - -is rewritten to - -```TypeScript -var _a = getSomeObject(), - x = _a.x, - _b = _a.p, - _c = _b === void 0 ? getSomeArray() : _b, - y = _c[0], - _d = _c[1], - z = _d === void 0 ? 10 : _d; -``` - -### 5.2.3 Implied Type - -A variable, parameter, binding property, or binding element declaration that specifies a binding pattern has an ***implied type*** which is determined as follows: - -* If the declaration specifies an object binding pattern, the implied type is an object type with a set of properties corresponding to the specified binding property declarations. The type of each property is the type implied by its binding property declaration, and a property is optional when its binding property declaration specifies an initializer expression. -* If the declaration specifies an array binding pattern without a rest element, the implied type is a tuple type with elements corresponding to the specified binding element declarations. The type of each element is the type implied by its binding element declaration. -* If the declaration specifies an array binding pattern with a rest element, the implied type is an array type with an element type of Any. - -The implied type of a binding property or binding element declaration is - -* the type of the declaration's initializer expression, if any, or otherwise -* the implied type of the binding pattern specified in the declaration, if any, or otherwise -* the type Any. - -In the example - -```TypeScript -function f({ a, b = "hello", c = 1 }) { ... } -``` - -the implied type of the binding pattern in the function's parameter is '{ a: any; b?: string; c?: number; }'. Since the parameter has no type annotation, this becomes the type of the parameter. - -In the example - -```TypeScript -var [a, b, c] = [1, "hello", true]; -``` - -the array literal initializer expression is contextually typed by the implied type of the binding pattern, specifically the tuple type '[any, any, any]'. Because the contextual type is a tuple type, the resulting type of the array literal is the tuple type '[number, string, boolean]', and the destructuring declaration thus gives the types number, string, and boolean to a, b, and c respectively. - -## 5.3 Let and Const Declarations - -Let and const declarations are exended to include optional type annotations. - -  *LexicalBinding:* *( Modified )* -   *SimpleLexicalBinding* -   *DestructuringLexicalBinding* - -  *SimpleLexicalBinding:* -   *BindingIdentifier* *TypeAnnotationopt* *Initializeropt* - -  *DestructuringLexicalBinding:* -   *BindingPattern* *TypeAnnotationopt* *Initializeropt* - -*TODO: Document scoping and types of [let and const declarations](https://github.com/Microsoft/TypeScript/pull/904)*. - -## 5.4 If, Do, and While Statements - -Expressions controlling 'if', 'do', and 'while' statements can be of any type (and not just type Boolean). - -## 5.5 For Statements - -Variable declarations in 'for' statements are extended in the same manner as variable declarations in variable statements (section [5.2](#5.2)). - -## 5.6 For-In Statements - -In a 'for-in' statement of the form - -```TypeScript -for (v in expr) statement -``` - -*v* 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. - -In a 'for-in' statement of the form - -```TypeScript -for (var v in expr) statement -``` - -*v* 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. - -## 5.7 For-Of Statements - -*TODO: Document [for-of statements](https://github.com/Microsoft/TypeScript/issues/7)*. - -## 5.8 Continue Statements - -A 'continue' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') statement. When a 'continue' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) iteration statement. - -## 5.9 Break Statements - -A 'break' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') or 'switch' statement. When a 'break' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) statement. - -## 5.10 Return Statements - -It is an error for a 'return' statement to occur outside a function body. Specifically, 'return' statements are not permitted at the global level or in namespace bodies. - -A 'return' statement without an expression returns the value 'undefined' and is permitted in the body of any function, regardless of the return type of the function. - -When a 'return' statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section [4.23](#4.23)) by that return type and must be of a type that is assignable to the return type. Otherwise, if the containing function is contextually typed by a type *T*, *Expr* is contextually typed by *T*'s return type. - -In a function implementation without a return type annotation, the return type is inferred from the 'return' statements in the function body, as described in section [6.3](#6.3). - -In the example - -```TypeScript -function f(): (x: string) => number { - return s => s.length; -} -``` - -the arrow expression in the 'return' statement is contextually typed by the return type of 'f', thus giving type 'string' to 's'. - -## 5.11 With Statements - -Use of the 'with' statement in TypeScript is an error, as is the case in ECMAScript 5's strict mode. Furthermore, within the body of a 'with' statement, TypeScript considers every identifier occurring in an expression (section [4.3](#4.3)) to be of the Any type regardless of its declared type. Because the 'with' statement puts a statically unknown set of identifiers in scope in front of those that are statically known, it is not possible to meaningfully assign a static type to any identifier. - -## 5.12 Switch Statements - -In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from (section [3.11.4](#3.11.4)) the type of the 'switch' expression. - -## 5.13 Throw Statements - -The expression specified in a 'throw' statement can be of any type. - -## 5.14 Try Statements - -The variable introduced by a 'catch' clause of a 'try' statement is always of type Any. It is not possible to include a type annotation in a 'catch' clause. - -
- -#
6 Functions - -TypeScript extends JavaScript functions to include type parameters, parameter and return type annotations, overloads, default parameter values, and rest parameters. - -## 6.1 Function Declarations - -Function declarations are extended to permit the function body to be omitted in overload declarations. - -  *FunctionDeclaration:* *( Modified )* -   `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}` -   `function` *BindingIdentifieropt* *CallSignature* `;` - -A *FunctionDeclaration* introduces a named value of a function type in the containing declaration space. The *BindingIdentifier* is optional only when the function declaration occurs in an export default declaration (section [11.3.4.2](#11.3.4.2)). - -Function declarations that specify a body are called ***function implementations*** and function declarations without a body are called ***function overloads***. It is possible to specify multiple overloads for the same function (i.e. for the same name in the same declaration space), but a function can have at most one implementation. All declarations for the same function must specify the same set of modifiers (i.e. the same combination of `declare`, `export`, and `default`). - -When a function has overload declarations, the overloads determine the call signatures of the type given to the function object and the function implementation signature (if any) must be assignable to that type. Otherwise, the function implementation itself determines the call signature. - -When a function has both overloads and an implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements. - -## 6.2 Function Overloads - -Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads it is possible to statically describe the manner in which a function's return type varies based on its arguments. Overload resolution in function calls is described further in section [4.15](#4.15). - -Function overloads are purely a compile-time construct. They have no impact on the emitted JavaScript and thus no run-time cost. - -The parameter list of a function overload cannot specify default values for parameters. In other words, an overload may use only the `?` form when specifying optional parameters. - -The following is an example of a function with overloads. - -```TypeScript -function attr(name: string): string; -function attr(name: string, value: string): Accessor; -function attr(map: any): Accessor; -function attr(nameOrMap: any, value?: string): any { - if (nameOrMap && typeof nameOrMap === "string") { - // handle string case - } - else { - // handle map case - } -} -``` - -Note that each overload and the final implementation specify the same identifier. The type of the local variable 'attr' introduced by this declaration is - -```TypeScript -var attr: { - (name: string): string; - (name: string, value: string): Accessor; - (map: any): Accessor; -}; -``` - -Note that the signature of the actual function implementation is not included in the type. - -## 6.3 Function Implementations - -A function implementation without a return type annotation is said to be an ***implicitly typed function***. The return type of an implicitly typed function *f* is inferred from its function body as follows: - -* If there are no return statements with expressions in *f*'s function body, the inferred return type is Void. -* Otherwise, if *f*'s function body directly references *f* or references any implicitly typed functions that through this same analysis reference *f*, the inferred return type is Any. -* Otherwise, if *f* is a contextually typed function expression (section [4.10](#4.10)), the inferred return type is the union type (section [3.4](#3.4)) of the types of the return statement expressions in the function body, ignoring return statements with no expressions. -* Otherwise, the inferred return type is the first of the types of the return statement expressions in the function body that is a supertype (section [3.11.3](#3.11.3)) of each of the others, ignoring return statements with no expressions. A compile-time error occurs if no return statement expression has a type that is a supertype of each of the others. - -In the example - -```TypeScript -function f(x: number) { - if (x <= 0) return x; - return g(x); -} - -function g(x: number) { - return f(x - 1); -} -``` - -the inferred return type for 'f' and 'g' is Any because the functions reference themselves through a cycle with no return type annotations. Adding an explicit return type 'number' to either breaks the cycle and causes the return type 'number' to be inferred for the other. - -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. - -The type of 'this' in a function implementation is the Any type. - -In the signature of a function implementation, a parameter can be marked optional by following it with an initializer. When a parameter declaration includes both a type annotation and an initializer, the initializer expression is contextually typed (section [4.23](#4.23)) by the stated type and must be assignable to the stated type, or otherwise a compile-time error occurs. When a parameter declaration has no type annotation but includes an initializer, the type of the parameter is the widened form (section [3.12](#3.12)) of the type of the initializer expression. - -Initializer expressions are evaluated in the scope of the function body but are not permitted to reference local variables and are only permitted to access parameters that are declared to the left of the parameter they initialize, unless the parameter reference occurs in a nested function expression. - -When the output target is ECMAScript 3 or 5, for each parameter with an initializer, a statement that substitutes the default value for an omitted argument is included in the generated JavaScript, as described in section [6.6](#6.6). The example - -```TypeScript -function strange(x: number, y = x * 2, z = x + y) { - return z; -} -``` - -generates JavaScript that is equivalent to - -```TypeScript -function strange(x, y, z) { - if (y === void 0) { y = x * 2; } - if (z === void 0) { z = x + y; } - return z; -} -``` - -In the example - -```TypeScript -var x = 1; -function f(a = x) { - var x = "hello"; -} -``` - -the local variable 'x' is in scope in the parameter initializer (thus hiding the outer 'x'), but it is an error to reference it because it will always be uninitialized at the time the parameter initializer is evaluated. - -## 6.4 Destructuring Parameter Declarations - -Parameter declarations can specify binding patterns (section [3.9.2.2](#3.9.2.2)) and are then called ***destructuring parameter declarations***. Similar to a destructuring variable declaration (section [5.2.2](#5.2.2)), a destructuring parameter declaration introduces zero or more named locals and initializes them with values extracted from properties or elements of the object or array passed as an argument for the parameter. - -The type of local introduced in a destructuring parameter declaration is determined in the same manner as a local introduced by a destructuring variable declaration, except the type *T* associated with a destructuring parameter declaration is determined as follows: - -* If the declaration includes a type annotation, *T* is that type. -* If the declaration occurs in a function expression for which a contextual signature is available (section [4.10](#4.10)), *T* is the type obtained from the contextual signature. -* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.12](#3.12)) of the type of the initializer expression. -* Otherwise, if the declaration specifies a binding pattern, *T* is the implied type of that binding pattern (section [5.2.3](#5.2.3)). -* Otherwise, if the parameter is a rest parameter, *T* is `any[]`. -* Otherwise, *T* is `any`. - -When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations. - -The example - -```TypeScript -function drawText({ text = "", location: [x, y] = [0, 0], bold = false }) { - // Draw text -} -``` - -declares a function `drawText` that takes a single parameter of the type - -```TypeScript -{ text?: string; location?: [number, number]; bold?: boolean; } -``` - -When the output target is ECMAScript 3 or 5, the function is rewritten to - -```TypeScript -function drawText(_a) { - var _b = _a.text, - text = _b === void 0 ? "" : _b, - _c = _a.location, - _d = _c === void 0 ? [0, 0] : _c, - x = _d[0], - y = _d[1], - _e = _a.bold, - bold = _e === void 0 ? false : _e; - // Draw text -} -``` - -Destructuring parameter declarations do not permit type annotations on the individual binding patterns, as such annotations would conflict with the already established meaning of colons in object literals. Type annotations must instead be written on the top-level parameter declaration. For example - -```TypeScript -interface DrawTextInfo { - text?: string; - location?: [number, number]; - bold?: boolean; -} - -function drawText({ text, location: [x, y], bold }: DrawTextInfo) { - // Draw text -} -``` - -## 6.5 Generic Functions - -A function implementation may include type parameters in its signature (section [3.9.2.1](#3.9.2.1)) and is then called a ***generic function***. Type parameters provide a mechanism for expressing relationships between parameter and return types in call operations. Type parameters have no run-time representation—they are purely a compile-time construct. - -Type parameters declared in the signature of a function implementation are in scope in the signature and body of that function implementation. - -The following is an example of a generic function: - -```TypeScript -interface Comparable { - localeCompare(other: any): number; -} - -function compare(x: T, y: T): number { - if (x == null) return y == null ? 0 : -1; - if (y == null) return 1; - return x.localeCompare(y); -} -``` - -Note that the 'x' and 'y' parameters are known to be subtypes of the constraint 'Comparable' and therefore have a 'compareTo' member. This is described further in section [3.6.1](#3.6.1). - -The type arguments of a call to a generic function may be explicitly specified in a call operation or may, when possible, be inferred (section [4.15.2](#4.15.2)) from the types of the regular arguments in the call. In the example - -```TypeScript -class Person { - name: string; - localeCompare(other: Person) { - return compare(this.name, other.name); - } -} -``` - -the type argument to 'compare' is automatically inferred to be the String type because the two arguments are strings. - -## 6.6 Code Generation - -A function declaration generates JavaScript code that is equivalent to: - -```TypeScript -function () { - - -} -``` - -*FunctionName* is the name of the function (or nothing in the case of a function expression). - -*FunctionParameters* is a comma separated list of the function's parameter names. - -*DefaultValueAssignments* is a sequence of default property value assignments, one for each parameter with a default value, in the order they are declared, of the form - -```TypeScript -if ( === void 0) { = ; } -``` - -where *Parameter* is the parameter name and *Default* is the default value expression. - -*FunctionStatements* is the code generated for the statements specified in the function body. - -## 6.7 Generator Functions - -*TODO: Document [generator functions](https://github.com/Microsoft/TypeScript/issues/2873)*. - -## 6.8 Asynchronous Functions - -*TODO: Document [asynchronous functions](https://github.com/Microsoft/TypeScript/issues/1664)*. - -## 6.9 Type Guard Functions - -*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007), including [this type predicates](https://github.com/Microsoft/TypeScript/pull/5906)*. - -
- -#
7 Interfaces - -Interfaces provide the ability to name and parameterize object types and to compose existing named object types into new ones. - -Interfaces have no run-time representation—they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions. - -Because TypeScript has a structural type system, an interface type with a particular set of members is considered identical to, and can be substituted for, another interface type or object type literal with an identical set of members (see section [3.11.2](#3.11.2)). - -Class declarations may reference interfaces in their implements clause to validate that they provide an implementation of the interfaces. - -## 7.1 Interface Declarations - -An interface declaration declares an ***interface type***. - -  *InterfaceDeclaration:* -   `interface` *BindingIdentifier* *TypeParametersopt* *InterfaceExtendsClauseopt* *ObjectType* - -  *InterfaceExtendsClause:* -   `extends` *ClassOrInterfaceTypeList* - -  *ClassOrInterfaceTypeList:* -   *ClassOrInterfaceType* -   *ClassOrInterfaceTypeList* `,` *ClassOrInterfaceType* - -  *ClassOrInterfaceType:* -   *TypeReference* - -An *InterfaceDeclaration* introduces a named type (section [3.7](#3.7)) in the containing declaration space. The *BindingIdentifier* of an interface declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). - -An interface may optionally have type parameters (section [3.6.1](#3.6.1)) that serve as placeholders for actual types to be provided when the interface is referenced in type references. An interface with type parameters is called a ***generic interface***. The type parameters of a generic interface declaration are in scope in the entire declaration and may be referenced in the *InterfaceExtendsClause* and *ObjectType* body. - -An interface can inherit from zero or more ***base types*** which are specified in the *InterfaceExtendsClause*. The base types must be type references to class or interface types. - -An interface has the members specified in the *ObjectType* of its declaration and furthermore inherits all base type members that aren't hidden by declarations in the interface: - -* A property declaration hides a public base type property with the same name. -* A string index signature declaration hides a base type string index signature. -* A numeric index signature declaration hides a base type numeric index signature. - -The following constraints must be satisfied by an interface declaration or otherwise a compile-time error occurs: - -* An interface declaration may not, directly or indirectly, specify a base type that originates in the same declaration. In other words an interface cannot, directly or indirectly, be a base type of itself, regardless of type arguments. -* An interface cannot declare a property with the same name as an inherited private or protected property. -* Inherited properties with the same name must be identical (section [3.11.2](#3.11.2)). -* All properties of the interface must satisfy the constraints implied by the index signatures of the interface as specified in section [3.9.4](#3.9.4). -* The this-type (section [3.6.3](#3.6.3)) of the declared interface must be assignable (section [3.11.4](#3.11.4)) to each of the base type references. - -An interface is permitted to inherit identical members from multiple base types and will in that case only contain one occurrence of each particular member. - -Below is an example of two interfaces that contain properties with the same name but different types: - -```TypeScript -interface Mover { - move(): void; - getStatus(): { speed: number; }; -} - -interface Shaker { - shake(): void; - getStatus(): { frequency: number; }; -} -``` - -An interface that extends 'Mover' and 'Shaker' must declare a new 'getStatus' property as it would otherwise inherit two 'getStatus' properties with different types. The new 'getStatus' property must be declared such that the resulting 'MoverShaker' is a subtype of both 'Mover' and 'Shaker': - -```TypeScript -interface MoverShaker extends Mover, Shaker { - getStatus(): { speed: number; frequency: number; }; -} -``` - -Since function and constructor types are just object types containing call and construct signatures, interfaces can be used to declare named function and constructor types. For example: - -```TypeScript -interface StringComparer { (a: string, b: string): number; } -``` - -This declares type 'StringComparer' to be a function type taking two strings and returning a number. - -## 7.2 Declaration Merging - -Interfaces are "open-ended" and interface declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single interface. - -When a generic interface has multiple declarations, all declarations must have identical type parameter lists, i.e. identical type parameter names with identical constraints in identical order. - -In an interface with multiple declarations, the `extends` clauses are merged into a single set of base types and the bodies of the interface declarations are merged into a single object type. Declaration merging produces a declaration order that corresponds to *prepending* the members of each interface declaration, in the order the members are written, to the combined list of members in the order of the interface declarations. Thus, members declared in the last interface declaration will appear first in the declaration order of the merged type. - -For example, a sequence of declarations in this order: - -```TypeScript -interface Document { - createElement(tagName: any): Element; -} - -interface Document { - createElement(tagName: string): HTMLElement; -} - -interface Document { - createElement(tagName: "div"): HTMLDivElement; - createElement(tagName: "span"): HTMLSpanElement; - createElement(tagName: "canvas"): HTMLCanvasElement; -} -``` - -is equivalent to the following single declaration: - -```TypeScript -interface Document { - createElement(tagName: "div"): HTMLDivElement; - createElement(tagName: "span"): HTMLSpanElement; - createElement(tagName: "canvas"): HTMLCanvasElement; - createElement(tagName: string): HTMLElement; - createElement(tagName: any): Element; -} -``` - -Note that the members of the last interface declaration appear first in the merged declaration. Also note that the relative order of members declared in the same interface body is preserved. - -*TODO: Document [class and interface declaration merging](https://github.com/Microsoft/TypeScript/pull/3333)*. - -## 7.3 Interfaces Extending Classes - -When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. When a class containing private or protected members is the base type of an interface type, that interface type can only be implemented by that class or a descendant class. For example: - -```TypeScript -class Control { - private state: any; -} - -interface SelectableControl extends Control { - select(): void; -} - -class Button extends Control { - select() { } -} - -class TextBox extends Control { - select() { } -} - -class Image extends Control { -} - -class Location { - select() { } -} -``` - -In the above example, 'SelectableControl' contains all of the members of 'Control', including the private 'state' property. Since 'state' is a private member it is only possible for descendants of 'Control' to implement 'SelectableControl'. This is because only descendants of 'Control' will have a 'state' private member that originates in the same declaration, which is a requirement for private members to be compatible (section [3.11](#3.11)). - -Within the 'Control' class it is possible to access the 'state' private member through an instance of 'SelectableControl'. Effectively, a 'SelectableControl' acts like a 'Control' that is known to have a 'select' method. The 'Button' and 'TextBox' classes are subtypes of 'SelectableControl' (because they both inherit from 'Control' and have a 'select' method), but the 'Image' and 'Location' classes are not. - -## 7.4 Dynamic Type Checks - -TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface. Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example, given the declarations in section [7.1](#7.1), the following is a dynamic check for the 'MoverShaker' interface: - -```TypeScript -var obj: any = getSomeObject(); -if (obj && obj.move && obj.shake && obj.getStatus) { - var moverShaker = obj; - ... -} -``` - -If such a check is used often it can be abstracted into a function: - -```TypeScript -function asMoverShaker(obj: any): MoverShaker { - return obj && obj.move && obj.shake && obj.getStatus ? obj : null; -} -``` - -
- -#
8 Classes - -TypeScript extends JavaScript classes to include type parameters, implements clauses, accessibility modifiers, member variable declarations, and parameter property declarations in constructors. - -*TODO: Document [abstract classes](https://github.com/Microsoft/TypeScript/issues/3578)*. - -## 8.1 Class Declarations - -A class declaration declares a ***class type*** and a ***constructor function***. - -  *ClassDeclaration:* *( Modified )* -   `class` *BindingIdentifieropt* *TypeParametersopt* *ClassHeritage* `{` *ClassBody* `}` - -A *ClassDeclaration* introduces a named type (the class type) and a named value (the constructor function) in the containing declaration space. The class type is formed from the instance members declared in the class body and the instance members inherited from the base class. The constructor function is given an anonymous type formed from the constructor declaration, the static member declarations in the class body, and the static members inherited from the base class. The constructor function initializes and returns an instance of the class type. - -The *BindingIdentifier* of a class declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). The *BindingIdentifier* is optional only when the class declaration occurs in an export default declaration (section [11.3.4.2](#11.3.4.2)). - -A class may optionally have type parameters (section [3.6.1](#3.6.1)) that serve as placeholders for actual types to be provided when the class is referenced in type references. A class with type parameters is called a ***generic class***. The type parameters of a generic class declaration are in scope in the entire declaration and may be referenced in the *ClassHeritage* and *ClassBody*. - -The following example introduces both a named type called 'Point' (the class type) and a named value called 'Point' (the constructor function) in the containing declaration space. - -```TypeScript -class Point { - constructor(public x: number, public y: number) { } - public length() { return Math.sqrt(this.x * this.x + this.y * this.y); } - static origin = new Point(0, 0); -} -``` - -The named type 'Point' is exactly equivalent to - -```TypeScript -interface Point { - x: number; - y: number; - length(): number; -} -``` - -The named value 'Point' is a constructor function whose type corresponds to the declaration - -```TypeScript -var Point: { - new(x: number, y: number): Point; - origin: Point; -}; -``` - -The context in which a class is referenced distinguishes between the class type and the constructor function. For example, in the assignment statement - -```TypeScript -var p: Point = new Point(10, 20); -``` - -the identifier 'Point' in the type annotation refers to the class type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object. - -### 8.1.1 Class Heritage Specification - -*TODO: Update this section to reflect [expressions in class extends clauses](https://github.com/Microsoft/TypeScript/pull/3516)*. - -The heritage specification of a class consists of optional `extends` and `implements` clauses. The `extends` clause specifies the base class of the class and the `implements` clause specifies a set of interfaces for which to validate the class provides an implementation. - -  *ClassHeritage:* *( Modified )* -   *ClassExtendsClauseopt* *ImplementsClauseopt* - -  *ClassExtendsClause:* -   `extends`  *ClassType* - -  *ClassType:* -   *TypeReference* - -  *ImplementsClause:* -   `implements` *ClassOrInterfaceTypeList* - -A class that includes an `extends` clause is called a ***derived class***, and the class specified in the `extends` clause is called the ***base class*** of the derived class. When a class heritage specification omits the `extends` clause, the class does not have a base class. However, as is the case with every object type, type references (section [3.3.1](#3.3.1)) to the class will appear to have the members of the global interface type named 'Object' unless those members are hidden by members with the same name in the class. - -The following constraints must be satisfied by the class heritage specification or otherwise a compile-time error occurs: - -* If present, the type reference specified in the `extends` clause must denote a class type. Furthermore, the *TypeName* part of the type reference is required to be a reference to the class constructor function when evaluated as an expression. -* A class declaration may not, directly or indirectly, specify a base class that originates in the same declaration. In other words a class cannot, directly or indirectly, be a base class of itself, regardless of type arguments. -* The this-type (section [3.6.3](#3.6.3)) of the declared class must be assignable (section [3.11.4](#3.11.4)) to the base type reference and each of the type references listed in the `implements` clause. -* The constructor function type created by the class declaration must be assignable to the base class constructor function type, ignoring construct signatures. - -The following example illustrates a situation in which the first rule above would be violated: - -```TypeScript -class A { a: number; } - -namespace Foo { - var A = 1; - class B extends A { b: string; } -} -``` - -When evaluated as an expression, the type reference 'A' in the `extends` clause doesn't reference the class constructor function of 'A' (instead it references the local variable 'A'). - -The only situation in which the last two constraints above are violated is when a class overrides one or more base class members with incompatible new members. - -Note that because TypeScript has a structural type system, a class doesn't need to explicitly state that it implements an interface—it suffices for the class to simply contain the appropriate set of instance members. The `implements` clause of a class provides a mechanism to assert and validate that the class contains the appropriate sets of instance members, but otherwise it has no effect on the class type. - -### 8.1.2 Class Body - -The class body consists of zero or more constructor or member declarations. Statements are not allowed in the body of a class—they must be placed in the constructor or in members. - -  *ClassElement:* *( Modified )* -   *ConstructorDeclaration* -   *PropertyMemberDeclaration* -   *IndexMemberDeclaration* - -The body of class may optionally contain a single constructor declaration. Constructor declarations are described in section [8.3](#8.3). - -Member declarations are used to declare instance and static members of the class. Property member declarations are described in section [8.4](#8.4) and index member declarations are described in section [8.5](#8.5). - -## 8.2 Members - -The members of a class consist of the members introduced through member declarations in the class body and the members inherited from the base class. - -### 8.2.1 Instance and Static Members - -Members are either ***instance members*** or ***static members***. - -Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated this-type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of the class. - -Static members are declared using the `static` modifier and are members of the constructor function type (section [8.2.5](#8.2.5)). Within static member functions and static member accessors, the type of `this` is the constructor function type. - -Class type parameters cannot be referenced in static member declarations. - -### 8.2.2 Accessibility - -Property members have either ***public***, ***private***, or ***protected*** accessibility. The default is public accessibility, but property member declarations may include a `public`, `private`, or `protected` modifier to explicitly specify the desired accessibility. - -Public property members can be accessed everywhere without restrictions. - -Private property members can be accessed only within their declaring class. Specifically, a private member *M* declared in a class *C* can be accessed only within the class body of *C*. - -Protected property members can be accessed only within their declaring class and classes derived from their declaring class, and a protected instance property member must be accessed *through* an instance of the enclosing class or a subclass thereof. Specifically, a protected member *M* declared in a class *C* can be accessed only within the class body of *C* or the class body of a class derived from *C*. Furthermore, when a protected instance member *M* is accessed in a property access *E*`.`*M* within the body of a class *D*, the type of *E* is required to be *D* or a type that directly or indirectly has *D* as a base type, regardless of type arguments. - -Private and protected accessibility is enforced only at compile-time and serves as no more than an *indication of intent*. Since JavaScript provides no mechanism to create private and protected properties on an object, it is not possible to enforce the private and protected modifiers in dynamic code at run-time. For example, private and protected accessibility can be defeated by changing an object's static type to Any and accessing the member dynamically. - -The following example demonstrates private and protected accessibility: - -```TypeScript -class A { - private x: number; - protected y: number; - static f(a: A, b: B) { - a.x = 1; // Ok - b.x = 1; // Ok - a.y = 1; // Ok - b.y = 1; // Ok - } -} - -class B extends A { - static f(a: A, b: B) { - a.x = 1; // Error, x only accessible within A - b.x = 1; // Error, x only accessible within A - a.y = 1; // Error, y must be accessed through instance of B - b.y = 1; // Ok - } -} -``` - -In class 'A', the accesses to 'x' are permitted because 'x' is declared in 'A', and the accesses to 'y' are permitted because both take place through an instance of 'A' or a type derived from 'A'. In class 'B', access to 'x' is not permitted, and the first access to 'y' is an error because it takes place through an instance of 'A', which is not derived from the enclosing class 'B'. - -### 8.2.3 Inheritance and Overriding - -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. Only public and protected 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.11.4](#3.11.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. - -Base class static property members can be overridden by derived class static property members of any kind as long as the types are compatible, as described above. - -An index member in a derived class is said to override an index member in a base class when the derived class index member is of the same index kind (string or numeric) as the base class index member. The type of an overriding index member must be assignable (section [3.11.4](#3.11.4)) to the type of the overridden index member, or otherwise a compile-time error occurs. - -### 8.2.4 Class Types - -A class declaration declares a new named type (section [3.7](#3.7)) called a class type. Within the constructor and instance member functions of a class, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of that class type. The class type has the following members: - -* A property for each instance member variable declaration in the class body. -* A property of a function type for each instance member function declaration in the class body. -* A property for each uniquely named instance member accessor declaration in the class body. -* A property for each constructor parameter declared with a `public`, `private`, or `protected` modifier. -* An index signature for each instance index member declaration in the class body. -* All base class instance property or index members that are not overridden in the class. - -All instance property members (including those that are private or protected) of a class must satisfy the constraints implied by the index members of the class as specified in section [3.9.4](#3.9.4). - -In the example - -```TypeScript -class A { - public x: number; - public f() { } - public g(a: any) { return undefined; } - static s: string; -} - -class B extends A { - public y: number; - public g(b: boolean) { return false; } -} -``` - -the class type of 'A' is equivalent to - -```TypeScript -interface A { - x: number; - f: () => void; - g: (a: any) => any; -} -``` - -and the class type of 'B' is equivalent to - -```TypeScript -interface B { - x: number; - y: number; - f: () => void; - g: (b: boolean) => boolean; -} -``` - -Note that static declarations in a class do not contribute to the class type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of 'g' in 'B' overrides the member inherited from 'A'. - -### 8.2.5 Constructor Function Types - -The type of the constructor function introduced by a class declaration is called the constructor function type. The constructor function type has the following members: - -* If the class contains no constructor declaration and has no base class, a single construct signature with no parameters, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. -* If the class contains no constructor declaration and has a base class, a set of construct signatures with the same parameters as those of the base class constructor function type following substitution of type parameters with the type arguments specified in the base class type reference, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. -* If the class contains a constructor declaration with no overloads, a construct signature with the parameter list of the constructor implementation, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. -* If the class contains a constructor declaration with overloads, a set of construct signatures with the parameter lists of the overloads, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. -* A property for each static member variable declaration in the class body. -* A property of a function type for each static member function declaration in the class body. -* A property for each uniquely named static member accessor declaration in the class body. -* A property 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. -* All base class constructor function type properties that are not overridden in the class. - -Every class automatically contains a static property member named 'prototype', the type of which is the containing class with type Any substituted for each type parameter. - -The example - -```TypeScript -class Pair { - constructor(public item1: T1, public item2: T2) { } -} - -class TwoArrays extends Pair { } -``` - -introduces two named types corresponding to - -```TypeScript -interface Pair { - item1: T1; - item2: T2; -} - -interface TwoArrays { - item1: T[]; - item2: T[]; -} -``` - -and two constructor functions corresponding to - -```TypeScript -var Pair: { - new (item1: T1, item2: T2): Pair; -} - -var TwoArrays: { - new (item1: T[], item2: T[]): TwoArrays; -} -``` - -Note that each construct signature in the constructor function types has the same type parameters as its class and returns an instantiation of its class with those type parameters passed as type arguments. Also note that when a derived class doesn't declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type. - -## 8.3 Constructor Declarations - -A constructor declaration declares the constructor function of a class. - -  *ConstructorDeclaration:* -   *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `{` *FunctionBody* `}` -   *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `;` - -Constructor declarations that specify a body are called ***constructor implementations*** and constructor declarations without a body are called ***constructor overloads***. It is possible to specify multiple constructor overloads in a class, but a class can have at most one constructor implementation. All constructor declarations in a class must specify the same set of modifiers. Only public constructors are supported and private or protected constructors result in an error. - -In a class with no constructor declaration, an automatic constructor is provided, as described in section [8.3.3](#8.3.3). - -When a class has constructor overloads, the overloads determine the construct signatures of the type given to the constructor function object, and the constructor implementation signature (if any) must be assignable to that type. Otherwise, the constructor implementation itself determines the construct signature. This exactly parallels the way overloads are processed in a function declaration (section [6.2](#6.2)). - -When a class has both constructor overloads and a constructor implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements. - -The function body of a constructor is permitted to contain return statements. If return statements specify expressions, those expressions must be of types that are assignable to the this-type (section [3.6.3](#3.6.3)) of the class. - -The type parameters of a generic class are in scope and accessible in a constructor declaration. - -### 8.3.1 Constructor Parameters - -Similar to functions, only the constructor implementation (and not constructor overloads) can specify default value expressions for optional parameters. It is a compile-time error for such default value expressions to reference `this`. When the output target is ECMAScript 3 or 5, for each parameter with a default value, a statement that substitutes the default value for an omitted argument is included in the JavaScript generated for the constructor function. - -A parameter of a *ConstructorImplementation* may be prefixed with a `public`, `private`, or `protected` modifier. This is called a ***parameter property declaration*** and is shorthand for declaring a property with the same name as the parameter and initializing it with the value of the parameter. For example, the declaration - -```TypeScript -class Point { - constructor(public x: number, public y: number) { - // Constructor body - } -} -``` - -is equivalent to writing - -```TypeScript -class Point { - public x: number; - public y: number; - constructor(x: number, y: number) { - this.x = x; - this.y = y; - // Constructor body - } -} -``` - -A parameter property declaration may declare an optional parameter (by including a question mark or a default value), but the property introduced by such a declaration is always considered a required property (section [3.3.6](#3.3.6)). - -### 8.3.2 Super Calls - -Super calls (section [4.9.1](#4.9.1)) are used to call the constructor of the base class. A super call consists of the keyword `super` followed by an argument list enclosed in parentheses. For example: - -```TypeScript -class ColoredPoint extends Point { - constructor(x: number, y: number, public color: string) { - super(x, y); - } -} -``` - -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. Super calls are not permitted outside constructors or in local functions inside constructors. - -The first statement in the body of a constructor *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. - -In such a required super call, it is a compile-time error for argument expressions to reference `this`. - -Initialization of parameter properties and instance member variables with initializers takes place immediately at the beginning of the constructor body if the class has no base class, or immediately following the super call if the class is a derived class. - -### 8.3.3 Automatic Constructors - -If a class omits a constructor declaration, an ***automatic constructor*** is provided. - -In a class with no `extends` clause, the automatic constructor has no parameters and performs no action other than executing the instance member variable initializers (section [8.4.1](#8.4.1)), if any. - -In a derived class, the automatic constructor has the same parameter list (and possibly overloads) as the base class constructor. The automatically provided constructor first forwards the call to the base class constructor using a call equivalent to - -```TypeScript -BaseClass.apply(this, arguments); -``` - -and then executes the instance member variable initializers, if any. - -## 8.4 Property Member Declarations - -Property member declarations can be member variable declarations, member function declarations, or member accessor declarations. - -  *PropertyMemberDeclaration:* -   *MemberVariableDeclaration* -   *MemberFunctionDeclaration* -   *MemberAccessorDeclaration* - -Member declarations without a `static` modifier are called instance member declarations. Instance property member declarations declare properties in the class type (section [8.2.4](#8.2.4)), and must specify names that are unique among all instance property member and parameter property declarations in the containing class, with the exception that instance get and set accessor declarations may pairwise specify the same name. - -Member declarations with a `static` modifier are called static member declarations. Static property member declarations declare properties in the constructor function type (section [8.2.5](#8.2.5)), and must specify names that are unique among all static property member declarations in the containing class, with the exception that static get and set accessor declarations may pairwise specify the same name. - -Note that the declaration spaces of instance and static property members are separate. Thus, it is possible to have instance and static property members with the same name. - -Except for overrides, as described in section [8.2.3](#8.2.3), it is an error for a derived class to declare a property member with the same name and kind (instance or static) as a base class member. - -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'. - -Below is an example of a class containing both instance and static property member declarations: - -```TypeScript -class Point { - constructor(public x: number, public y: number) { } - public distance(p: Point) { - var dx = this.x - p.x; - var dy = this.y - p.y; - return Math.sqrt(dx * dx + dy * dy); - } - static origin = new Point(0, 0); - static distance(p1: Point, p2: Point) { return p1.distance(p2); } -} -``` - -The class type 'Point' has the members: - -```TypeScript -interface Point { - x: number; - y: number; - distance(p: Point); -} -``` - -and the constructor function 'Point' has a type corresponding to the declaration: - -```TypeScript -var Point: { - new(x: number, y: number): Point; - origin: Point; - distance(p1: Point, p2: Point): number; -} -``` - -### 8.4.1 Member Variable Declarations - -A member variable declaration declares an instance member variable or a static member variable. - -  *MemberVariableDeclaration:* -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* *Initializeropt* `;` - -The type associated with a member variable declaration is determined in the same manner as an ordinary variable declaration (see section [5.2](#5.2)). - -An instance member variable declaration introduces a member in the class type and optionally initializes a property on instances of the class. Initializers in instance member variable declarations are executed once for every new instance of the class and are equivalent to assignments to properties of `this` in the constructor. In an initializer expression for an instance member variable, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. - -A static member variable declaration introduces a property in the constructor function type and optionally initializes a property on the constructor function object. Initializers in static member variable declarations are executed once when the containing script or module is loaded. - -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. - -Since instance member variable initializers are equivalent to assignments to properties of `this` in the constructor, the example - -```TypeScript -class Employee { - public name: string; - public address: string; - public retired = false; - public manager: Employee = null; - public reports: Employee[] = []; -} -``` - -is equivalent to - -```TypeScript -class Employee { - public name: string; - public address: string; - public retired: boolean; - public manager: Employee; - public reports: Employee[]; - constructor() { - this.retired = false; - this.manager = null; - this.reports = []; - } -} -``` - -### 8.4.2 Member Function Declarations - -A member function declaration declares an instance member function or a static member function. - -  *MemberFunctionDeclaration:* -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `{` *FunctionBody* `}` -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;` - -A member function declaration is processed in the same manner as an ordinary function declaration (section [6](#6)), except that in a member function `this` has a known type. - -All declarations for the same member function must specify the same accessibility (public, private, or protected) and kind (instance or static). - -An instance member function declaration declares a property in the class type and assigns a function object to a property on the prototype object of the class. In the body of an instance member function declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. - -A static member function declaration declares a property in the constructor function type and assigns a function object to a property on the constructor function object. In the body of a static member function declaration, the type of `this` is the constructor function type. - -A member function can access overridden base class members using a super property access (section [4.9.2](#4.9.2)). For example - -```TypeScript -class Point { - constructor(public x: number, public y: number) { } - public toString() { - return "x=" + this.x + " y=" + this.y; - } -} - -class ColoredPoint extends Point { - constructor(x: number, y: number, public color: string) { - super(x, y); - } - public toString() { - return super.toString() + " color=" + this.color; - } -} -``` - -In a static member function, `this` represents the constructor function object on which the static member function was invoked. Thus, a call to 'new this()' may actually invoke a derived class constructor: - -```TypeScript -class A { - a = 1; - static create() { - return new this(); - } -} - -class B extends A { - b = 2; -} - -var x = A.create(); // new A() -var y = B.create(); // new B() -``` - -Note that TypeScript doesn't require or verify that derived constructor functions are subtypes of base constructor functions. In other words, changing the declaration of 'B' to - -```TypeScript -class B extends A { - constructor(public b: number) { - super(); - } -} -``` - -does not cause errors in the example, even though the call to the constructor from the 'create' function doesn't specify an argument (thus giving the value 'undefined' to 'b'). - -### 8.4.3 Member Accessor Declarations - -A member accessor declaration declares an instance member accessor or a static member accessor. - -  *MemberAccessorDeclaration:* -   *AccessibilityModifieropt* `static`*opt* *GetAccessor* -   *AccessibilityModifieropt* `static`*opt* *SetAccessor* - -Get and set accessors are processed in the same manner as in an object literal (section [4.5](#4.5)), except that a contextual type is never available in a member accessor declaration. - -Accessors for the same member name must specify the same accessibility. - -An instance member accessor declaration declares a property in the class type and defines a property on the prototype object of the class with a get or set accessor. In the body of an instance member accessor declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. - -A static member accessor declaration declares a property in the constructor function type and defines a property on the constructor function object of the class with a get or set accessor. In the body of a static member accessor declaration, the type of `this` is the constructor function type. - -Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.7.1](#8.7.1). - -### 8.4.4 Dynamic Property Declarations - -If the *PropertyName* of a property member declaration is a computed property name that doesn't denote a well-known symbol ([2.2.3](#2.2.3)), the construct is considered a ***dynamic property declaration***. The following rules apply to dynamic property declarations: - -* A dynamic property declaration does not introduce a property in the class type or constructor function type. -* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type. -* The name associated with a dynamic property declarations is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type. - -## 8.5 Index Member Declarations - -An index member declaration introduces an index signature (section [3.9.4](#3.9.4)) in the class type. - -  *IndexMemberDeclaration:* -   *IndexSignature* `;` - -Index member declarations have no body and cannot specify an accessibility modifier. - -A class declaration can have at most one string index member declaration and one numeric index member declaration. All instance property members of a class must satisfy the constraints implied by the index members of the class as specified in section [3.9.4](#3.9.4). - -It is not possible to declare index members for the static side of a class. - -Note that it is seldom meaningful to include a string index signature in a class because it constrains all instance properties of the class. However, numeric index signatures can be useful to control the element type when a class is used in an array-like manner. - -## 8.6 Decorators - -*TODO: Document [decorators](https://github.com/Microsoft/TypeScript/issues/2249)*. - -## 8.7 Code Generation - -When the output target is ECMAScript 2015 or higher, type parameters, implements clauses, accessibility modifiers, and member variable declarations are removed in the emitted code, but otherwise class declarations are emitted as written. When the output target is ECMAScript 3 or 5, more comprehensive rewrites are performed, as described in this section. - -### 8.7.1 Classes Without Extends Clauses - -A class with no `extends` clause generates JavaScript equivalent to the following: - -```TypeScript -var = (function () { - function () { - - - - - } - - - return ; -})(); -``` - -*ClassName* is the name of the class. - -*ConstructorParameters* is a comma separated list of the constructor's parameter names. - -*DefaultValueAssignments* is a sequence of default property value assignments corresponding to those generated for a regular function declaration, as described in section [6.6](#6.6). - -*ParameterPropertyAssignments* is a sequence of assignments, one for each parameter property declaration in the constructor, in order they are declared, of the form - -```TypeScript -this. = ; -``` - -where *ParameterName* is the name of a parameter property. - -*MemberVariableAssignments* is a sequence of assignments, one for each instance member variable declaration with an initializer, in the order they are declared, of the form - -```TypeScript -this. = ; -``` - -where *MemberName* is the name of the member variable and *InitializerExpression* is the code generated for the initializer expression. - -*ConstructorStatements* is the code generated for the statements specified in the constructor body. - -*MemberFunctionStatements* is a sequence of statements, one for each member function declaration or member accessor declaration, in the order they are declared. - -An instance member function declaration generates a statement of the form - -```TypeScript -.prototype. = function () { - - -} -``` - -and static member function declaration generates a statement of the form - -```TypeScript -. = function () { - - -} -``` - -where *MemberName* is the name of the member function, and *FunctionParameters*, *DefaultValueAssignments*, and *FunctionStatements* correspond to those generated for a regular function declaration, as described in section [6.6](#6.6). - -A get or set instance member accessor declaration, or a pair of get and set instance member accessor declarations with the same name, generates a statement of the form - -```TypeScript -Object.defineProperty(.prototype, "", { - get: function () { - - }, - set: function () { - - }, - enumerable: true, - configurable: true -}; -``` - -and a get or set static member accessor declaration, or a pair of get and set static member accessor declarations with the same name, generates a statement of the form - -```TypeScript -Object.defineProperty(, "", { - get: function () { - - }, - set: function () { - - }, - enumerable: true, - configurable: true -}; -``` - -where *MemberName* is the name of the member accessor, *GetAccessorStatements* is the code generated for the statements in the get acessor's function body, *ParameterName* is the name of the set accessor parameter, and *SetAccessorStatements* is the code generated for the statements in the set accessor's function body. The 'get' property is included only if a get accessor is declared and the 'set' property is included only if a set accessor is declared. - -*StaticVariableAssignments* is a sequence of statements, one for each static member variable declaration with an initializer, in the order they are declared, of the form - -```TypeScript -. = ; -``` - -where *MemberName* is the name of the static variable, and *InitializerExpression* is the code generated for the initializer expression. - -### 8.7.2 Classes With Extends Clauses - -A class with an `extends` clause generates JavaScript equivalent to the following: - -```TypeScript -var = (function (_super) { - __extends(, _super); - function () { - - - - - - } - - - return ; -})(); -``` - -In addition, the '__extends' function below is emitted at the beginning of the JavaScript source file. It copies all properties from the base constructor function object to the derived constructor function object (in order to inherit static members), and appropriately establishes the 'prototype' property of the derived constructor function object. - -```TypeScript -var __extends = this.__extends || function(d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function f() { this.constructor = d; } - f.prototype = b.prototype; - d.prototype = new f(); -} -``` - -*BaseClassName* is the class name specified in the `extends` clause. - -If the class has no explicitly declared constructor, the *SuperCallStatement* takes the form - -```TypeScript -_super.apply(this, arguments); -``` - -Otherwise the *SuperCallStatement* is present if the constructor function is required to start with a super call, as discussed in section [8.3.2](#8.3.2), and takes the form - -```TypeScript -_super.call(this, ) -``` - -where *SuperCallArguments* is the argument list specified in the super call. Note that this call precedes the code generated for parameter properties and member variables with initializers. Super calls elsewhere in the constructor generate similar code, but the code generated for such calls will be part of the *ConstructorStatements* section. - -A super property access in the constructor, an instance member function, or an instance member accessor generates JavaScript equivalent to - -```TypeScript -_super.prototype. -``` - -where *PropertyName* is the name of the referenced base class property. When the super property access appears in a function call, the generated JavaScript is equivalent to - -```TypeScript -_super.prototype..call(this, ) -``` - -where Arguments is the code generated for the argument list specified in the function call. - -A super property access in a static member function or a static member accessor generates JavaScript equivalent to - -```TypeScript -_super. -``` - -where *PropertyName* is the name of the referenced base class property. When the super property access appears in a function call, the generated JavaScript is equivalent to - -```TypeScript -_super..call(this, ) -``` - -where Arguments is the code generated for the argument list specified in the function call. - -
- -#
9 Enums - -An enum type is a distinct subtype of the Number primitive type with an associated set of named constants that define the possible values of the enum type. - -## 9.1 Enum Declarations - -An enum declaration declares an ***enum type*** and an ***enum object***. - -  *EnumDeclaration:* -   `const`*opt* `enum` *BindingIdentifier* `{` *EnumBodyopt* `}` - -An *EnumDeclaration* introduces a named type (the enum type) and a named value (the enum object) in the containing declaration space. The enum type is a distinct subtype of the Number primitive type. The enum object is a value of an anonymous object type containing a set of properties, all of the enum type, corresponding to the values declared for the enum type in the body of the declaration. The enum object's type furthermore includes a numeric index signature with the signature '[x: number]: string'. - -The *BindingIdentifier* of an enum declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). - -When an enum declaration includes a `const` modifier it is said to be a constant enum declaration. The members of a constant enum declaration must all have constant values that can be computed at compile time. Constant enum declarations are discussed in section [9.4](#9.4). - -The example - -```TypeScript -enum Color { Red, Green, Blue } -``` - -declares a subtype of the Number primitive type called 'Color' and introduces a variable 'Color' with a type that corresponds to the declaration - -```TypeScript -var Color: { - [x: number]: string; - Red: Color; - Green: Color; - Blue: Color; -}; -``` - -The numeric index signature reflects a "reverse mapping" that is automatically generated in every enum object, as described in section [9.5](#9.5). The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example - -```TypeScript -var c = Color.Red; -console.log(Color[c]); // Outputs "Red" -``` - -## 9.2 Enum Members - -The body of an enum declaration defines zero or more enum members which are the named values of the enum type. Each enum member has an associated numeric value of the primitive type introduced by the enum declaration. - -  *EnumBody:* -   *EnumMemberList* `,`*opt* - -  *EnumMemberList:* -   *EnumMember* -   *EnumMemberList* `,` *EnumMember* - -  *EnumMember:* -   *PropertyName* -   *PropertyName* = *EnumValue* - -  *EnumValue:* -   *AssignmentExpression* - -The *PropertyName* of an enum member cannot be a computed property name ([2.2.3](#2.2.3)). - -Enum members are either ***constant members*** or ***computed members***. Constant members have known constant values that are substituted in place of references to the members in the generated JavaScript code. Computed members have values that are computed at run-time and not known at compile-time. No substitution is performed for references to computed members. - -An enum member is classified as follows: - -* 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 the member declaration specifies a value that can be classified as a constant enum expression (as defined below), the member is considered a constant enum member. -* Otherwise, the member is considered a computed enum member. - -Enum value expressions must be of type Any, the Number primitive type, or the enum type itself. - -A ***constant enum expression*** is a subset of the expression grammar that can be evaluated fully at compile time. An expression is considered a constant enum expression if it is one of the following: - -* A numeric literal. -* An identifier or property access that denotes a previously declared member in the same constant enum declaration. -* A parenthesized constant enum expression. -* A +, –, or ~ unary operator applied to a constant enum expression. -* A +, –, *, /, %, <<, >>, >>>, &, ^, or | operator applied to two constant enum expressions. - -In the example - -```TypeScript -enum Test { - A, - B, - C = Math.floor(Math.random() * 1000), - D = 10, - E -} -``` - -'A', 'B', 'D', and 'E' are constant members with values 0, 1, 10, and 11 respectively, and 'C' is a computed member. - -In the example - -```TypeScript -enum Style { - None = 0, - Bold = 1, - Italic = 2, - Underline = 4, - Emphasis = Bold | Italic, - Hyperlink = Bold | Underline -} -``` - -all members are constant members. Note that enum member declarations can reference other enum members without qualification. Also, because enums are subtypes of the Number primitive type, numeric operators, such as the bitwise OR operator, can be used to compute enum values. - -## 9.3 Declaration Merging - -Enums are "open-ended" and enum declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) define a single enum type and contribute to a single enum object. - -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. - -When enum declarations are merged, they must either all specify a `const` modifier or all specify no `const` modifier. - -## 9.4 Constant Enum Declarations - -An enum declaration that specifies a `const` modifier is a ***constant enum declaration***. In a constant enum declaration, all members must have constant values and it is an error for a member declaration to specify an expression that isn't classified as a constant enum expression. - -Unlike regular enum declarations, constant enum declarations are completely erased in the emitted JavaScript code. For this reason, it is an error to reference a constant enum object in any other context than a property access that selects one of the enum's members. For example: - -```TypeScript -const enum Comparison { - LessThan = -1, - EqualTo = 0, - GreaterThan = 1 -} - -var x = Comparison.EqualTo; // Ok, replaced with 0 in emitted code -var y = Comparison[Comparison.EqualTo]; // Error -var z = Comparison; // Error -``` - -The entire const enum declaration is erased in the emitted JavaScript code. Thus, the only permitted references to the enum object are those that are replaced with an enum member value. - -## 9.5 Code Generation - -An enum declaration generates JavaScript equivalent to the following: - -```TypeScript -var ; -(function () { - -})(||(={})); -``` - -*EnumName* is the name of the enum. - -*EnumMemberAssignments* is a sequence of assignments, one for each enum member, in order they are declared, of the form - -```TypeScript -[[""] = ] = ""; -``` - -where *MemberName* is the name of the enum member and *Value* is the assigned constant value or the code generated for the computed value expression. - -For example, the 'Color' enum example from section [9.1](#9.1) generates the following JavaScript: - -```TypeScript -var Color; -(function (Color) { - Color[Color["Red"] = 0] = "Red"; - Color[Color["Green"] = 1] = "Green"; - Color[Color["Blue"] = 2] = "Blue"; -})(Color||(Color={})); -``` - -
- -#
10 Namespaces - -Namespaces provide a mechanism for organizing code and declarations in hierarchies of named containers. Namespaces have named members that each denote a value, a type, or a namespace, or some combination thereof, and those members may be local or exported. The body of a namespace corresponds to a function that is executed once, thereby providing a mechanism for maintaining local state with assured isolation. Namespaces can be thought of as a formalization of the [immediately-invoked function expression](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) (IIFE) pattern. - -## 10.1 Namespace Declarations - -A namespace declaration introduces a name with a namespace meaning and, in the case of an instantiated namespace, a value meaning in the containing declaration space. - -  *NamespaceDeclaration:* -   `namespace` *IdentifierPath* `{` *NamespaceBody* `}` - -  *IdentifierPath:* -   *BindingIdentifier* -   *IdentifierPath* `.` *BindingIdentifier* - -Namespaces are declared using the `namespace` keyword, but for backward compatibility of earlier versions of TypeScript a `module` keyword can also be used. - -Namespaces are either ***instantiated*** or ***non-instantiated***. A non-instantiated namespace is a namespace containing only interface types, type aliases, and other non-instantiated namespace. An instantiated namespace is a namespace that doesn't meet this definition. In intuitive terms, an instantiated namespace is one for which a namespace instance is created, whereas a non-instantiated namespace is one for which no code is generated. - -When a namespace identifier is referenced as a *NamespaceName* (section [3.8.2](#3.8.2)) it denotes a container of namespace and type names, and when a namespace identifier is referenced as a *PrimaryExpression* (section [4.3](#4.3)) it denotes the singleton namespace instance. For example: - -```TypeScript -namespace M { - export interface P { x: number; y: number; } - export var a = 1; -} - -var p: M.P; // M used as NamespaceName -var m = M; // M used as PrimaryExpression -var x1 = M.a; // M used as PrimaryExpression -var x2 = m.a; // Same as M.a -var q: m.P; // Error -``` - -Above, when 'M' is used as a *PrimaryExpression* it denotes an object instance with a single member 'a' and when 'M' is used as a *NamespaceName* it denotes a container with a single type member 'P'. The final line in the example is an error because 'm' is a variable which cannot be referenced in a type name. - -If the declaration of 'M' above had excluded the exported variable 'a', 'M' would be a non-instantiated namespace and it would be an error to reference 'M' as a *PrimaryExpression*. - -A namespace declaration that specifies an *IdentifierPath* with more than one identifier is equivalent to a series of nested single-identifier namespace declarations where all but the outermost are automatically exported. For example: - -```TypeScript -namespace A.B.C { - export var x = 1; -} -``` - -corresponds to - -```TypeScript -namespace A { - export namespace B { - export namespace C { - export var x = 1; - } - } -} -``` - -The hierarchy formed by namespace and named type names partially mirrors that formed by namespace instances and members. The example - -```TypeScript -namespace A { - export namespace B { - export class C { } - } -} -``` - -introduces a named type with the qualified name 'A.B.C' and also introduces a constructor function that can be accessed using the expression 'A.B.C'. Thus, in the example - -```TypeScript -var c: A.B.C = new A.B.C(); -``` - -the two occurrences of 'A.B.C' in fact refer to different entities. It is the context of the occurrences that determines whether 'A.B.C' is processed as a type name or an expression. - -## 10.2 Namespace Body - -The body of a namespace corresponds to a function that is executed once to initialize the namespace instance. - -  *NamespaceBody:* -   *NamespaceElementsopt* - -  *NamespaceElements:* -   *NamespaceElement* -   *NamespaceElements* *NamespaceElement* - -  *NamespaceElement:* -   *Statement* -   *LexicalDeclaration* -   *FunctionDeclaration* -   *GeneratorDeclaration* -   *ClassDeclaration* -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *EnumDeclaration* -   *NamespaceDeclaration -   AmbientDeclaration -   ImportAliasDeclaration -   ExportNamespaceElement* - -  *ExportNamespaceElement:* -   `export` *VariableStatement* -   `export` *LexicalDeclaration* -   `export` *FunctionDeclaration* -   `export` *GeneratorDeclaration* -   `export` *ClassDeclaration* -   `export` *InterfaceDeclaration* -   `export` *TypeAliasDeclaration* -   `export` *EnumDeclaration* -   `export` *NamespaceDeclaration* -   `export` *AmbientDeclaration* -   `export` *ImportAliasDeclaration* - -## 10.3 Import Alias Declarations - -Import alias declarations are used to create local aliases for entities in other namespaces. - -  *ImportAliasDeclaration:* -   `import` *BindingIdentifier* `=` *EntityName* `;` - -  *EntityName:* -   *NamespaceName* -   *NamespaceName* `.` *IdentifierReference* - -An *EntityName* consisting of a single identifier is resolved as a *NamespaceName* and is thus required to reference a namespace. The resulting local alias references the given namespace and is itself classified as a namespace. - -An *EntityName* consisting of more than one identifier is resolved as a *NamespaceName* followed by an identifier that names an exported entity in the given namespace. The resulting local alias has all the meanings of the referenced entity. (As many as three distinct meanings are possible for an entity name—value, type, and namespace.) In effect, it is as if the imported entity was declared locally with the local alias name. - -In the example - -```TypeScript -namespace A { - export interface X { s: string } - export var X: X; -} - -namespace B { - interface A { n: number } - import Y = A; // Alias for namespace A - import Z = A.X; // Alias for type and value A.X - var v: Z = Z; -} -``` - -within 'B', 'Y' is an alias only for namespace 'A' and not the local interface 'A', whereas 'Z' is an alias for all exported meanings of 'A.X', thus denoting both an interface type and a variable. - -If the *NamespaceName* portion of an *EntityName* references an instantiated namespace, the *NamespaceName* is required to reference the namespace instance when evaluated as an expression. In the example - -```TypeScript -namespace A { - export interface X { s: string } -} - -namespace B { - var A = 1; - import Y = A; -} -``` - -'Y' is a local alias for the non-instantiated namespace 'A'. If the declaration of 'A' is changed such that 'A' becomes an instantiated namespace, for example by including a variable declaration in 'A', the import statement in 'B' above would be an error because the expression 'A' doesn't reference the namespace instance of namespace 'A'. - -When an import statement includes an export modifier, all meanings of the local alias are exported. - -## 10.4 Export Declarations - -An export declaration declares an externally accessible namespace member. An export declaration is simply a regular declaration prefixed with the keyword `export`. - -The members of a namespace's export declaration space (section [2.3](#2.3)) constitute the namespace's ***export member set***. A namespace's ***instance type*** is an object type with a property for each member in the namespace's export member set that denotes a value. - -An exported member depends on a (possibly empty) set of named types (section [3.7](#3.7)). Those named types must be at least as accessible as the exported member, or otherwise an error occurs. - -The named types upon which a member depends are the named types occurring in the transitive closure of the ***directly depends on*** relationship defined as follows: - -* A variable directly depends on the *Type* specified in its type annotation. -* A function directly depends on each *Type* specified in a parameter or return type annotation. -* A class directly depends on each *Type* specified as a type parameter constraint, each *TypeReference* specified as a base class or implemented interface, and each *Type* specified in a constructor parameter type annotation, public member variable type annotation, public member function parameter or return type annotation, public member accessor parameter or return type annotation, or index signature type annotation. -* An interface directly depends on each *Type* specified as a type parameter constraint, each *TypeReference* specified as a base interface, and the *ObjectType* specified as its body. -* A namespace directly depends on its exported members. -* A *Type* or *ObjectType* directly depends on every *TypeReference* that occurs within the type at any level of nesting. -* A *TypeReference* directly depends on the type it references and on each *Type* specified as a type argument. - -A named type *T* having a root namespace *R* (section [2.3](#2.3)) is said to be ***at least as accessible as*** a member *M* if - -* *R* is the global namespace or a module, or -* *R* is a namespace in the parent namespace chain of *M*. - -In the example - -```TypeScript -interface A { x: string; } - -namespace M { - export interface B { x: A; } - export interface C { x: B; } - export function foo(c: C) { … } -} -``` - -the 'foo' function depends upon the named types 'A', 'B', and 'C'. In order to export 'foo' it is necessary to also export 'B' and 'C' as they otherwise would not be at least as accessible as 'foo'. The 'A' interface is already at least as accessible as 'foo' because I t is declared in a parent namespace of foo's namespace. - -## 10.5 Declaration Merging - -Namespaces are "open-ended" and namespace declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single namespace. For example, the following two declarations of a namespace 'outer' might be located in separate source files. - -File a.ts: - -```TypeScript -namespace outer { - var local = 1; // Non-exported local variable - export var a = local; // outer.a - export namespace inner { - export var x = 10; // outer.inner.x - } -} -``` - -File b.ts: - -```TypeScript -namespace outer { - var local = 2; // Non-exported local variable - export var b = local; // outer.b - export namespace inner { - export var y = 20; // outer.inner.y - } -} -``` - -Assuming the two source files are part of the same program, the two declarations will have the global namespace as their common root and will therefore contribute to the same namespace instance, the instance type of which will be: - -```TypeScript -{ - a: number; - b: number; - inner: { - x: number; - y: number; - }; -} -``` - -Declaration merging does not apply to local aliases created by import alias declarations. In other words, it is not possible have an import alias declaration and a namespace declaration for the same name within the same namespace body. - -*TODO: Clarify rules for [alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*. - -Declaration merging also extends to namespace declarations with the same qualified name relative to a common root as a function, class, or enum declaration: - -* When merging a function and a namespace, the type of the function object is merged with the instance type of the namespace. In effect, the overloads or implementation of the function provide the call signatures and the exported members of the namespace provide the properties of the combined type. -* When merging a class and a namespace, the type of the constructor function object is merged with the instance type of the namespace. In effect, the overloads or implementation of the class constructor provide the construct signatures, and the static members of the class and exported members of the namespace provide the properties of the combined type. It is an error to have static class members and exported namespace members with the same name. -* When merging an enum and a namespace, the type of the enum object is merged with the instance type of the namespace. In effect, the members of the enum and the exported members of the namespace provide the properties of the combined type. It is an error to have enum members and exported namespace members with the same name. - -When merging a non-ambient function or class declaration and a non-ambient namespace declaration, the function or class declaration must be located prior to the namespace declaration in the same source file. This ensures that the shared object instance is created as a function object. (While it is possible to add properties to an object after its creation, it is not possible to make an object "callable" after the fact.) - -The example - -```TypeScript -interface Point { - x: number; - y: number; -} - -function point(x: number, y: number): Point { - return { x: x, y: y }; -} - -namespace point { - export var origin = point(0, 0); - export function equals(p1: Point, p2: Point) { - return p1.x == p2.x && p1.y == p2.y; - } -} - -var p1 = point(0, 0); -var p2 = point.origin; -var b = point.equals(p1, p2); -``` - -declares 'point' as a function object with two properties, 'origin' and 'equals'. Note that the namespace declaration for 'point' is located after the function declaration. - -## 10.6 Code Generation - -A namespace generates JavaScript code that is equivalent to the following: - -```TypeScript -var ; -(function() { - -})(||(={})); -``` - -where *NamespaceName* is the name of the namespace and *NamespaceStatements* is the code generated for the statements in the namespace body. The *NamespaceName* function parameter may be prefixed with one or more underscore characters to ensure the name is unique within the function body. Note that the entire namespace is emitted as an anonymous function that is immediately executed. This ensures that local variables are in their own lexical environment isolated from the surrounding context. Also note that the generated function doesn't create and return a namespace instance, but rather it extends the existing instance (which may have just been created in the function call). This ensures that namespaces can extend each other. - -An import statement generates code of the form - -```TypeScript -var = ; -``` - -This code is emitted only if the imported entity is referenced as a *PrimaryExpression* somewhere in the body of the importing namespace. If an imported entity is referenced only as a *TypeName* or *NamespaceName*, nothing is emitted. This ensures that types declared in one namespace can be referenced through an import alias in another namespace with no run-time overhead. - -When a variable is exported, all references to the variable in the body of the namespace are replaced with - -```TypeScript -. -``` - -This effectively promotes the variable to be a property on the namespace instance and ensures that all references to the variable become references to the property. - -When a function, class, enum, or namespace is exported, the code generated for the entity is followed by an assignment statement of the form - -```TypeScript -. = ; -``` - -This copies a reference to the entity into a property on the namespace instance. - -
- -#
11 Scripts and Modules - -TypeScript implements support for ECMAScript 2015 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems. - -## 11.1 Programs and Source Files - -A TypeScript ***program*** consists of one or more source files. - -  *SourceFile:* -   *ImplementationSourceFile* -   *DeclarationSourceFile* - -  *ImplementationSourceFile:* -   *ImplementationScript* -   *ImplementationModule* - -  *DeclarationSourceFile:* -   *DeclarationScript* -   *DeclarationModule* - -Source files with extension '.ts' are ***implementation source files*** containing statements and declarations, and source files with extension '.d.ts' are ***declaration source files*** containing declarations only. - -Declaration source files are a strict subset of implementation source files and are used to declare the static type information associated with existing JavaScript code in an adjunct manner. They are entirely optional but enable the TypeScript compiler and tools to provide better verification and assistance when integrating existing JavaScript code and libraries in a TypeScript application. - -When a TypeScript program is compiled, all of the program's source files are processed together. Statements and declarations in different source files can depend on each other, possibly in a circular fashion. By default, a JavaScript output file is generated for each implementation source file in a compilation, but no output is generated from declaration source files. - -### 11.1.1 Source Files Dependencies - -The TypeScript compiler automatically determines a source file's dependencies and includes those dependencies in the program being compiled. The determination is made from "reference comments" and module import declarations as follows: - -* A comment of the form /// <reference path="…"/> that occurs before the first token in a source file adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file. -* A module import declaration that specifies a relative module name (section [11.3.1](#11.3.1)) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension '.ts' exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension '.d.ts' exists, that file is added as a dependency. -* A module import declaration that specifies a top-level module name (section [11.3.1](#11.3.1)) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension '.ts' or '.d.ts' corresponding to the reference is located, that file is added as a dependency. - -Any files included as dependencies in turn have their references analyzed in a transitive manner until all dependencies have been determined. - -## 11.2 Scripts - -Source files that contain no module import or export declarations are classified as ***scripts***. Scripts form the single ***global namespace*** and entities declared in scripts are in scope everywhere in a program. - -  *ImplementationScript:* -   *ImplementationScriptElementsopt* - -  *ImplementationScriptElements:* -   *ImplementationScriptElement* -   *ImplementationScriptElements* *ImplementationScriptElement* - -  *ImplementationScriptElement:* -   *ImplementationElement* -   *AmbientModuleDeclaration* - -  *ImplementationElement:* -   *Statement* -   *LexicalDeclaration* -   *FunctionDeclaration* -   *GeneratorDeclaration* -   *ClassDeclaration* -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *EnumDeclaration* -   *NamespaceDeclaration* -   *AmbientDeclaration* -   *ImportAliasDeclaration* - -  *DeclarationScript:* -   *DeclarationScriptElementsopt* - -  *DeclarationScriptElements:* -   *DeclarationScriptElement* -   *DeclarationScriptElements* *DeclarationScriptElement* - -  *DeclarationScriptElement:* -   *DeclarationElement* -   *AmbientModuleDeclaration* - -  *DeclarationElement:* -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *NamespaceDeclaration* -   *AmbientDeclaration* -   *ImportAliasDeclaration* - -The initialization order of the scripts that make up the global namespace ultimately depends on the order in which the generated JavaScript files are loaded at run-time (which, for example, may be controlled by <script/> tags that reference the generated JavaScript files). - -## 11.3 Modules - -Source files that contain at least one module import or export declaration are considered separate ***modules***. Non-exported entities declared in a module are in scope only in that module, but exported entities can be imported into other modules using import declarations. - -  *ImplementationModule:* -   *ImplementationModuleElementsopt* - -  *ImplementationModuleElements:* -   *ImplementationModuleElement* -   *ImplementationModuleElements* *ImplementationModuleElement* - -  *ImplementationModuleElement:* -   *ImplementationElement* -   *ImportDeclaration* -   *ImportAliasDeclaration* -   *ImportRequireDeclaration* -   *ExportImplementationElement* -   *ExportDefaultImplementationElement* -   *ExportListDeclaration* -   *ExportAssignment* - -  *DeclarationModule:* -   *DeclarationModuleElementsopt* - -  *DeclarationModuleElements:* -   *DeclarationModuleElement* -   *DeclarationModuleElements* *DeclarationModuleElement* - -  *DeclarationModuleElement:* -   *DeclarationElement* -   *ImportDeclaration* -   *ImportAliasDeclaration* -   *ExportDeclarationElement* -   *ExportDefaultDeclarationElement* -   *ExportListDeclaration* -   *ExportAssignment* - -Initialization order of modules is determined by the module loader being used and is not specified by the TypeScript language. However, it is generally the case that non-circularly dependent modules are automatically loaded and initialized in the correct order. - -Modules can additionally be declared using *AmbientModuleDeclarations* in declaration scripts that directly specify the module names as string literals. This is described further in section [12.2](#12.2). - -Below is an example of two modules written in separate source files: - -```TypeScript -// -------- main.ts -------- -import { message } from "./log"; -message("hello"); - -// -------- log.ts -------- -export function message(s: string) { - console.log(s); -} -``` - -The import declaration in the 'main' module references the 'log' module and compiling the 'main.ts' file causes the 'log.ts' file to also be compiled as part of the program. - -TypeScript supports multiple patterns of JavaScript code generation for modules: - -* CommonJS. This format is used by server frameworks such as node.js. -* AMD (Asynchronous Module Definition). This format is used by asynchronous module loaders such as RequireJS. -* UMD (Universal Module Definition). A variation of the AMD format that allows modules to also be loaded by CommonJS loaders. -* System. This format is used to represent ECMAScript 2015 semantics with high fidelity in down-level environments. - -The desired module code generation pattern is selected through a compiler option and does not affect the TypeScript source code. Indeed, it is possible to author modules that can be compiled for use both on the server side (e.g. using node.js) and on the client side (using an AMD compliant loader) with no changes to the TypeScript source code. - -### 11.3.1 Module Names - -Modules are identified and referenced using module names. The following definition is aligned with that provided in the [CommonJS Modules](http://www.commonjs.org/specs/modules/1.0/) 1.0 specification. - -* A module name is a string of terms delimited by forward slashes. -* Module names may not have file-name extensions like ".js". -* Module names may be relative or top-level. A module name is relative if the first term is "." or "..". -* Top-level names are resolved off the conceptual module name space root. -* Relative names are resolved relative to the name of the module in which they occur. - -For purposes of resolving module references, TypeScript associates a file path with every module. The file path is simply the path of the module's source file without the file extension. For example, a module contained in the source file 'C:\src\lib\io.ts' has the file path 'C:/src/lib/io' and a module contained in the source file 'C:\src\ui\editor.d.ts' has the file path 'C:/src/ui/editor'. - -A module name in an import declaration is resolved as follows: - -* If the import declaration specifies a relative module name, the name is resolved relative to the directory of the referencing module's file path. The program must contain a module with the resulting file path or otherwise an error occurs. For example, in a module with the file path 'C:/src/ui/main', the module names './editor' and '../lib/io' reference modules with the file paths 'C:/src/ui/editor' and 'C:/src/lib/io'. -* If the import declaration specifies a top-level module name and the program contains an *AmbientModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, then the import declaration references that ambient module. -* If the import declaration specifies a top-level module name and the program contains no *AmbientModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, the name is resolved in a host dependent manner (for example by considering the name relative to a module name space root). If a matching module cannot be found an error occurs. - -### 11.3.2 Import Declarations - -Import declarations are used to import entities from other modules and provide bindings for them in the current module. - -An import declaration of the form - -```TypeScript -import * as m from "mod"; -``` - -imports the module with the given name and creates a local binding for the module itself. The local binding is classified as a value (representing the module instance) and a namespace (representing a container of types and namespaces). - -An import declaration of the form - -```TypeScript -import { x, y, z } from "mod"; -``` - -imports a given module and creates local bindings for a specified list of exported members of the module. The specified names must each reference an entity in the export member set ([11.3.4.4](#11.3.4.4)) of the given module. The local bindings have the same names and classifications as the entities they represent unless `as` clauses are used to that specify different local names: - -```TypeScript -import { x as a, y as b } from "mod"; -``` - -An import declaration of the form - -```TypeScript -import d from "mod"; -``` - -is exactly equivalent to the import declaration - -```TypeScript -import { default as d } from "mod"; -``` - -An import declaration of the form - -```TypeScript -import "mod"; -``` - -imports the given module without creating any local bindings (this is useful only if the imported module has side effects). - -### 11.3.3 Import Require Declarations - -Import require declarations exist for backward compatibility with earlier versions of TypeScript. - -  *ImportRequireDeclaration:* -   `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;` - -An import require declaration introduces a local identifier that references a given module. The string literal specified in an import require declaration is interpreted as a module name (section [11.3.1](#11.3.1)). The local identifier introduced by the declaration becomes an alias for, and is classified exactly like, the entity exported from the referenced module. Specifically, if the referenced module contains no export assignment the identifier is classified as a value and a namespace, and if the referenced module contains an export assignment the identifier is classified exactly like the entity named in the export assignment. - -An import require declaration of the form - -```TypeScript -import m = require("mod"); -``` - -is equivalent to the ECMAScript 2015 import declaration - -```TypeScript -import * as m from "mod"; -``` - -provided the referenced module contains no export assignment. - -### 11.3.4 Export Declarations - -An export declaration declares one or more exported module members. The exported members of a module can be imported in other modules using import declarations ([11.3.2](#11.3.2)). - -#### 11.3.4.1 Export Modifiers - -In the body of a module, a declaration can export the declared entity by including an `export` modifier. - -  *ExportImplementationElement:* -   `export` *VariableStatement* -   `export` *LexicalDeclaration* -   `export` *FunctionDeclaration* -   `export` *GeneratorDeclaration* -   `export` *ClassDeclaration* -   `export` *InterfaceDeclaration* -   `export` *TypeAliasDeclaration* -   `export` *EnumDeclaration* -   `export` *NamespaceDeclaration* -   `export` *AmbientDeclaration* -   `export` *ImportAliasDeclaration* - -  *ExportDeclarationElement:* -   `export` *InterfaceDeclaration* -   `export` *TypeAliasDeclaration* -   `export` *AmbientDeclaration* -   `export` *ImportAliasDeclaration* - -In addition to introducing a name in the local declaration space of the module, an exported declaration introduces the same name with the same classification in the module's export declaration space. For example, the declaration - -```TypeScript -export function point(x: number, y: number) { - return { x, y }; -} -``` - -introduces a local name `point` and an exported name `point` that both reference the function. - -#### 11.3.4.2 Export Default Declarations - -Export default declarations provide short-hand syntax for exporting an entity named `default`. - -  *ExportDefaultImplementationElement:* -   `export` `default` *FunctionDeclaration* -   `export` `default` *GeneratorDeclaration* -   `export` `default` *ClassDeclaration* -   `export` `default` *AssignmentExpression* `;` - -  *ExportDefaultDeclarationElement:* -   `export` `default` *AmbientFunctionDeclaration* -   `export` `default` *AmbientClassDeclaration* -   `export` `default` *IdentifierReference* `;` - -An *ExportDefaultImplementationElement* or *ExportDefaultDeclarationElement* for a function, generator, or class introduces a value named `default`, and in the case of a class, a type named `default`, in the containing module's export declaration space. The declaration may optionally specify a local name for the exported function, generator, or class. For example, the declaration - -```TypeScript -export default function point(x: number, y: number) { - return { x, y }; -} -``` - -introduces a local name `point` and an exported name `default` that both reference the function. The declaration is effectively equivalent to - -```TypeScript -function point(x: number, y: number) { - return { x, y }; -} - -export default point; -``` - -which again is equivalent to - -```TypeScript -function point(x: number, y: number) { - return { x, y }; -} - -export { point as default }; -``` - -An *ExportDefaultImplementationElement* or *ExportDefaultDeclarationElement* for an expression consisting of a single identifier must name an entity declared in the current module or the global namespace. The declaration introduces an entity named `default`, with the same classification as the referenced entity, in the containing module's export declaration space. For example, the declarations - -```TypeScript -interface Point { - x: number; - y: number; -} - -function Point(x: number, y: number): Point { - return { x, y }; -} - -export default Point; -``` - -introduce a local name `Point` and an exported name `default`, both with a value and a type meaning. - -An *ExportDefaultImplementationElement* for any expression but a single identifier introduces a value named `default` in the containing module's export declaration space. For example, the declaration - -```TypeScript -export default "hello"; -``` - -introduces an exported value named `default` of type string. - -#### 11.3.4.3 Export List Declarations - -An export list declaration exports one or more entities from the current module or a specified module. - -  *ExportListDeclaration:* -   `export` `*` *FromClause* `;` -   `export` *ExportClause* *FromClause* `;` -   `export` *ExportClause* `;` - -An *ExportListDeclaration* without a *FromClause* exports entities from the current module. In a declaration of the form - -```TypeScript -export { x }; -``` - -the name `x` must reference an entity declared in the current module or the global namespace, and the declaration introduces an entity with the same name and meaning in the containing module's export declaration space. - -An *ExportListDeclaration* with a *FromClause* re-exports entities from a specified module. In a declaration of the form - -```TypeScript -export { x } from "mod"; -``` - -the name `x` must reference an entity in the export member set of the specified module, and the declaration introduces an entity with the same name and meaning in the containing module's export declaration space. No local bindings are created for `x`. - -The *ExportClause* of an *ExportListDeclaration* can specify multiple entities and may optionally specify different names to be used for the exported entities. For example, the declaration - -```TypeScript -export { x, y as b, z as c }; -``` - -introduces entities named `x`, `b`, and `c` in the containing module's export declaration space with the same meaning as the local entities named `x`, `y`, and `z` respectively. - -An *ExportListDeclaration* that specifies `*` instead of an *ExportClause* is called an ***export star*** declaration. An export star declaration re-exports all members of a specified module. - -```TypeScript -export * from "mod"; -``` - -Explicitly exported members take precedence over members re-exported using export star declarations, as described in the following section. - -#### 11.3.4.4 Export Member Set - -The ***export member set*** of a particular module is determined by starting with an empty set of members *E* and an empty set of processed modules *P*, and then processing the module as described below to form the full set of exported members in *E*. Processing a module *M* consists of these steps: - -* Add *M* to *P*. -* Add to *E* each member in the export declaration space of *M* with a name that isn't already in *E*. -* For each export star declaration in *M*, in order of declaration, process the referenced module if it is not already in *P*. - -A module's ***instance type*** is an object type with a property for each member in the module's export member set that denotes a value. - -If a module contains an export assignment it is an error for the module to also contain export declarations. The two types of exports are mutually exclusive. - -### 11.3.5 Export Assignments - -Export assignments exist for backward compatibility with earlier versions of TypeScript. An export assignment designates a module member as the entity to be exported in place of the module itself. - -  *ExportAssignment:* -   `export` `=` *IdentifierReference* `;` - -A module containing an export assignment can be imported using an import require declaration ([11.3.3](#11.3.3)), and the local alias introduced by the import require declaration then takes on all meanings of the identifier named in the export assignment. - -A module containing an export assignment can also be imported using a regular import declaration ([11.3.2](#11.3.2)) provided the entity referenced in the export assignment is declared as a namespace or as a variable with a type annotation. - -Assume the following example resides in the file 'point.ts': - -```TypeScript -export = Point; - -class Point { - constructor(public x: number, public y: number) { } - static origin = new Point(0, 0); -} -``` - -When 'point.ts' is imported in another module, the import alias references the exported class and can be used both as a type and as a constructor function: - -```TypeScript -import Pt = require("./point"); - -var p1 = new Pt(10, 20); -var p2 = Pt.origin; -``` - -Note that there is no requirement that the import alias use the same name as the exported entity. - -### 11.3.6 CommonJS Modules - -The [CommonJS Modules](http://www.commonjs.org/specs/modules/1.0/) definition specifies a methodology for writing JavaScript modules with implied privacy, the ability to import other modules, and the ability to explicitly export members. A CommonJS compliant system provides a 'require' function that can be used to synchronously load other modules to obtain their singleton module instance, as well as an 'exports' variable to which a module can add properties to define its external API. - -The 'main' and 'log' example from section [11.3](#11.3) above generates the following JavaScript code when compiled for the CommonJS Modules pattern: - -File main.js: - -```TypeScript -var log_1 = require("./log"); -log_1.message("hello"); -``` - -File log.js: - -```TypeScript -function message(s) { - console.log(s); -} -exports.message = message; -``` - -A module import declaration is represented in the generated JavaScript as a variable initialized by a call to the 'require' function provided by the module system host. A variable declaration and 'require' call is emitted for a particular imported module only if the imported module, or a local alias (section [10.3](#10.3)) that references the imported module, is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *NamespaceName* or *TypeQueryExpression*, nothing is emitted. - -An example: - -File geometry.ts: - -```TypeScript -export interface Point { x: number; y: number }; - -export function point(x: number, y: number): Point { - return { x, y }; -} -``` - -File game.ts: - -```TypeScript -import * as g from "./geometry"; -let p = g.point(10, 20); -``` - -The 'game' module references the imported 'geometry' module in an expression (through its alias 'g') and a 'require' call is therefore included in the emitted JavaScript: - -```TypeScript -var g = require("./geometry"); -var p = g.point(10, 20); -``` - -Had the 'game' module instead been written to only reference 'geometry' in a type position - -```TypeScript -import * as g from "./geometry"; -let p: g.Point = { x: 10, y: 20 }; -``` - -the emitted JavaScript would have no dependency on the 'geometry' module and would simply be - -```TypeScript -var p = { x: 10, y: 20 }; -``` - -### 11.3.7 AMD Modules - -The [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) (AMD) specification extends the CommonJS Modules specification with a pattern for authoring asynchronously loadable modules with associated dependencies. Using the AMD pattern, modules are emitted as calls to a global 'define' function taking an array of dependencies, specified as module names, and a callback function containing the module body. The global 'define' function is provided by including an AMD compliant loader in the application. The loader arranges to asynchronously load the module's dependencies and, upon completion, calls the callback function passing resolved module instances as arguments in the order they were listed in the dependency array. - -The "main" and "log" example from above generates the following JavaScript code when compiled for the AMD pattern. - -File main.js: - -```TypeScript -define(["require", "exports", "./log"], function(require, exports, log_1) { - log_1.message("hello"); -} -``` - -File log.js: - -```TypeScript -define(["require", "exports"], function(require, exports) { - function message(s) { - console.log(s); - } - exports.message = message; -} -``` - -The special 'require' and 'exports' dependencies are always present. Additional entries are added to the dependencies array and the parameter list as required to represent imported modules. Similar to the code generation for CommonJS Modules, a dependency entry is generated for a particular imported module only if the imported module is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *NamespaceName*, no dependency is generated for that module. - -
- -#
12 Ambients - -Ambient declarations are used to provide static typing over existing JavaScript code. Ambient declarations differ from regular declarations in that no JavaScript code is emitted for them. Instead of introducing new variables, functions, classes, enums, or namespaces, ambient declarations provide type information for entities that exist "ambiently" and are included in a program by external means, for example by referencing a JavaScript library in a <script/> tag. - -## 12.1 Ambient Declarations - -Ambient declarations are written using the `declare` keyword and can declare variables, functions, classes, enums, namespaces, or modules. - -  *AmbientDeclaration:* -   `declare` *AmbientVariableDeclaration* -   `declare` *AmbientFunctionDeclaration* -   `declare` *AmbientClassDeclaration* -   `declare` *AmbientEnumDeclaration* -   `declare` *AmbientNamespaceDeclaration* - -### 12.1.1 Ambient Variable Declarations - -An ambient variable declaration introduces a variable in the containing declaration space. - -  *AmbientVariableDeclaration:* -   `var` *AmbientBindingList* `;` -   `let` *AmbientBindingList* `;` -   `const` *AmbientBindingList* `;` - -  *AmbientBindingList:* -   *AmbientBinding* -   *AmbientBindingList* `,` *AmbientBinding* - -  *AmbientBinding:* -   *BindingIdentifier* *TypeAnnotationopt* - -An ambient variable declaration may optionally include a type annotation. If no type annotation is present, the variable is assumed to have type Any. - -An ambient variable declaration does not permit an initializer expression to be present. - -### 12.1.2 Ambient Function Declarations - -An ambient function declaration introduces a function in the containing declaration space. - -  *AmbientFunctionDeclaration:* -   `function` *BindingIdentifier* *CallSignature* `;` - -Ambient functions may be overloaded by specifying multiple ambient function declarations with the same name, but it is an error to declare multiple overloads that are considered identical (section [3.11.2](#3.11.2)) or differ only in their return types. - -Ambient function declarations cannot specify a function bodies and do not permit default parameter values. - -### 12.1.3 Ambient Class Declarations - -An ambient class declaration declares a class type and a constructor function in the containing declaration space. - -  *AmbientClassDeclaration:* -   `class` *BindingIdentifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}` - -  *AmbientClassBody:* -   *AmbientClassBodyElementsopt* - -  *AmbientClassBodyElements:* -   *AmbientClassBodyElement* -   *AmbientClassBodyElements* *AmbientClassBodyElement* - -  *AmbientClassBodyElement:* -   *AmbientConstructorDeclaration* -   *AmbientPropertyMemberDeclaration* -   *IndexSignature* - -  *AmbientConstructorDeclaration:* -   `constructor` `(` *ParameterListopt* `)` `;` - -  *AmbientPropertyMemberDeclaration:* -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* `;` -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;` - -### 12.1.4 Ambient Enum Declarations - -An ambient enum is grammatically equivalent to a non-ambient enum declaration. - -  *AmbientEnumDeclaration:* -   *EnumDeclaration* - -Ambient enum declarations differ from non-ambient enum declarations in two ways: - -* In ambient enum declarations, all values specified in enum member declarations must be classified as constant enum expressions. -* 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 assigned). - -Ambient enum declarations are otherwise processed in the same manner as non-ambient enum declarations. - -### 12.1.5 Ambient Namespace Declarations - -An ambient namespace declaration declares a namespace. - -  *AmbientNamespaceDeclaration:* -   `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}` - -  *AmbientNamespaceBody:* -   *AmbientNamespaceElementsopt* - -  *AmbientNamespaceElements:* -   *AmbientNamespaceElement* -   *AmbientNamespaceElements* *AmbientNamespaceElement* - -  *AmbientNamespaceElement:* -   `export`*opt* *AmbientVariableDeclaration* -   `export`*opt* *AmbientLexicalDeclaration* -   `export`*opt* *AmbientFunctionDeclaration* -   `export`*opt* *AmbientClassDeclaration* -   `export`*opt* *InterfaceDeclaration* -   `export`*opt* *AmbientEnumDeclaration* -   `export`*opt* *AmbientNamespaceDeclaration* -   `export`*opt* *ImportAliasDeclaration* - -Except for *ImportAliasDeclarations*, *AmbientNamespaceElements* always declare exported entities regardless of whether they include the optional `export` modifier. - -## 12.2 Ambient Module Declarations - -An *AmbientModuleDeclaration* declares a module. This type of declaration is permitted only at the top level in a source file that contributes to the global namespace (section [11.1](#11.1)). The *StringLiteral* must specify a top-level module name. Relative module names are not permitted. - -  *AmbientModuleDeclaration:* -   `declare` `module` *StringLiteral* `{`  *DeclarationModule* `}` - -An *ImportRequireDeclaration* in an *AmbientModuleDeclaration* may reference other modules only through top-level module names. Relative module names are not permitted. - -If an ambient module declaration includes an export assignment, it is an error for any of the declarations within the module to specify an `export` modifier. If an ambient module declaration contains no export assignment, entities declared in the module are exported regardless of whether their declarations include the optional `export` modifier. - -Ambient modules are "open-ended" and ambient module declarations with the same string literal name contribute to a single module. For example, the following two declarations of a module 'io' might be located in separate source files. - -```TypeScript -declare module "io" { - export function readFile(filename: string): string; -} - -declare module "io" { - export function writeFile(filename: string, data: string): void; -} -``` - -This has the same effect as a single combined declaration: - -```TypeScript -declare module "io" { - export function readFile(filename: string): string; - export function writeFile(filename: string, data: string): void; -} -``` - -
- -#
A Grammar - -This appendix contains a summary of the grammar found in the main document. As described in section [2.1](#2.1), the TypeScript grammar is a superset of the grammar defined in the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar. - -## A.1 Types - -  *TypeParameters:* -   `<` *TypeParameterList* `>` - -  *TypeParameterList:* -   *TypeParameter* -   *TypeParameterList* `,` *TypeParameter* - -  *TypeParameter:* -   *BindingIdentifier* *Constraintopt* - -  *Constraint:* -   `extends` *Type* - -  *TypeArguments:* -   `<` *TypeArgumentList* `>` - -  *TypeArgumentList:* -   *TypeArgument* -   *TypeArgumentList* `,` *TypeArgument* - -  *TypeArgument:* -   *Type* - -  *Type:* -   *UnionOrIntersectionOrPrimaryType* -   *FunctionType* -   *ConstructorType* - -  *UnionOrIntersectionOrPrimaryType:* -   *UnionType* -   *IntersectionOrPrimaryType* - -  *IntersectionOrPrimaryType:* -   *IntersectionType* -   *PrimaryType* - -  *PrimaryType:* -   *ParenthesizedType* -   *PredefinedType* -   *TypeReference* -   *ObjectType* -   *ArrayType* -   *TupleType* -   *TypeQuery* -   *ThisType* - -  *ParenthesizedType:* -   `(` *Type* `)` - -  *PredefinedType:* -   `any` -   `number` -   `boolean` -   `string` -   `symbol` -   `void` - -  *TypeReference:* -   *TypeName* *[no LineTerminator here]* *TypeArgumentsopt* - -  *TypeName:* -   *IdentifierReference* -   *NamespaceName* `.` *IdentifierReference* - -  *NamespaceName:* -   *IdentifierReference* -   *NamespaceName* `.` *IdentifierReference* - -  *ObjectType:* -   `{` *TypeBodyopt* `}` - -  *TypeBody:* -   *TypeMemberList* `;`*opt* -   *TypeMemberList* `,`*opt* - -  *TypeMemberList:* -   *TypeMember* -   *TypeMemberList* `;` *TypeMember* -   *TypeMemberList* `,` *TypeMember* - -  *TypeMember:* -   *PropertySignature* -   *CallSignature* -   *ConstructSignature* -   *IndexSignature* -   *MethodSignature* - -  *ArrayType:* -   *PrimaryType* *[no LineTerminator here]* `[` `]` - -  *TupleType:* -   `[` *TupleElementTypes* `]` - -  *TupleElementTypes:* -   *TupleElementType* -   *TupleElementTypes* `,` *TupleElementType* - -  *TupleElementType:* -   *Type* - -  *UnionType:* -   *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType* - -  *IntersectionType:* -   *IntersectionOrPrimaryType* `&` *PrimaryType* - -  *FunctionType:* -   *TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type* - -  *ConstructorType:* -   `new` *TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type* - -  *TypeQuery:* -   `typeof` *TypeQueryExpression* - -  *TypeQueryExpression:* -   *IdentifierReference* -   *TypeQueryExpression* `.` *IdentifierName* - -  *ThisType:* -   `this` - -  *PropertySignature:* -   *PropertyName* `?`*opt* *TypeAnnotationopt* - -  *PropertyName:* -   *IdentifierName* -   *StringLiteral* -   *NumericLiteral* - -  *TypeAnnotation:* -   `:` *Type* - -  *CallSignature:* -   *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt* - -  *ParameterList:* -   *RequiredParameterList* -   *OptionalParameterList* -   *RestParameter* -   *RequiredParameterList* `,` *OptionalParameterList* -   *RequiredParameterList* `,` *RestParameter* -   *OptionalParameterList* `,` *RestParameter* -   *RequiredParameterList* `,` *OptionalParameterList* `,` *RestParameter* - -  *RequiredParameterList:* -   *RequiredParameter* -   *RequiredParameterList* `,` *RequiredParameter* - -  *RequiredParameter:* -   *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* -   *BindingIdentifier* `:` *StringLiteral* - -  *AccessibilityModifier:* -   `public` -   `private` -   `protected` - -  *BindingIdentifierOrPattern:* -   *BindingIdentifier* -   *BindingPattern* - -  *OptionalParameterList:* -   *OptionalParameter* -   *OptionalParameterList* `,` *OptionalParameter* - -  *OptionalParameter:* -   *AccessibilityModifieropt* *BindingIdentifierOrPattern* `?` *TypeAnnotationopt* -   *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* *Initializer* -   *BindingIdentifier* `?` `:` *StringLiteral* - -  *RestParameter:* -   `...` *BindingIdentifier* *TypeAnnotationopt* - -  *ConstructSignature:* -   `new` *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt* - -  *IndexSignature:* -   `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation* -   `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation* - -  *MethodSignature:* -   *PropertyName* `?`*opt* *CallSignature* - -  *TypeAliasDeclaration:* -   `type` *BindingIdentifier* *TypeParametersopt* `=` *Type* `;` - -## A.2 Expressions - -  *PropertyDefinition:* *( Modified )* -   *IdentifierReference* -   *CoverInitializedName* -   *PropertyName* `:` *AssignmentExpression* -   *PropertyName* *CallSignature* `{` *FunctionBody* `}` -   *GetAccessor* -   *SetAccessor* - -  *GetAccessor:* -   `get` *PropertyName* `(` `)` *TypeAnnotationopt* `{` *FunctionBody* `}` - -  *SetAccessor:* -   `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotationopt* `)` `{` *FunctionBody* `}` - -  *FunctionExpression:* *( Modified )* -   `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}` - -  *ArrowFormalParameters:* *( Modified )* -   *CallSignature* - -  *Arguments:* *( Modified )* -   *TypeArgumentsopt* `(` *ArgumentListopt* `)` - -  *UnaryExpression:* *( Modified )* -   … -   `<` *Type* `>` *UnaryExpression* - -## A.3 Statements - -  *Declaration:* *( Modified )* -   … -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *EnumDeclaration* - -  *VariableDeclaration:* *( Modified )* -   *SimpleVariableDeclaration* -   *DestructuringVariableDeclaration* - -  *SimpleVariableDeclaration:* -   *BindingIdentifier* *TypeAnnotationopt* *Initializeropt* - -  *DestructuringVariableDeclaration:* -   *BindingPattern* *TypeAnnotationopt* *Initializer* - -  *LexicalBinding:* *( Modified )* -   *SimpleLexicalBinding* -   *DestructuringLexicalBinding* - -  *SimpleLexicalBinding:* -   *BindingIdentifier* *TypeAnnotationopt* *Initializeropt* - -  *DestructuringLexicalBinding:* -   *BindingPattern* *TypeAnnotationopt* *Initializeropt* - -## A.4 Functions - -  *FunctionDeclaration:* *( Modified )* -   `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}` -   `function` *BindingIdentifieropt* *CallSignature* `;` - -## A.5 Interfaces - -  *InterfaceDeclaration:* -   `interface` *BindingIdentifier* *TypeParametersopt* *InterfaceExtendsClauseopt* *ObjectType* - -  *InterfaceExtendsClause:* -   `extends` *ClassOrInterfaceTypeList* - -  *ClassOrInterfaceTypeList:* -   *ClassOrInterfaceType* -   *ClassOrInterfaceTypeList* `,` *ClassOrInterfaceType* - -  *ClassOrInterfaceType:* -   *TypeReference* - -## A.6 Classes - -  *ClassDeclaration:* *( Modified )* -   `class` *BindingIdentifieropt* *TypeParametersopt* *ClassHeritage* `{` *ClassBody* `}` - -  *ClassHeritage:* *( Modified )* -   *ClassExtendsClauseopt* *ImplementsClauseopt* - -  *ClassExtendsClause:* -   `extends`  *ClassType* - -  *ClassType:* -   *TypeReference* - -  *ImplementsClause:* -   `implements` *ClassOrInterfaceTypeList* - -  *ClassElement:* *( Modified )* -   *ConstructorDeclaration* -   *PropertyMemberDeclaration* -   *IndexMemberDeclaration* - -  *ConstructorDeclaration:* -   *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `{` *FunctionBody* `}` -   *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `;` - -  *PropertyMemberDeclaration:* -   *MemberVariableDeclaration* -   *MemberFunctionDeclaration* -   *MemberAccessorDeclaration* - -  *MemberVariableDeclaration:* -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* *Initializeropt* `;` - -  *MemberFunctionDeclaration:* -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `{` *FunctionBody* `}` -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;` - -  *MemberAccessorDeclaration:* -   *AccessibilityModifieropt* `static`*opt* *GetAccessor* -   *AccessibilityModifieropt* `static`*opt* *SetAccessor* - -  *IndexMemberDeclaration:* -   *IndexSignature* `;` - -## A.7 Enums - -  *EnumDeclaration:* -   `const`*opt* `enum` *BindingIdentifier* `{` *EnumBodyopt* `}` - -  *EnumBody:* -   *EnumMemberList* `,`*opt* - -  *EnumMemberList:* -   *EnumMember* -   *EnumMemberList* `,` *EnumMember* - -  *EnumMember:* -   *PropertyName* -   *PropertyName* = *EnumValue* - -  *EnumValue:* -   *AssignmentExpression* - -## A.8 Namespaces - -  *NamespaceDeclaration:* -   `namespace` *IdentifierPath* `{` *NamespaceBody* `}` - -  *IdentifierPath:* -   *BindingIdentifier* -   *IdentifierPath* `.` *BindingIdentifier* - -  *NamespaceBody:* -   *NamespaceElementsopt* - -  *NamespaceElements:* -   *NamespaceElement* -   *NamespaceElements* *NamespaceElement* - -  *NamespaceElement:* -   *Statement* -   *LexicalDeclaration* -   *FunctionDeclaration* -   *GeneratorDeclaration* -   *ClassDeclaration* -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *EnumDeclaration* -   *NamespaceDeclaration -   AmbientDeclaration -   ImportAliasDeclaration -   ExportNamespaceElement* - -  *ExportNamespaceElement:* -   `export` *VariableStatement* -   `export` *LexicalDeclaration* -   `export` *FunctionDeclaration* -   `export` *GeneratorDeclaration* -   `export` *ClassDeclaration* -   `export` *InterfaceDeclaration* -   `export` *TypeAliasDeclaration* -   `export` *EnumDeclaration* -   `export` *NamespaceDeclaration* -   `export` *AmbientDeclaration* -   `export` *ImportAliasDeclaration* - -  *ImportAliasDeclaration:* -   `import` *BindingIdentifier* `=` *EntityName* `;` - -  *EntityName:* -   *NamespaceName* -   *NamespaceName* `.` *IdentifierReference* - -## A.9 Scripts and Modules - -  *SourceFile:* -   *ImplementationSourceFile* -   *DeclarationSourceFile* - -  *ImplementationSourceFile:* -   *ImplementationScript* -   *ImplementationModule* - -  *DeclarationSourceFile:* -   *DeclarationScript* -   *DeclarationModule* - -  *ImplementationScript:* -   *ImplementationScriptElementsopt* - -  *ImplementationScriptElements:* -   *ImplementationScriptElement* -   *ImplementationScriptElements* *ImplementationScriptElement* - -  *ImplementationScriptElement:* -   *ImplementationElement* -   *AmbientModuleDeclaration* - -  *ImplementationElement:* -   *Statement* -   *LexicalDeclaration* -   *FunctionDeclaration* -   *GeneratorDeclaration* -   *ClassDeclaration* -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *EnumDeclaration* -   *NamespaceDeclaration* -   *AmbientDeclaration* -   *ImportAliasDeclaration* - -  *DeclarationScript:* -   *DeclarationScriptElementsopt* - -  *DeclarationScriptElements:* -   *DeclarationScriptElement* -   *DeclarationScriptElements* *DeclarationScriptElement* - -  *DeclarationScriptElement:* -   *DeclarationElement* -   *AmbientModuleDeclaration* - -  *DeclarationElement:* -   *InterfaceDeclaration* -   *TypeAliasDeclaration* -   *NamespaceDeclaration* -   *AmbientDeclaration* -   *ImportAliasDeclaration* - -  *ImplementationModule:* -   *ImplementationModuleElementsopt* - -  *ImplementationModuleElements:* -   *ImplementationModuleElement* -   *ImplementationModuleElements* *ImplementationModuleElement* - -  *ImplementationModuleElement:* -   *ImplementationElement* -   *ImportDeclaration* -   *ImportAliasDeclaration* -   *ImportRequireDeclaration* -   *ExportImplementationElement* -   *ExportDefaultImplementationElement* -   *ExportListDeclaration* -   *ExportAssignment* - -  *DeclarationModule:* -   *DeclarationModuleElementsopt* - -  *DeclarationModuleElements:* -   *DeclarationModuleElement* -   *DeclarationModuleElements* *DeclarationModuleElement* - -  *DeclarationModuleElement:* -   *DeclarationElement* -   *ImportDeclaration* -   *ImportAliasDeclaration* -   *ExportDeclarationElement* -   *ExportDefaultDeclarationElement* -   *ExportListDeclaration* -   *ExportAssignment* - -  *ImportRequireDeclaration:* -   `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;` - -  *ExportImplementationElement:* -   `export` *VariableStatement* -   `export` *LexicalDeclaration* -   `export` *FunctionDeclaration* -   `export` *GeneratorDeclaration* -   `export` *ClassDeclaration* -   `export` *InterfaceDeclaration* -   `export` *TypeAliasDeclaration* -   `export` *EnumDeclaration* -   `export` *NamespaceDeclaration* -   `export` *AmbientDeclaration* -   `export` *ImportAliasDeclaration* - -  *ExportDeclarationElement:* -   `export` *InterfaceDeclaration* -   `export` *TypeAliasDeclaration* -   `export` *AmbientDeclaration* -   `export` *ImportAliasDeclaration* - -  *ExportDefaultImplementationElement:* -   `export` `default` *FunctionDeclaration* -   `export` `default` *GeneratorDeclaration* -   `export` `default` *ClassDeclaration* -   `export` `default` *AssignmentExpression* `;` - -  *ExportDefaultDeclarationElement:* -   `export` `default` *AmbientFunctionDeclaration* -   `export` `default` *AmbientClassDeclaration* -   `export` `default` *IdentifierReference* `;` - -  *ExportListDeclaration:* -   `export` `*` *FromClause* `;` -   `export` *ExportClause* *FromClause* `;` -   `export` *ExportClause* `;` - -  *ExportAssignment:* -   `export` `=` *IdentifierReference* `;` - -## A.10 Ambients - -  *AmbientDeclaration:* -   `declare` *AmbientVariableDeclaration* -   `declare` *AmbientFunctionDeclaration* -   `declare` *AmbientClassDeclaration* -   `declare` *AmbientEnumDeclaration* -   `declare` *AmbientNamespaceDeclaration* - -  *AmbientVariableDeclaration:* -   `var` *AmbientBindingList* `;` -   `let` *AmbientBindingList* `;` -   `const` *AmbientBindingList* `;` - -  *AmbientBindingList:* -   *AmbientBinding* -   *AmbientBindingList* `,` *AmbientBinding* - -  *AmbientBinding:* -   *BindingIdentifier* *TypeAnnotationopt* - -  *AmbientFunctionDeclaration:* -   `function` *BindingIdentifier* *CallSignature* `;` - -  *AmbientClassDeclaration:* -   `class` *BindingIdentifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}` - -  *AmbientClassBody:* -   *AmbientClassBodyElementsopt* - -  *AmbientClassBodyElements:* -   *AmbientClassBodyElement* -   *AmbientClassBodyElements* *AmbientClassBodyElement* - -  *AmbientClassBodyElement:* -   *AmbientConstructorDeclaration* -   *AmbientPropertyMemberDeclaration* -   *IndexSignature* - -  *AmbientConstructorDeclaration:* -   `constructor` `(` *ParameterListopt* `)` `;` - -  *AmbientPropertyMemberDeclaration:* -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* `;` -   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;` - -  *AmbientEnumDeclaration:* -   *EnumDeclaration* - -  *AmbientNamespaceDeclaration:* -   `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}` - -  *AmbientNamespaceBody:* -   *AmbientNamespaceElementsopt* - -  *AmbientNamespaceElements:* -   *AmbientNamespaceElement* -   *AmbientNamespaceElements* *AmbientNamespaceElement* - -  *AmbientNamespaceElement:* -   `export`*opt* *AmbientVariableDeclaration* -   `export`*opt* *AmbientLexicalDeclaration* -   `export`*opt* *AmbientFunctionDeclaration* -   `export`*opt* *AmbientClassDeclaration* -   `export`*opt* *InterfaceDeclaration* -   `export`*opt* *AmbientEnumDeclaration* -   `export`*opt* *AmbientNamespaceDeclaration* -   `export`*opt* *ImportAliasDeclaration* - -  *AmbientModuleDeclaration:* -   `declare` `module` *StringLiteral* `{`  *DeclarationModule* `}` - + +Section [3.9.2.4](#3.9.2.4) provides details on how to use string literals in function signatures. + +## 1.9 Generic Types and Functions + +Like overloading on string parameters, *generic types* make it easier for TypeScript to accurately capture the behavior of JavaScript libraries. Because they enable type information to flow from client code, through library code, and back into client code, generic types may do more than any other TypeScript feature to support detailed API descriptions. + +To illustrate this, let's take a look at part of the TypeScript interface for the built-in JavaScript array type. You can find this interface in the 'lib.d.ts' file that accompanies a TypeScript distribution. + +```TypeScript +interface Array { + reverse(): T[]; + sort(compareFn?: (a: T, b: T) => number): T[]; + // ... +} +``` + +Interface definitions, like the one above, can have one or more *type parameters*. In this case the 'Array' interface has a single parameter, 'T', that defines the element type for the array. The 'reverse' method returns an array with the same element type. The sort method takes an optional parameter, 'compareFn', whose type is a function that takes two parameters of type 'T' and returns a number. Finally, sort returns an array with element type 'T'. + +Functions can also have generic parameters. For example, the array interface contains a 'map' method, defined as follows: + +```TypeScript +map(func: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; +``` + +The map method, invoked on an array 'a' with element type 'T', will apply function 'func' to each element of 'a', returning a value of type 'U'. + +The TypeScript compiler can often infer generic method parameters, making it unnecessary for the programmer to explicitly provide them. In the following example, the compiler infers that parameter 'U' of the map method has type 'string', because the function passed to map returns a string. + +```TypeScript +function numberToString(a: number[]) { + var stringArray = a.map(v => v.toString()); + return stringArray; +} +``` + +The compiler infers in this example that the 'numberToString' function returns an array of strings. + +In TypeScript, classes can also have type parameters. The following code declares a class that implements a linked list of items of type 'T'. This code illustrates how programmers can *constrain* type parameters to extend a specific type. In this case, the items on the list must extend the type 'NamedItem'. This enables the programmer to implement the 'log' function, which logs the name of the item. + +```TypeScript +interface NamedItem { + name: string; +} + +class List { + next: List = null; + + constructor(public item: T) { + } + + insertAfter(item: T) { + var temp = this.next; + this.next = new List(item); + this.next.next = temp; + } + + log() { + console.log(this.item.name); + } + + // ... +} +``` + +Section [3.7](#3.7) provides further information about generic types. + +## 1.10 Namespaces + +Classes and interfaces support large-scale JavaScript development by providing a mechanism for describing how to use a software component that can be separated from that component's implementation. TypeScript enforces *encapsulation* of implementation in classes at design time (by restricting use of private and protected members), but cannot enforce encapsulation at runtime because all object properties are accessible at runtime. Future versions of JavaScript may provide *private names* which would enable runtime enforcement of private and protected members. + +In JavaScript, a very common way to enforce encapsulation at runtime is to use the module pattern: encapsulate private fields and methods using closure variables. The module pattern is a natural way to provide organizational structure and dynamic loading options by drawing a boundary around a software component. The module pattern can also provide the ability to introduce namespaces, avoiding use of the global namespace for most software components. + +The following example illustrates the JavaScript module pattern. + +```TypeScript +(function(exports) { + var key = generateSecretKey(); + function sendMessage(message) { + sendSecureMessage(message, key); + } + exports.sendMessage = sendMessage; +})(MessageModule); +``` + +This example illustrates the two essential elements of the module pattern: a *module closure* and a *module* *object*. The module closure is a function that encapsulates the module's implementation, in this case the variable 'key' and the function 'sendMessage'. The module object contains the exported variables and functions of the module. Simple modules may create and return the module object. The module above takes the module object as a parameter, 'exports', and adds the 'sendMessage' property to the module object. This *augmentation* approach simplifies dynamic loading of modules and also supports separation of module code into multiple files. + +The example assumes that an outer lexical scope defines the functions 'generateSecretKey' and 'sendSecureMessage'; it also assumes that the outer scope has assigned the module object to the variable 'MessageModule'. + +TypeScript namespaces provide a mechanism for succinctly expressing the module pattern. In TypeScript, programmers can combine the module pattern with the class pattern by nesting namespaces and classes within an outer namespace. + +The following example shows the definition and use of a simple namespace. + +```TypeScript +namespace M { + var s = "hello"; + export function f() { + return s; + } +} + +M.f(); +M.s; // Error, s is not exported +``` + +In this example, variable 's' is a private feature of the namespace, but function 'f' is exported from the namespace and accessible to code outside of the namespace. If we were to describe the effect of namespace 'M' in terms of interfaces and variables, we would write + +```TypeScript +interface M { + f(): string; +} + +var M: M; +``` + +The interface 'M' summarizes the externally visible behavior of namespace 'M'. In this example, we can use the same name for the interface as for the initialized variable because in TypeScript type names and variable names do not conflict: each lexical scope contains a variable declaration space and type declaration space (see section [2.3](#2.3) for more details). + +The TypeScript compiler emits the following JavaScript code for the namespace: + +```TypeScript +var M; +(function(M) { + var s = "hello"; + function f() { + return s; + } + M.f = f; +})(M || (M = {})); +``` + +In this case, the compiler assumes that the namespace object resides in global variable 'M', which may or may not have been initialized to the desired namespace object. + +## 1.11 Modules + +TypeScript also supports ECMAScript 2015 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 2015 compliant code and down-level ECMAScript 3 or 5 compliant code for a variety of module loading systems, including CommonJS, Asynchronous Module Definition (AMD), and Universal Module Definition (UMD). + +
+ +#
2 Basic Concepts + +The remainder of this document is the formal specification of the TypeScript programming language and is intended to be read as an adjunct to the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition). This document describes the syntactic grammar added by TypeScript along with the compile-time processing and type checking performed by the TypeScript compiler, but it only minimally discusses the run-time behavior of programs since that is covered by the ECMAScript specification. + +## 2.1 Grammar Conventions + +The syntactic grammar added by TypeScript language is specified throughout this document using the existing conventions and production names of the ECMAScript grammar. In places where TypeScript augments an existing grammar production it is so noted. For example: + +  *Declaration:* *( Modified )* +   … +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *EnumDeclaration* + +The '*( Modified )*' annotation indicates that an existing grammar production is being replaced, and the '…' references the contents of the original grammar production. + +Similar to the ECMAScript grammar, if the phrase "*[no LineTerminator here]*" appears in the right-hand side of a production of the syntactic grammar, it indicates that the production is not a match if a *LineTerminator* occurs in the input stream at the indicated position. + +## 2.2 Names + +A core purpose of the TypeScript compiler is to track the named entities in a program and validate that they are used according to their designated meaning. Names in TypeScript can be written in several ways, depending on context. Specifically, a name can be written as + +* an *IdentifierName*, +* a *StringLiteral* in a property name, +* a *NumericLiteral* in a property name, or +* a *ComputedPropertyName* that denotes a well-known symbol ([2.2.3](#2.2.3)). + +Most commonly, names are written to conform with the *Identifier* production, which is any *IdentifierName* that isn't a reserved word. + +### 2.2.1 Reserved Words + +The following keywords are reserved and cannot be used as an *Identifier*: + +```TypeScript +break case catch class +const continue debugger default +delete do else enum +export extends false finally +for function if import +in instanceof new null +return super switch this +throw true try typeof +var void while with +``` + +The following keywords cannot be used as identifiers in strict mode code, but are otherwise not restricted: + +```TypeScript +implements interface let package +private protected public static +yield +``` + +The following keywords cannot be used as user defined type names, but are otherwise not restricted: + +```TypeScript +any boolean number string +symbol +``` + +The following keywords have special meaning in certain contexts, but are valid identifiers: + +```TypeScript +abstract as async await +constructor declare from get +is module namespace of +require set type +``` + +### 2.2.2 Property Names + +The *PropertyName* production from the ECMAScript grammar is reproduced below: + +  *PropertyName:* +   *LiteralPropertyName* +   *ComputedPropertyName* + +  *LiteralPropertyName:* +   *IdentifierName* +   *StringLiteral* +   *NumericLiteral* + +  *ComputedPropertyName:* +   `[` *AssignmentExpression* `]` + +A property name can be any identifier (including a reserved word), a string literal, a numeric literal, or a computed property name. String literals may be used to give properties names that are not valid identifiers, such as names containing blanks. Numeric literal property names are equivalent to string literal property names with the string representation of the numeric literal, as defined in the ECMAScript specification. + +### 2.2.3 Computed Property Names + +ECMAScript 2015 permits object literals and classes to declare members with computed property names. A computed property name specifies an expression that computes the actual property name at run-time. Because the final property name isn't known at compile-time, TypeScript can only perform limited checks for entities declared with computed property names. However, a subset of computed property names known as ***well-known symbols*** can be used anywhere a *PropertyName* is expected, including property names within types. A computed property name is a well-known symbol if it is of the form + +```TypeScript +[ Symbol . xxx ] +``` + +In a well-known symbol, the identifier to the right of the dot must denote a property of the primitive type `symbol` in the type of the global variable 'Symbol', or otherwise an error occurs. + +In a *PropertyName* that specifies a *ComputedPropertyName*, the computed property name is required to denote a well-known symbol unless the property name occurs in a property assignment of an object literal ([4.5](#4.5)) or a property member declaration in a non-ambient class ([8.4](#8.4)). + +Below is an example of an interface that declares a property with a well-known symbol name: + +```TypeScript +interface Iterable { + [Symbol.iterator](): Iterator; +} +``` + +*TODO: Update to reflect treatment of [computed property names with literal expressions](https://github.com/Microsoft/TypeScript/pull/5535)*. + +## 2.3 Declarations + +Declarations introduce names in their associated ***declaration spaces***. A name must be unique in its declaration space and can denote a ***value***, a ***type***, or a ***namespace***, or some combination thereof. Effectively, a single name can have as many as three distinct meanings. For example: + +```TypeScript +var X: string; // Value named X + +type X = number; // Type named X + +namespace X { // Namespace named X + type Y = string; +} +``` + +A name that denotes a value has an associated type (section [3](#3)) and can be referenced in expressions (section [4.3](#4.3)). A name that denotes a type can be used by itself in a type reference or on the right hand side of a dot in a type reference ([3.8.2](#3.8.2)). A name that denotes a namespace can be used one the left hand side of a dot in a type reference. + +When a name with multiple meanings is referenced, the context in which the reference occurs determines the meaning. For example: + +```TypeScript +var n: X; // X references type +var s: X.Y = X; // First X references namespace, second X references value +``` + +In the first line, X references the type X because it occurs in a type position. In the second line, the first X references the namespace X because it occurs before a dot in a type name, and the second X references the variable X because it occurs in an expression. + +Declarations introduce the following meanings for the name they declare: + +* A variable, parameter, function, generator, member variable, member function, member accessor, or enum member declaration introduces a value meaning. +* An interface, type alias, or type parameter declaration introduces a type meaning. +* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class type). +* An enum declaration introduces a value meaning (the enum instance) and a type meaning (the enum type). +* A namespace declaration introduces a namespace meaning (the type and namespace container) and, if the namespace is instantiated (section [10.1](#10.1)), a value meaning (the namespace instance). +* An import or export declaration introduces the meaning(s) of the imported or exported entity. + +Below are some examples of declarations that introduce multiple meanings for a name: + +```TypeScript +class C { // Value and type named C + x: string; +} + +namespace N { // Value and namespace named N + export var x: string; +} +``` + +Declaration spaces exist as follows: + +* The global namespace, each module, and each declared namespace has a declaration space for its contained entities (whether local or exported). +* Each module has a declaration space for its exported entities. All export declarations in the module contribute to this declaration space. +* Each declared namespace has a declaration space for its exported entities. All export declarations in the namespace contribute to this declaration space. A declared namespace’s declaration space is shared with other declared namespaces that have the same root container and the same qualified name starting from that root container. +* Each class declaration has a declaration space for instance members and type parameters, and a declaration space for static members. +* Each interface declaration has a declaration space for members and type parameters. An interface's declaration space is shared with other interfaces that have the same root container and the same qualified name starting from that root container. +* Each enum declaration has a declaration space for its enum members. An enum's declaration space is shared with other enums that have the same root container and the same qualified name starting from that root container. +* Each type alias declaration has a declaration space for its type parameters. +* Each function-like declaration (including function declarations, constructor declarations, member function declarations, member accessor declarations, function expressions, and arrow functions) has a declaration space for locals and type parameters. This declaration space includes parameter declarations, all local var and function declarations, and local let, const, class, interface, type alias, and enum declarations that occur immediately within the function body and are not further nested in blocks. +* Each statement block has a declaration space for local let, const, class, interface, type alias, and enum declarations that occur immediately within that block. +* Each object literal has a declaration space for its properties. +* Each object type literal has a declaration space for its members. + +Top-level declarations in a source file with no top-level import or export declarations belong to the ***global namespace***. Top-level declarations in a source file with one or more top-level import or export declarations belong to the ***module*** represented by that source file. + +The ***container*** of an entity is defined as follows: + +* The container of an entity declared in a namespace declaration is that namespace declaration. +* The container of an entity declared in a module is that module. +* The container of an entity declared in the global namespace is the global namespace. +* The container of a module is the global namespace. + +The ***root container*** of an entity is defined as follows: + +* The root container of a non-exported entity is the entity’s container. +* The root container of an exported entity is the root container of the entity's container. + +Intuitively, the root container of an entity is the outermost module or namespace body from within which the entity is reachable. + +Interfaces, enums, and namespaces are "open ended," meaning that interface, enum, and namespace declarations with the same qualified name relative to a common root are automatically merged. For further details, see sections [7.2](#7.2), [9.3](#9.3), and [10.5](#10.5). + +Instance and static members in a class are in separate declaration spaces. Thus the following is permitted: + +```TypeScript +class C { + x: number; // Instance member + static x: string; // Static member +} +``` + +## 2.4 Scopes + +The ***scope*** of a name is the region of program text within which it is possible to refer to the entity declared by that name without qualification of the name. The scope of a name depends on the context in which the name is declared. The contexts are listed below in order from outermost to innermost: + +* The scope of a name declared in the global namespace is the entire program text. +* The scope of a name declared in a module is the source file of that module. +* The scope of an exported name declared within a namespace declaration is the body of that namespace declaration and every namespace declaration with the same root and the same qualified name relative to that root. +* The scope of a non-exported name declared within a namespace declaration is the body of that namespace declaration. +* The scope of a type parameter name declared in a class or interface declaration is that entire declaration, including constraints, extends clause, implements clause, and declaration body, but not including static member declarations. +* The scope of a type parameter name declared in a type alias declaration is that entire type alias declaration. +* The scope of a member name declared in an enum declaration is the body of that declaration and every enum declaration with the same root and the same qualified name relative to that root. +* The scope of a type parameter name declared in a call or construct signature is that entire signature declaration, including constraints, parameter list, and return type. If the signature is part of a function implementation, the scope includes the function body. +* The scope of a parameter name declared in a call or construct signature is the remainder of the signature declaration. If the signature is part of a function-like declaration with a body (including a function declaration, constructor declaration, member function declaration, member accessor declaration, function expression, or arrow function), the scope includes the body of that function-like declaration. +* The scope of a local var or function name declared anywhere in the body of a function-like declaration is the body of that function-like declaration. +* The scope of a local let, const, class, interface, type alias, or enum declaration declared immediately within the body of a function-like declaration is the body of that function-like declaration. +* The scope of a local let, const, class, interface, type alias, or enum declaration declared immediately within a statement block is the body of that statement block. + +Scopes may overlap, for example through nesting of namespaces and functions. When the scopes of two names overlap, the name with the innermost declaration takes precedence and access to the outer name is either not possible or only possible by qualification. + +When an identifier is resolved as a *PrimaryExpression* (section [4.3](#4.3)), only names in scope with a value meaning are considered and other names are ignored. + +When an identifier is resolved as a *TypeName* (section [3.8.2](#3.8.2)), only names in scope with a type meaning are considered and other names are ignored. + +When an identifier is resolved as a *NamespaceName* (section [3.8.2](#3.8.2)), only names in scope with a namespace meaning are considered and other names are ignored. + +*TODO: [Include specific rules for alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*. + +Note that class and interface members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class or interface instance. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`. + +As the rules above imply, locally declared entities in a namespace are closer in scope than exported entities declared in other namespace declarations for the same namespace. For example: + +```TypeScript +var x = 1; +namespace M { + export var x = 2; + console.log(x); // 2 +} +namespace M { + console.log(x); // 2 +} +namespace M { + var x = 3; + console.log(x); // 3 +} +``` + +
+ +#
3 Types + +TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development. TypeScript's *static* compile-time type system closely models the *dynamic* run-time type system of JavaScript, allowing programmers to accurately express the type relationships that are expected to exist when their programs run and have those assumptions pre-validated by the TypeScript compiler. TypeScript's type analysis occurs entirely at compile-time and adds no run-time overhead to program execution. + +All types in TypeScript are subtypes of a single top type called the Any type. The `any` keyword references this type. The Any type is the one type that can represent *any* JavaScript value with no constraints. All other types are categorized as ***primitive types***, ***object types***, ***union types***, ***intersection types***, or ***type parameters***. These types introduce various static constraints on their values. + +The primitive types are the Number, Boolean, String, Symbol, Void, Null, and Undefined types along with user defined enum types. The `number`, `boolean`, `string`, `symbol`, and `void` keywords reference the Number, Boolean, String, Symbol, and Void primitive types respectively. The Void type exists purely to indicate the absence of a value, such as in a function with no return value. It is not possible to explicitly reference the Null and Undefined types—only *values* of those types can be referenced, using the `null` and `undefined` literals. + +The object types are all class, interface, array, tuple, function, and constructor types. Class and interface types are introduced through class and interface declarations and are referenced by the name given to them in their declarations. Class and interface types may be ***generic types*** which have one or more type parameters. + +Union types represent values that have one of multiple types, and intersection types represent values that simultaneously have more than one type. + +Declarations of classes, properties, functions, variables and other language entities associate types with those entities. The mechanism by which a type is formed and associated with a language entity depends on the particular kind of entity. For example, a namespace declaration associates the namespace with an anonymous type containing a set of properties corresponding to the exported variables and functions in the namespace, and a function declaration associates the function with an anonymous type containing a call signature corresponding to the parameters and return type of the function. Types can be associated with variables through explicit ***type annotations***, such as + +```TypeScript +var x: number; +``` + +or through implicit ***type inference***, as in + +```TypeScript +var x = 1; +``` + +which infers the type of 'x' to be the Number primitive type because that is the type of the value used to initialize 'x'. + +## 3.1 The Any Type + +The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list. + +The `any` keyword references the Any type. In general, in places where a type is not explicitly provided and TypeScript cannot infer one, the Any type is assumed. + +The Any type is a supertype of all types, and is assignable to and from all types. + +Some examples: + +```TypeScript +var x: any; // Explicitly typed +var y; // Same as y: any +var z: { a; b; }; // Same as z: { a: any; b: any; } + +function f(x) { // Same as f(x: any): void + console.log(x); +} +``` + +## 3.2 Primitive Types + +The primitive types are the Number, Boolean, String, Symbol, Void, Null, and Undefined types and all user defined enum types. + +### 3.2.1 The Number Type + +The Number primitive type corresponds to the similarly named JavaScript primitive type and represents double-precision 64-bit format IEEE 754 floating point values. + +The `number` keyword references the Number primitive type and numeric literals may be used to write values of the Number primitive type. + +For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Number primitive type behaves as an object type with the same properties as the global interface type 'Number'. + +Some examples: + +```TypeScript +var x: number; // Explicitly typed +var y = 0; // Same as y: number = 0 +var z = 123.456; // Same as z: number = 123.456 +var s = z.toFixed(2); // Property of Number interface +``` + +### 3.2.2 The Boolean Type + +The Boolean primitive type corresponds to the similarly named JavaScript primitive type and represents logical values that are either true or false. + +The `boolean` keyword references the Boolean primitive type and the `true` and `false` literals reference the two Boolean truth values. + +For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Boolean primitive type behaves as an object type with the same properties as the global interface type 'Boolean'. + +Some examples: + +```TypeScript +var b: boolean; // Explicitly typed +var yes = true; // Same as yes: boolean = true +var no = false; // Same as no: boolean = false +``` + +### 3.2.3 The String Type + +The String primitive type corresponds to the similarly named JavaScript primitive type and represents sequences of characters stored as Unicode UTF-16 code units. + +The `string` keyword references the String primitive type and string literals may be used to write values of the String primitive type. + +For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the String primitive type behaves as an object type with the same properties as the global interface type 'String'. + +Some examples: + +```TypeScript +var s: string; // Explicitly typed +var empty = ""; // Same as empty: string = "" +var abc = 'abc'; // Same as abc: string = "abc" +var c = abc.charAt(2); // Property of String interface +``` + +### 3.2.4 The Symbol Type + +The Symbol primitive type corresponds to the similarly named JavaScript primitive type and represents unique tokens that may be used as keys for object properties. + +The `symbol` keyword references the Symbol primitive type. Symbol values are obtained using the global object 'Symbol' which has a number of methods and properties and can be invoked as a function. In particular, the global object 'Symbol' defines a number of well-known symbols ([2.2.3](#2.2.3)) that can be used in a manner similar to identifiers. Note that the 'Symbol' object is available only in ECMAScript 2015 environments. + +For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Symbol primitive type behaves as an object type with the same properties as the global interface type 'Symbol'. + +Some examples: + +```TypeScript +var secretKey = Symbol(); +var obj = {}; +obj[secretKey] = "secret message"; // Use symbol as property key +obj[Symbol.toStringTag] = "test"; // Use of well-known symbol +``` + +### 3.2.5 The Void Type + +The Void type, referenced by the `void` keyword, represents the absence of a value and is used as the return type of functions with no return value. + +The only possible values for the Void type are `null` and `undefined`. The Void type is a subtype of the Any type and a supertype of the Null and Undefined types, but otherwise Void is unrelated to all other types. + +*NOTE: We might consider disallowing declaring variables of type Void as they serve no useful purpose. However, because Void is permitted as a type argument to a generic type or function it is not feasible to disallow Void properties or parameters*. + +### 3.2.6 The Null Type + +The Null type corresponds to the similarly named JavaScript primitive type and is the type of the `null` literal. + +The `null` literal references the one and only value of the Null type. It is not possible to directly reference the Null type itself. + +The Null type is a subtype of all types, except the Undefined type. This means that `null` is considered a valid value for all primitive types, object types, union types, intersection types, and type parameters, including even the Number and Boolean primitive types. + +Some examples: + +```TypeScript +var n: number = null; // Primitives can be null +var x = null; // Same as x: any = null +var e: Null; // Error, can't reference Null type +``` + +### 3.2.7 The Undefined Type + +The Undefined type corresponds to the similarly named JavaScript primitive type and is the type of the `undefined` literal. + +The `undefined` literal denotes the value given to all uninitialized variables and is the one and only value of the Undefined type. It is not possible to directly reference the Undefined type itself. + +The undefined type is a subtype of all types. This means that `undefined` is considered a valid value for all primitive types, object types, union types, intersection types, and type parameters. + +Some examples: + +```TypeScript +var n: number; // Same as n: number = undefined +var x = undefined; // Same as x: any = undefined +var e: Undefined; // Error, can't reference Undefined type +``` + +### 3.2.8 Enum Types + +Enum types are distinct user defined subtypes of the Number primitive type. Enum types are declared using enum declarations (section [9.1](#9.1)) and referenced using type references (section [3.8.2](#3.8.2)). + +Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other. + +### 3.2.9 String Literal Types + +Specialized signatures (section [3.9.2.4](#3.9.2.4)) permit string literals to be used as types in parameter type annotations. String literal types are permitted only in that context and nowhere else. + +All string literal types are subtypes of the String primitive type. + +*TODO: Update to reflect [expanded support for string literal types](https://github.com/Microsoft/TypeScript/pull/5185)*. + +## 3.3 Object Types + +Object types are composed from properties, call signatures, construct signatures, and index signatures, collectively called members. + +Class and interface type references, array types, tuple types, function types, and constructor types are all classified as object types. Multiple constructs in the TypeScript language create object types, including: + +* Object type literals (section [3.8.3](#3.8.3)). +* Array type literals (section [3.8.4](#3.8.4)). +* Tuple type literals (section [3.8.5](#3.8.5)). +* Function type literals (section [3.8.8](#3.8.8)). +* Constructor type literals (section [3.8.9](#3.8.9)). +* Object literals (section [4.5](#4.5)). +* Array literals (section [4.6](#4.6)). +* Function expressions (section [4.10](#4.10)) and function declarations ([6.1](#6.1)). +* Constructor function types created by class declarations (section [8.2.5](#8.2.5)). +* Namespace instance types created by namespace declarations (section [10.3](#10.3)). + +### 3.3.1 Named Type References + +Type references (section [3.8.2](#3.8.2)) to class and interface types are classified as object types. Type references to generic class and interface types include type arguments that are substituted for the type parameters of the class or interface to produce an actual object type. + +### 3.3.2 Array Types + +***Array types*** represent JavaScript arrays with a common element type. Array types are named type references created from the generic interface type 'Array' in the global namespace with the array element type as a type argument. Array type literals (section [3.8.4](#3.8.4)) provide a shorthand notation for creating such references. + +The declaration of the 'Array' interface includes a property 'length' and a numeric index signature for the element type, along with other members: + +```TypeScript +interface Array { + length: number; + [x: number]: T; + // Other members +} +``` + +Array literals (section [4.6](#4.6)) may be used to create values of array types. For example + +```TypeScript +var a: string[] = ["hello", "world"]; +``` + +A type is said to be an ***array-like type*** if it is assignable (section [3.11.4](#3.11.4)) to the type `any[]`. + +### 3.3.3 Tuple Types + +***Tuple types*** represent JavaScript arrays with individually tracked element types. Tuple types are written using tuple type literals (section [3.8.5](#3.8.5)). A tuple type combines a set of numerically named properties with the members of an array type. Specifically, a tuple type + +```TypeScript +[ T0, T1, ..., Tn ] +``` + +combines the set of properties + +```TypeScript +{ + 0: T0; + 1: T1; + ... + n: Tn; +} +``` + +with the members of an array type whose element type is the union type (section [3.4](#3.4)) of the tuple element types. + +Array literals (section [4.6](#4.6)) may be used to create values of tuple types. For example: + +```TypeScript +var t: [number, string] = [3, "three"]; +var n = t[0]; // Type of n is number +var s = t[1]; // Type of s is string +var i: number; +var x = t[i]; // Type of x is number | string +``` + +Named tuple types can be created by declaring interfaces that derive from Array<T> and introduce numerically named properties. For example: + +```TypeScript +interface KeyValuePair extends Array { 0: K; 1: V; } + +var x: KeyValuePair = [10, "ten"]; +``` + +A type is said to be a ***tuple-like type*** if it has a property with the numeric name '0'. + +### 3.3.4 Function Types + +An object type containing one or more call signatures is said to be a ***function type***. Function types may be written using function type literals (section [3.8.8](#3.8.8)) or by including call signatures in object type literals. + +### 3.3.5 Constructor Types + +An object type containing one or more construct signatures is said to be a ***constructor type***. Constructor types may be written using constructor type literals (section [3.8.9](#3.8.9)) or by including construct signatures in object type literals. + +### 3.3.6 Members + +Every object type is composed from zero or more of the following kinds of members: + +* ***Properties***, which define the names and types of the properties of objects of the given type. Property names are unique within their type. +* ***Call signatures***, which define the possible parameter lists and return types associated with applying call operations to objects of the given type. +* ***Construct signatures***, which define the possible parameter lists and return types associated with applying the `new` operator to objects of the given type. +* ***Index signatures***, which define type constraints for properties in the given type. An object type can have at most one string index signature and one numeric index signature. + +Properties are either ***public***, ***private***, or ***protected*** and are either ***required*** or ***optional***: + +* Properties in a class declaration may be designated public, private, or protected, while properties declared in other contexts are always considered public. Private members are only accessible within their declaring class, as described in section [8.2.2](#8.2.2), and private properties match only themselves in subtype and assignment compatibility checks, as described in section [3.11](#3.11). Protected members are only accessible within their declaring class and classes derived from it, as described in section [8.2.2](#8.2.2), and protected properties match only themselves and overrides in subtype and assignment compatibility checks, as described in section [3.11](#3.11). +* Properties in an object type literal or interface declaration may be designated required or optional, while properties declared in other contexts are always considered required. Properties that are optional in the target type of an assignment may be omitted from source objects, as described in section [3.11.4](#3.11.4). + +Call and construct signatures may be ***specialized*** (section [3.9.2.4](#3.9.2.4)) by including parameters with string literal types. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. + +## 3.4 Union Types + +***Union types*** represent values that may have one of several distinct representations. A value of a union type *A* | *B* is a value that is *either* of type *A* or type *B*. Union types are written using union type literals (section [3.8.6](#3.8.6)). + +A union type encompasses an ordered set of constituent types. While it is generally true that *A* | *B* is equivalent to *B* | *A*, the order of the constituent types may matter when determining the call and construct signatures of the union type. + +Union types have the following subtype relationships: + +* A union type *U* is a subtype of a type *T* if each type in *U* is a subtype of *T*. +* A type *T* is a subtype of a union type *U* if *T* is a subtype of any type in *U*. + +Similarly, union types have the following assignability relationships: + +* A union type *U* is assignable to a type *T* if each type in *U* is assignable to *T*. +* A type *T* is assignable to a union type *U* if *T* is assignable to any type in *U*. + +The || and conditional operators (section [4.19.7](#4.19.7) and [4.20](#4.20)) may produce values of union types, and array literals (section [4.6](#4.6)) may produce array values that have union types as their element types. + +Type guards (section [4.24](#4.24)) may be used to narrow a union type to a more specific type. In particular, type guards are useful for narrowing union type values to a non-union type values. + +In the example + +```TypeScript +var x: string | number; +var test: boolean; +x = "hello"; // Ok +x = 42; // Ok +x = test; // Error, boolean not assignable +x = test ? 5 : "five"; // Ok +x = test ? 0 : false; // Error, number | boolean not assignable +``` + +it is possible to assign 'x' a value of type `string`, `number`, or the union type `string | number`, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either `string` or `number`: + +```TypeScript +var n = typeof x === "string" ? x.length : x; // Type of n is number +``` + +For purposes of property access and function calls, the apparent members (section [3.11.1](#3.11.1)) of a union type are those that are present in every one of its constituent types, with types that are unions of the respective apparent members in the constituent types. The following example illustrates the merging of member types that occurs when union types are created from object types. + +```TypeScript +interface A { + a: string; + b: number; +} + +interface B { + a: number; + b: number; + c: number; +} + +var x: A | B; +var a = x.a; // a has type string | number +var b = x.b; // b has type number +var c = x.c; // Error, no property c in union type +``` + +Note that 'x.a' has a union type because the type of 'a' is different in 'A' and 'B', whereas 'x.b' simply has type number because that is the type of 'b' in both 'A' and 'B'. Also note that there is no property 'x.c' because only 'B' has a property 'c'. + +When used as a contextual type (section [4.23](#4.23)), a union type has those members that are present in any of its constituent types, with types that are unions of the respective members in the constituent types. Specifically, a union type used as a contextual type has the apparent members defined in section [3.11.1](#3.11.1), except that a particular member need only be present in one or more constituent types instead of all constituent types. + +## 3.5 Intersection Types + +***Intersection types*** represent values that simultaneously have multiple types. A value of an intersection type *A* & *B* is a value that is *both* of type *A* and type *B*. Intersection types are written using intersection type literals (section [3.8.7](#3.8.7)). + +An intersection type encompasses an ordered set of constituent types. While it is generally true that *A* & *B* is equivalent to *B* & *A*, the order of the constituent types may matter when determining the call and construct signatures of the intersection type. + +Intersection types have the following subtype relationships: + +* An intersection type *I* is a subtype of a type *T* if any type in *I* is a subtype of *T*. +* A type *T* is a subtype of an intersection type *I* if *T* is a subtype of each type in *I*. + +Similarly, intersection types have the following assignability relationships: + +* An intersection type *I* is assignable to a type *T* if any type in *I* is assignable to *T*. +* A type *T* is assignable to an intersection type *I* if *T* is assignable to each type in *I*. + +For purposes of property access and function calls, the apparent members (section [3.11.1](#3.11.1)) of an intersection type are those that are present in one or more of its constituent types, with types that are intersections of the respective apparent members in the constituent types. The following examples illustrate the merging of member types that occurs when intersection types are created from object types. + +```TypeScript +interface A { a: number } +interface B { b: number } + +var ab: A & B = { a: 1, b: 1 }; +var a: A = ab; // A & B assignable to A +var b: B = ab; // A & B assignable to B + +interface X { p: A } +interface Y { p: B } + +var xy: X & Y = { p: ab }; // X & Y has property p of type A & B + +type F1 = (a: string, b: string) => void; +type F2 = (a: number, b: number) => void; + +var f: F1 & F2 = (a: string | number, b: string | number) => { }; +f("hello", "world"); // Ok +f(1, 2); // Ok +f(1, "test"); // Error +``` + +The union and intersection type operators can be applied to type parameters. This capability can for example be used to model functions that merge objects: + +```TypeScript +function extend(first: T, second: U): T & U { + // Extend first with properties of second +} + +var x = extend({ a: "hello" }, { b: 42 }); +var s = x.a; +var n = x.b; +``` + +It is possible to create intersection types for which no values other than null or undefined are possible. For example, intersections of primitive types such as `string & number` fall into this category. + +## 3.6 Type Parameters + +A type parameter represents an actual type that the parameter is bound to in a generic type reference or a generic function call. Type parameters have constraints that establish upper bounds for their actual type arguments. + +Since a type parameter represents a multitude of different type arguments, type parameters have certain restrictions compared to other types. In particular, a type parameter cannot be used as a base class or interface. + +### 3.6.1 Type Parameter Lists + +Class, interface, type alias, and function declarations may optionally include lists of type parameters enclosed in < and > brackets. Type parameters are also permitted in call signatures of object, function, and constructor type literals. + +  *TypeParameters:* +   `<` *TypeParameterList* `>` + +  *TypeParameterList:* +   *TypeParameter* +   *TypeParameterList* `,` *TypeParameter* + +  *TypeParameter:* +   *BindingIdentifier* *Constraintopt* + +  *Constraint:* +   `extends` *Type* + +Type parameter names must be unique. A compile-time error occurs if two or more type parameters in the same *TypeParameterList* have the same name. + +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. + +A type parameter may have an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Type parameters may be referenced in type parameter constraints within the same type parameter list, including even constraint declarations that occur to the left of the type parameter. + +The ***base constraint*** of a type parameter *T* is defined as follows: + +* If *T* has no declared constraint, *T*'s base constraint is the empty object type `{}`. +* If *T*'s declared constraint is a type parameter, *T*'s base constraint is that of the type parameter. +* Otherwise, *T*'s base constraint is *T*'s declared constraint. + +In the example + +```TypeScript +interface G { } +``` + +the base constraint of 'T' is the empty object type and the base constraint of 'U' and 'V' is 'Function'. + +For purposes of determining type relationships (section [3.11](#3.11)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)), type parameters appear to have the members of their base constraint, but no other members. + +It is an error for a type parameter to directly or indirectly be a constraint for itself. For example, both of the following declarations are invalid: + +```TypeScript +interface A { } + +interface B { } +``` + +### 3.6.2 Type Argument Lists + +A type reference (section [3.8.2](#3.8.2)) to a generic type must include a list of type arguments enclosed in angle brackets and separated by commas. Similarly, a call (section [4.15](#4.15)) to a generic function may explicitly include a type argument list instead of relying on type inference. + +  *TypeArguments:* +   `<` *TypeArgumentList* `>` + +  *TypeArgumentList:* +   *TypeArgument* +   *TypeArgumentList* `,` *TypeArgument* + +  *TypeArgument:* +   *Type* + +Type arguments correspond one-to-one with type parameters of the generic type or function being referenced. A type argument list is required to specify exactly one type argument for each corresponding type parameter, and each type argument for a constrained type parameter is required to ***satisfy*** the constraint of that type parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section [3.11.4](#3.11.4)) the constraint type once type arguments are substituted for type parameters. + +Given the declaration + +```TypeScript +interface G { } +``` + +a type reference of the form 'G<A, B>' places no requirements on 'A' but requires 'B' to be assignable to 'Function'. + +The process of substituting type arguments for type parameters in a generic type or generic signature is known as ***instantiating*** the generic type or signature. Instantiation of a generic type or signature can fail if the supplied type arguments do not satisfy the constraints of their corresponding type parameters. + +### 3.6.3 This-types + +Every class and interface has a ***this-type*** that represents the actual type of instances of the class or interface within the declaration of the class or interface. The this-type is referenced using the keyword `this` in a type position. Within instance methods and constructors of a class, the type of the expression `this` (section [4.2](#4.2)) is the this-type of the class. + +Classes and interfaces support inheritance and therefore the instance represented by `this` in a method isn't necessarily an instance of the containing class—it may in fact be an instance of a derived class or interface. To model this relationship, the this-type of a class or interface is classified as a type parameter. Unlike other type parameters, it is not possible to explicitly pass a type argument for a this-type. Instead, in a type reference to a class or interface type, the type reference *itself* is implicitly passed as a type argument for the this-type. For example: + +```TypeScript +class A { + foo() { + return this; + } +} + +class B extends A { + bar() { + return this; + } +} + +let b: B; +let x = b.foo().bar(); // Fluent pattern works, type of x is B +``` + +In the declaration of `b` above, the type reference `B` is itself passed as a type argument for B's this-type. Thus, the referenced type is an instantiation of class `B` where all occurrences of the type `this` are replaced with `B`, and for that reason the `foo` method of `B` actually returns `B` (as opposed to `A`). + +The this-type of a given class or interface type *C* implicitly has a constraint consisting of a type reference to *C* with *C*'s own type parameters passed as type arguments and with that type reference passed as the type argument for the this-type. + +## 3.7 Named Types + +Classes, interfaces, enums, and type aliases are ***named types*** that are introduced through class declarations (section [8.1](#8.1)), interface declarations (section [7.1](#7.1)), enum declarations ([9.1](#9.1)), and type alias declarations (section [3.10](#3.10)). Classes, interfaces, and type aliases may have type parameters and are then called ***generic types***. Conversely, named types without type parameters are called ***non-generic types***. + +Interface declarations only introduce named types, whereas class declarations introduce named types *and* constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can't declare optional members and interfaces can't declare private or protected members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations. + +Named types are referenced through ***type references*** (section [3.8.2](#3.8.2)) that specify a type name and, if applicable, the type arguments to be substituted for the type parameters of the named type. + +Named types are technically not types—only *references* to named types are. This distinction is particularly evident with generic types: Generic types are "templates" from which multiple *actual* types can be created by writing type references that supply type arguments to substitute in place of the generic type's type parameters. This substitution process is known as ***instantiating*** a generic type. Only once a generic type is instantiated does it denote an actual type. + +TypeScript has a structural type system, and therefore an instantiation of a generic type is indistinguishable from an equivalent manually written expansion. For example, given the declaration + +```TypeScript +interface Pair { first: T1; second: T2; } +``` + +the type reference + +```TypeScript +Pair +``` + +is indistinguishable from the type + +```TypeScript +{ first: string; second: Entity; } +``` + +## 3.8 Specifying Types + +Types are specified either by referencing their keyword or name, or by writing object type literals, array type literals, tuple type literals, function type literals, constructor type literals, or type queries. + +  *Type:* +   *UnionOrIntersectionOrPrimaryType* +   *FunctionType* +   *ConstructorType* + +  *UnionOrIntersectionOrPrimaryType:* +   *UnionType* +   *IntersectionOrPrimaryType* + +  *IntersectionOrPrimaryType:* +   *IntersectionType* +   *PrimaryType* + +  *PrimaryType:* +   *ParenthesizedType* +   *PredefinedType* +   *TypeReference* +   *ObjectType* +   *ArrayType* +   *TupleType* +   *TypeQuery* +   *ThisType* + +  *ParenthesizedType:* +   `(` *Type* `)` + +Parentheses are required around union, intersection, function, or constructor types when they are used as array element types; around union, function, or constructor types in intersection types; and around function or constructor types in union types. For example: + +```TypeScript +(string | number)[] +((x: string) => string) | ((x: number) => number) +(A | B) & (C | D) +``` + +The different forms of type notations are described in the following sections. + +### 3.8.1 Predefined Types + +The `any`, `number`, `boolean`, `string`, `symbol` and `void` keywords reference the Any type and the Number, Boolean, String, Symbol, and Void primitive types respectively. + +  *PredefinedType:* +   `any` +   `number` +   `boolean` +   `string` +   `symbol` +   `void` + +The predefined type keywords are reserved and cannot be used as names of user defined types. + +### 3.8.2 Type References + +A type reference references a named type or type parameter through its name and, in the case of a generic type, supplies a type argument list. + +  *TypeReference:* +   *TypeName* *[no LineTerminator here]* *TypeArgumentsopt* + +  *TypeName:* +   *IdentifierReference* +   *NamespaceName* `.` *IdentifierReference* + +  *NamespaceName:* +   *IdentifierReference* +   *NamespaceName* `.` *IdentifierReference* + +A *TypeReference* consists of a *TypeName* that a references a named type or type parameter. A reference to a generic type must be followed by a list of *TypeArguments* (section [3.6.2](#3.6.2)). + +A *TypeName* is either a single identifier or a sequence of identifiers separated by dots. In a type name, all identifiers but the last one refer to namespaces and the last identifier refers to a named type. + +Resolution of a *TypeName* consisting of a single identifier is described in section [2.4](#2.4). + +Resolution of a *TypeName* of the form *N.X*, where *N* is a *NamespaceName* and *X* is an *IdentifierReference*, proceeds by first resolving the namespace name *N*. If the resolution of *N* is successful and the export member set (sections [10.4](#10.4) and [11.3.4.4](#11.3.4.4)) of the resulting namespace contains a named type *X*, then *N.X* refers to that member. Otherwise, *N.X* is undefined. + +Resolution of a *NamespaceName* consisting of a single identifier is described in section [2.4](#2.4). Identifiers declared in namespace declarations (section [10.1](#10.1)) or import declarations (sections [10.3](#10.3), [11.3.2](#11.3.2), and [11.3.3](#11.3.3)) may be classified as namespaces. + +Resolution of a *NamespaceName* of the form *N.X*, where *N* is a *NamespaceName* and *X* is an *IdentifierReference*, proceeds by first resolving the namespace name *N*. If the resolution of *N* is successful and the export member set (sections [10.4](#10.4) and [11.3.4.4](#11.3.4.4)) of the resulting namespace contains an exported namespace member *X*, then *N.X* refers to that member. Otherwise, *N.X* is undefined. + +A type reference to a generic type is required to specify exactly one type argument for each type parameter of the referenced generic type, and each type argument must be assignable to (section [3.11.4](#3.11.4)) the constraint of the corresponding type parameter or otherwise an error occurs. An example: + +```TypeScript +interface A { a: string; } + +interface B extends A { b: string; } + +interface C extends B { c: string; } + +interface G { + x: T; + y: U; +} + +var v1: G; // Ok +var v2: G<{ a: string }, C>; // Ok, equivalent to G +var v3: G; // Error, A not valid argument for U +var v4: G, C>; // Ok +var v5: G; // Ok +var v6: G; // Error, wrong number of arguments +var v7: G; // Error, no arguments +``` + +A type argument is simply a *Type* and may itself be a type reference to a generic type, as demonstrated by 'v4' in the example above. + +As described in section [3.7](#3.7), a type reference to a generic type *G* designates a type wherein all occurrences of *G*'s type parameters have been replaced with the actual type arguments supplied in the type reference. For example, the declaration of 'v1' above is equivalent to: + +```TypeScript +var v1: { + x: { a: string; } + y: { a: string; b: string; c: string }; +}; +``` + +### 3.8.3 Object Type Literals + +An object type literal defines an object type by specifying the set of members that are statically considered to be present in instances of the type. Object type literals can be given names using interface declarations but are otherwise anonymous. + +  *ObjectType:* +   `{` *TypeBodyopt* `}` + +  *TypeBody:* +   *TypeMemberList* `;`*opt* +   *TypeMemberList* `,`*opt* + +  *TypeMemberList:* +   *TypeMember* +   *TypeMemberList* `;` *TypeMember* +   *TypeMemberList* `,` *TypeMember* + +  *TypeMember:* +   *PropertySignature* +   *CallSignature* +   *ConstructSignature* +   *IndexSignature* +   *MethodSignature* + +The members of an object type literal are specified as a combination of property, call, construct, index, and method signatures. Object type members are described in section [3.9](#3.9). + +### 3.8.4 Array Type Literals + +An array type literal is written as an element type followed by an open and close square bracket. + +  *ArrayType:* +   *PrimaryType* *[no LineTerminator here]* `[` `]` + +An array type literal references an array type (section [3.3.2](#3.3.2)) with the given element type. An array type literal is simply shorthand notation for a reference to the generic interface type 'Array' in the global namespace with the element type as a type argument. + +When union, intersection, function, or constructor types are used as array element types they must be enclosed in parentheses. For example: + +```TypeScript +(string | number)[] +(() => string)[] +``` + +Alternatively, array types can be written using the 'Array<T>' notation. For example, the types above are equivalent to + +```TypeScript +Array +Array<() => string> +``` + +### 3.8.5 Tuple Type Literals + +A tuple type literal is written as a sequence of element types, separated by commas and enclosed in square brackets. + +  *TupleType:* +   `[` *TupleElementTypes* `]` + +  *TupleElementTypes:* +   *TupleElementType* +   *TupleElementTypes* `,` *TupleElementType* + +  *TupleElementType:* +   *Type* + +A tuple type literal references a tuple type (section [3.3.3](#3.3.3)). + +### 3.8.6 Union Type Literals + +A union type literal is written as a sequence of types separated by vertical bars. + +  *UnionType:* +   *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType* + +A union type literal references a union type (section [3.4](#3.4)). + +### 3.8.7 Intersection Type Literals + +An intersection type literal is written as a sequence of types separated by ampersands. + +  *IntersectionType:* +   *IntersectionOrPrimaryType* `&` *PrimaryType* + +An intersection type literal references an intersection type (section [3.5](#3.5)). + +### 3.8.8 Function Type Literals + +A function type literal specifies the type parameters, regular parameters, and return type of a call signature. + +  *FunctionType:* +   *TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type* + +A function type literal is shorthand for an object type containing a single call signature. Specifically, a function type literal of the form + +```TypeScript +< T1, T2, ... > ( p1, p2, ... ) => R +``` + +is exactly equivalent to the object type literal + +```TypeScript +{ < T1, T2, ... > ( p1, p2, ... ) : R } +``` + +Note that function types with multiple call or construct signatures cannot be written as function type literals but must instead be written as object type literals. + +### 3.8.9 Constructor Type Literals + +A constructor type literal specifies the type parameters, regular parameters, and return type of a construct signature. + +  *ConstructorType:* +   `new` *TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type* + +A constructor type literal is shorthand for an object type containing a single construct signature. Specifically, a constructor type literal of the form + +```TypeScript +new < T1, T2, ... > ( p1, p2, ... ) => R +``` + +is exactly equivalent to the object type literal + +```TypeScript +{ new < T1, T2, ... > ( p1, p2, ... ) : R } +``` + +Note that constructor types with multiple construct signatures cannot be written as constructor type literals but must instead be written as object type literals. + +### 3.8.10 Type Queries + +A type query obtains the type of an expression. + +  *TypeQuery:* +   `typeof` *TypeQueryExpression* + +  *TypeQueryExpression:* +   *IdentifierReference* +   *TypeQueryExpression* `.` *IdentifierName* + +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. The expression is processed as an identifier expression (section [4.3](#4.3)) or property access expression (section [4.13](#4.13)), the widened type (section [3.12](#3.12)) of which becomes the result. Similar to other static typing constructs, type queries are erased from the generated JavaScript code and add no run-time overhead. + +Type queries are useful for capturing anonymous types that are generated by various constructs such as object literals, function declarations, and namespace declarations. For example: + +```TypeScript +var a = { x: 10, y: 20 }; +var b: typeof a; +``` + +Above, 'b' is given the same type as 'a', namely `{ x: number; y: number; }`. + +If a declaration includes a type annotation that references the entity being declared through a circular path of type queries or type references containing type queries, the resulting type is the Any type. For example, all of the following variables are given the type Any: + +```TypeScript +var c: typeof c; +var d: typeof e; +var e: typeof d; +var f: Array; +``` + +However, if a circular path of type queries includes at least one *ObjectType*, *FunctionType* or *ConstructorType*, the construct denotes a recursive type: + +```TypeScript +var g: { x: typeof g; }; +var h: () => typeof h; +``` + +Here, 'g' and 'g.x' have the same recursive type, and likewise 'h' and 'h()' have the same recursive type. + +### 3.8.11 This-Type References + +The `this` keyword is used to reference the this-type (section [3.6.3](#3.6.3)) of a class or interface. + +  *ThisType:* +   `this` + +The meaning of a *ThisType* depends on the closest enclosing *FunctionDeclaration*, *FunctionExpression*, *PropertyDefinition*, *ClassElement*, or *TypeMember*, known as the root declaration of the *ThisType*, as follows: + +* When the root declaration is an instance member or constructor of a class, the *ThisType* references the this-type of that class. +* When the root declaration is a member of an interface type, the *ThisType* references the this-type of that interface. +* Otherwise, the *ThisType* is an error. + +Note that in order to avoid ambiguities it is not possible to reference the this-type of a class or interface in a nested object type literal. In the example + +```TypeScript +interface ListItem { + getHead(): this; + getTail(): this; + getHeadAndTail(): { head: this, tail: this }; // Error +} +``` + +the `this` references on the last line are in error because their root declarations are not members of a class or interface. The recommended way to reference the this-type of an outer class or interface in an object type literal is to declare an intermediate generic type and pass `this` as a type argument. For example: + +```TypeScript +type HeadAndTail = { head: T, tail: T }; + +interface ListItem { + getHead(): this; + getTail(): this; + getHeadAndTail(): HeadAndTail; +} +``` + +## 3.9 Specifying Members + +The members of an object type literal (section [3.8.3](#3.8.3)) are specified as a combination of property, call, construct, index, and method signatures. + +### 3.9.1 Property Signatures + +A property signature declares the name and type of a property member. + +  *PropertySignature:* +   *PropertyName* `?`*opt* *TypeAnnotationopt* + +  *TypeAnnotation:* +   `:` *Type* + +The *PropertyName* ([2.2.2](#2.2.2)) of a property signature must be unique within its containing type, and must denote a well-known symbol if it is a computed property name ([2.2.3](#2.2.3)). If the property name is followed by a question mark, the property is optional. Otherwise, the property is required. + +If a property signature omits a *TypeAnnotation*, the Any type is assumed. + +### 3.9.2 Call Signatures + +A call signature defines the type parameters, parameter list, and return type associated with applying a call operation (section [4.15](#4.15)) to an instance of the containing type. A type may ***overload*** call operations by defining multiple different call signatures. + +  *CallSignature:* +   *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt* + +A call signature that includes *TypeParameters* (section [3.6.1](#3.6.1)) is called a ***generic call signature***. Conversely, a call signature with no *TypeParameters* is called a non-generic call signature. + +As well as being members of object type literals, call signatures occur in method signatures (section [3.9.5](#3.9.5)), function expressions (section [4.10](#4.10)), and function declarations (section [6.1](#6.1)). + +An object type containing call signatures is said to be a ***function type***. + +#### 3.9.2.1 Type Parameters + +Type parameters (section [3.6.1](#3.6.1)) in call signatures provide a mechanism for expressing the relationships of parameter and return types in call operations. For example, a signature might introduce a type parameter and use it as both a parameter type and a return type, in effect describing a function that returns a value of the same type as its argument. + +Type parameters may be referenced in parameter types and return type annotations, but not in type parameter constraints, of the call signature in which they are introduced. + +Type arguments (section [3.6.2](#3.6.2)) for call signature type parameters may be explicitly specified in a call operation or may, when possible, be inferred (section [4.15.2](#4.15.2)) from the types of the regular arguments in the call. An ***instantiation*** of a generic call signature for a particular set of type arguments is the call signature formed by replacing each type parameter with its corresponding type argument. + +Some examples of call signatures with type parameters follow below. + +A function taking an argument of any type, returning a value of that same type: + +```TypeScript +(x: T): T +``` + +A function taking two values of the same type, returning an array of that type: + +```TypeScript +(x: T, y: T): T[] +``` + +A function taking two arguments of different types, returning an object with properties 'x' and 'y' of those types: + +```TypeScript +(x: T, y: U): { x: T; y: U; } +``` + +A function taking an array of one type and a function argument, returning an array of another type, where the function argument takes a value of the first array element type and returns a value of the second array element type: + +```TypeScript +(a: T[], f: (x: T) => U): U[] +``` + +#### 3.9.2.2 Parameter List + +A signature's parameter list consists of zero or more required parameters, followed by zero or more optional parameters, finally followed by an optional rest parameter. + +  *ParameterList:* +   *RequiredParameterList* +   *OptionalParameterList* +   *RestParameter* +   *RequiredParameterList* `,` *OptionalParameterList* +   *RequiredParameterList* `,` *RestParameter* +   *OptionalParameterList* `,` *RestParameter* +   *RequiredParameterList* `,` *OptionalParameterList* `,` *RestParameter* + +  *RequiredParameterList:* +   *RequiredParameter* +   *RequiredParameterList* `,` *RequiredParameter* + +  *RequiredParameter:* +   *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* +   *BindingIdentifier* `:` *StringLiteral* + +  *AccessibilityModifier:* +   `public` +   `private` +   `protected` + +  *BindingIdentifierOrPattern:* +   *BindingIdentifier* +   *BindingPattern* + +  *OptionalParameterList:* +   *OptionalParameter* +   *OptionalParameterList* `,` *OptionalParameter* + +  *OptionalParameter:* +   *AccessibilityModifieropt* *BindingIdentifierOrPattern* `?` *TypeAnnotationopt* +   *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* *Initializer* +   *BindingIdentifier* `?` `:` *StringLiteral* + +  *RestParameter:* +   `...` *BindingIdentifier* *TypeAnnotationopt* + +A parameter declaration may specify either an identifier or a binding pattern ([5.2.2](#5.2.2)). The identifiers specified in parameter declarations and binding patterns in a parameter list must be unique within that parameter list. + +The type of a parameter in a signature is determined as follows: + +* If the declaration includes a type annotation, the parameter is of that type. +* Otherwise, if the declaration includes an initializer expression (which is permitted only when the parameter list occurs in conjunction with a function body), the parameter type is the widened form (section [3.12](#3.12)) of the type of the initializer expression. +* Otherwise, if the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section [5.2.3](#5.2.3)). +* Otherwise, if the parameter is a rest parameter, the parameter type is `any[]`. +* Otherwise, the parameter type is `any`. + +A parameter is permitted to include a `public`, `private`, or `protected` modifier only if it occurs in the parameter list of a *ConstructorImplementation* (section [8.3.1](#8.3.1)) and only if it doesn't specify a *BindingPattern*. + +A type annotation for a rest parameter must denote an array type. + +When a parameter type annotation specifies a string literal type, the containing signature is a specialized signature (section [3.9.2.4](#3.9.2.4)). Specialized signatures are not permitted in conjunction with a function body, i.e. the *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, and *ConstructorImplementation* grammar productions do not permit parameters with string literal types. + +A parameter can be marked optional by following its name or binding pattern with a question mark (`?`) or by including an initializer. Initializers (including binding property or element initializers) are permitted only when the parameter list occurs in conjunction with a function body, i.e. only in a *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, or *ConstructorImplementation* grammar production. + +*TODO: Update to reflect [binding parameter cannot be optional in implementation signature](https://github.com/Microsoft/TypeScript/issues/2797)*. + +*TODO: Update to reflect [required parameters support initializers](https://github.com/Microsoft/TypeScript/pull/4022)*. + +#### 3.9.2.3 Return Type + +If present, a call signature's return type annotation specifies the type of the value computed and returned by a call operation. A `void` return type annotation is used to indicate that a function has no return value. + +When a call signature with no return type annotation occurs in a context without a function body, the return type is assumed to be the Any type. + +When a call signature with no return type annotation occurs in a context that has a function body (specifically, a function implementation, a member function implementation, or a member accessor declaration), the return type is inferred from the function body as described in section [6.3](#6.3). + +#### 3.9.2.4 Specialized Signatures + +When a parameter type annotation specifies a string literal type (section [3.2.9](#3.2.9)), the containing signature is considered a specialized signature. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. For example, the declaration + +```TypeScript +interface Document { + createElement(tagName: "div"): HTMLDivElement; + createElement(tagName: "span"): HTMLSpanElement; + createElement(tagName: "canvas"): HTMLCanvasElement; + createElement(tagName: string): HTMLElement; +} +``` + +states that calls to 'createElement' with the string literals "div", "span", and "canvas" return values of type 'HTMLDivElement', 'HTMLSpanElement', and 'HTMLCanvasElement' respectively, and that calls with all other string expressions return values of type 'HTMLElement'. + +When writing overloaded declarations such as the one above it is important to list the non-specialized signature last. This is because overload resolution (section [4.15.1](#4.15.1)) processes the candidates in declaration order and picks the first one that matches. + +Every specialized call or construct signature in an object type must be assignable to at least one non-specialized call or construct signature in the same object type (where a call signature *A* is considered assignable to another call signature *B* if an object type containing only *A* would be assignable to an object type containing only *B*). For example, the 'createElement' property in the example above is of a type that contains three specialized signatures, all of which are assignable to the non-specialized signature in the type. + +### 3.9.3 Construct Signatures + +A construct signature defines the parameter list and return type associated with applying the `new` operator (section [4.14](#4.14)) to an instance of the containing type. A type may overload `new` operations by defining multiple construct signatures with different parameter lists. + +  *ConstructSignature:* +   `new` *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt* + +The type parameters, parameter list, and return type of a construct signature are subject to the same rules as a call signature. + +A type containing construct signatures is said to be a ***constructor type***. + +### 3.9.4 Index Signatures + +An index signature defines a type constraint for properties in the containing type. + +  *IndexSignature:* +   `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation* +   `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation* + +There are two kinds of index signatures: + +* ***String index signatures***, specified using index type `string`, define type constraints for all properties and numeric index signatures in the containing type. Specifically, in a type with a string index signature of type *T*, all properties and numeric index signatures must have types that are assignable to *T*. +* ***Numeric index signatures***, specified using index type `number`, define type constraints for all numerically named properties in the containing type. Specifically, in a type with a numeric index signature of type *T*, all numerically named properties must have types that are assignable to *T*. + +A ***numerically named property*** is a property whose name is a valid numeric literal. Specifically, a property with a name *N* for which ToString(ToNumber(*N*)) is identical to *N*, where ToString and ToNumber are the abstract operations defined in ECMAScript specification. + +An object type can contain at most one string index signature and one numeric index signature. + +Index signatures affect the determination of the type that results from applying a bracket notation property access to an instance of the containing type, as described in section [4.13](#4.13). + +### 3.9.5 Method Signatures + +A method signature is shorthand for declaring a property of a function type. + +  *MethodSignature:* +   *PropertyName* `?`*opt* *CallSignature* + +If the *PropertyName* is a computed property name ([2.2.3](#2.2.3)), it must specify a well-known symbol. If the *PropertyName* is followed by a question mark, the property is optional. Otherwise, the property is required. Only object type literals and interfaces can declare optional properties. + +A method signature of the form + +```TypeScript +f < T1, T2, ... > ( p1, p2, ... ) : R +``` + +is equivalent to the property declaration + +```TypeScript +f : { < T1, T2, ... > ( p1, p2, ... ) : R } +``` + +A literal type may ***overload*** a method by declaring multiple method signatures with the same name but differing parameter lists. Overloads must either all be required (question mark omitted) or all be optional (question mark included). A set of overloaded method signatures correspond to a declaration of a single property with a type composed from an equivalent set of call signatures. Specifically + +```TypeScript +f < T1, T2, ... > ( p1, p2, ... ) : R ; +f < U1, U2, ... > ( q1, q2, ... ) : S ; +... +``` + +is equivalent to + +```TypeScript +f : { + < T1, T2, ... > ( p1, p2, ... ) : R ; + < U1, U2, ... > ( q1, q2, ... ) : S ; + ... +} ; +``` + +In the following example of an object type + +```TypeScript +{ + func1(x: number): number; // Method signature + func2: (x: number) => number; // Function type literal + func3: { (x: number): number }; // Object type literal +} +``` + +the properties 'func1', 'func2', and 'func3' are all of the same type, namely an object type with a single call signature taking a number and returning a number. Likewise, in the object type + +```TypeScript +{ + func4(x: number): number; + func4(s: string): string; + func5: { + (x: number): number; + (s: string): string; + }; +} +``` + +the properties 'func4' and 'func5' are of the same type, namely an object type with two call signatures taking and returning number and string respectively. + +## 3.10 Type Aliases + +A type alias declaration introduces a ***type alias*** in the containing declaration space. + +  *TypeAliasDeclaration:* +   `type` *BindingIdentifier* *TypeParametersopt* `=` *Type* `;` + +A type alias serves as an alias for the type specified in the type alias declaration. Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types. + +A type alias may optionally have type parameters (section [3.6.1](#3.6.1)) that serve as placeholders for actual types to be provided when the type alias is referenced in type references. A type alias with type parameters is called a ***generic type alias***. The type parameters of a generic type alias declaration are in scope and may be referenced in the aliased *Type*. + +Type aliases are referenced using type references ([3.8.2](#3.8.2)). Type references to generic type aliases produce instantiations of the aliased type with the given type arguments. Writing a reference to a non-generic type alias has exactly the same effect as writing the aliased type itself, and writing a reference to a generic type alias has exactly the same effect as writing the resulting instantiation of the aliased type. + +The *BindingIdentifier* of a type alias declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). + +It is an error for the type specified in a type alias to depend on that type alias. Types have the following dependencies: + +* A type alias *directly depends on* the type it aliases. +* A type reference *directly depends on* the referenced type and each of the type arguments, if any. +* A union or intersection type *directly depends on* each of the constituent types. +* An array type *directly depends on* its element type. +* A tuple type *directly depends on* each of its element types. +* A type query *directly depends on* the type of the referenced entity. + +Given this definition, the complete set of types upon which a type depends is the transitive closure of the *directly depends on* relationship. Note that object type literals, function type literals, and constructor type literals do not depend on types referenced within them and are therefore permitted to circularly reference themselves through type aliases. + +Some examples of type alias declarations: + +```TypeScript +type StringOrNumber = string | number; +type Text = string | { text: string }; +type NameLookup = Dictionary; +type ObjectStatics = typeof Object; +type Callback = (data: T) => void; +type Pair = [T, T]; +type Coordinates = Pair; +type Tree = T | { left: Tree, right: Tree }; +``` + +Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface type + +```TypeScript +interface Point { + x: number; + y: number; +} +``` + +could be written as the type alias + +```TypeScript +type Point = { + x: number; + y: number; +}; +``` + +However, doing so means the following capabilities are lost: + +* An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot. +* An interface can have multiple merged declarations, but a type alias for an object type literal cannot. + +## 3.11 Type Relationships + +Types in TypeScript have identity, subtype, supertype, and assignment compatibility relationships as defined in the following sections. + +### 3.11.1 Apparent Members + +The ***apparent members*** of a type are the members observed in subtype, supertype, and assignment compatibility relationships, as well as in the type checking of property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)). The apparent members of a type are determined as follows: + +* The apparent members of the primitive type Number and all enum types are the apparent members of the global interface type 'Number'. +* The apparent members of the primitive type Boolean are the apparent members of the global interface type 'Boolean'. +* The apparent members of the primitive type String and all string literal types are the apparent members of the global interface type 'String'. +* The apparent members of a type parameter are the apparent members of the constraint (section [3.6.1](#3.6.1)) of that type parameter. +* The apparent members of an object type *T* are the combination of the following: + * The declared and/or inherited members of *T*. + * The properties of the global interface type 'Object' that aren't hidden by properties with the same name in *T*. + * If *T* has one or more call or construct signatures, the properties of the global interface type 'Function' that aren't hidden by properties with the same name in *T*. +* The apparent members of a union type *U* are determined as follows: + * When all constituent types of *U* have an apparent property named *N*, *U* has an apparent property named *N* of a union type of the respective property types. + * When all constituent types of *U* have an apparent call signature with a parameter list *P*, *U* has an apparent call signature with the parameter list *P* and a return type that is a union of the respective return types. The call signatures appear in the same order as in the first constituent type. + * When all constituent types of *U* have an apparent construct signature with a parameter list *P*, *U* has an apparent construct signature with the parameter list *P* and a return type that is a union of the respective return types. The construct signatures appear in the same order as in the first constituent type. + * When all constituent types of *U* have an apparent string index signature, *U* has an apparent string index signature of a union type of the respective string index signature types. + * When all constituent types of *U* have an apparent numeric index signature, *U* has an apparent numeric index signature of a union type of the respective numeric index signature types. +* The apparent members of an intersection type *I* are determined as follows: + * When one of more constituent types of *I* have an apparent property named *N*, *I* has an apparent property named *N* of an intersection type of the respective property types. + * When one or more constituent types of *I* have a call signature *S*, *I* has the apparent call signature *S*. The signatures are ordered as a concatenation of the signatures of each constituent type in the order of the constituent types within *I*. + * When one or more constituent types of *I* have a construct signature *S*, *I* has the apparent construct signature *S*. The signatures are ordered as a concatenation of the signatures of each constituent type in the order of the constituent types within *I*. + * When one or more constituent types of *I* have an apparent string index signature, *I* has an apparent string index signature of an intersection type of the respective string index signature types. + * When one or more constituent types of *I* have an apparent numeric index signature, *I* has an apparent numeric index signature of an intersection type of the respective numeric index signature types. + +If a type is not one of the above, it is considered to have no apparent members. + +In effect, a type's apparent members make it a subtype of the 'Object' or 'Function' interface unless the type defines members that are incompatible with those of the 'Object' or 'Function' interface—which, for example, occurs if the type defines a property with the same name as a property in the 'Object' or 'Function' interface but with a type that isn't a subtype of that in the 'Object' or 'Function' interface. + +Some examples: + +```TypeScript +var o: Object = { x: 10, y: 20 }; // Ok +var f: Function = (x: number) => x * x; // Ok +var err: Object = { toString: 0 }; // Error +``` + +The last assignment is an error because the object literal has a 'toString' method that isn't compatible with that of 'Object'. + +### 3.11.2 Type and Member Identity + +Two types are considered ***identical*** when + +* they are both the Any type, +* they are the same primitive type, +* they are the same type parameter, +* they are union types with identical sets of constituent types, or +* they are intersection types with identical sets of constituent types, or +* they are object types with identical sets of members. + +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, +* they are identical call signatures, +* they are identical construct signatures, or +* they are index signatures of identical kind with identical types. + +Two call or construct signatures are considered identical when they have the same number of type parameters with identical type parameter constraints and, after substituting type Any for the type parameters introduced by the signatures, identical number of parameters with identical kind (required, optional or rest) and types, and identical return types. + +Note that, except for primitive types and classes with private or protected members, it is structure, not naming, of types that determines identity. Also, note that parameter names are not significant when determining identity of signatures. + +Private and protected properties match only if they originate in the same declaration and have identical types. Two distinct types might contain properties that originate in the same declaration if the types are separate parameterized references to the same generic class. In the example + +```TypeScript +class C { private x: T; } + +interface X { f(): string; } + +interface Y { f(): string; } + +var a: C; +var b: C; +``` + +the variables 'a' and 'b' are of identical types because the two type references to 'C' create types with a private member 'x' that originates in the same declaration, and because the two private 'x' members have types with identical sets of members once the type arguments 'X' and 'Y' are substituted. + +### 3.11.3 Subtypes and Supertypes + +*S* is a ***subtype*** of a type *T*, and *T* is a ***supertype*** of *S*, if *S* has no excess properties with respect to *T* ([3.11.5](#3.11.5)) and one of the following is true: + +* *S* and *T* are identical types. +* *T* is the Any type. +* *S* is the Undefined type. +* *S* is the Null type and *T* is not the Undefined type. +* *S* is an enum type and *T* is the primitive type Number. +* *S* is a string literal type and *T* is the primitive type String. +* *S* is a union type and each constituent type of *S* is a subtype of *T*. +* *S* is an intersection type and at least one constituent type of *S* is a subtype of *T*. +* *T* is a union type and *S* is a subtype of at least one constituent type of *T*. +* *T* is an intersection type and *S* is a subtype of each constituent type of *T*. +* *S* is a type parameter and the constraint of *S* is a subtype of *T*. +* *S* is an object type, an intersection type, an enum type, or the Number, Boolean, or String primitive type, *T* is an object type, and for each member *M* in *T*, one of the following is true: + * *M* is a property and *S* has an apparent property *N* where + * *M* and *N* have the same name, + * the type of *N* is a subtype of that of *M*, + * if *M* is a required property, *N* is also a required property, and + * *M* and *N* are both public, *M* and *N* are both private and originate in the same declaration, *M* and *N* are both protected and originate in the same declaration, or *M* is protected and *N* is declared in a class derived from the class in which *M* is declared. + * *M* is a non-specialized call or construct signature and *S* has an apparent call or construct signature *N* where, when *M* and *N* are instantiated using type Any as the type argument for all type parameters declared by *M* and *N* (if any), + * the signatures are of the same kind (call or construct), + * *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*, + * for parameter positions that are present in both signatures, each parameter type in *N* is a subtype or supertype of the corresponding parameter type in *M*, and + * the result type of *M* is Void, or the result type of *N* is a subtype of that of *M*. + * *M* is a string index signature of type *U*, and *U* is the Any type or *S* has an apparent string index signature of a type that is a subtype of *U*. + * *M* is a numeric index signature of type *U*, and *U* is the Any type or *S* has an apparent string or numeric index signature of a type that is a subtype of *U*. + +When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. + +Note that specialized call and construct signatures (section [3.9.2.4](#3.9.2.4)) are not significant when determining subtype and supertype relationships. + +Also note that type parameters are not considered object types. Thus, the only subtypes of a type parameter *T* are *T* itself and other type parameters that are directly or indirectly constrained to *T*. + +### 3.11.4 Assignment Compatibility + +Types are required to be assignment compatible in certain circumstances, such as expression and variable types in assignment statements and argument and parameter types in function calls. + +*S* is ***assignable to*** a type *T*, and *T* is ***assignable from*** *S*, if *S* has no excess properties with respect to *T* ([3.11.5](#3.11.5)) and one of the following is true: + +* *S* and *T* are identical types. +* *S* or *T* is the Any type. +* *S* is the Undefined type. +* *S* is the Null type and *T* is not the Undefined type. +* *S* or *T* is an enum type and the other is the primitive type Number. +* *S* is a string literal type and *T* is the primitive type String. +* *S* is a union type and each constituent type of *S* is assignable to *T*. +* *S* is an intersection type and at least one constituent type of *S* is assignable to *T*. +* *T* is a union type and *S* is assignable to at least one constituent type of *T*. +* *T* is an intersection type and *S* is assignable to each constituent type of *T*. +* *S* is a type parameter and the constraint of *S* is assignable to *T*. +* *S* is an object type, an intersection type, an enum type, or the Number, Boolean, or String primitive type, *T* is an object type, and for each member *M* in *T*, one of the following is true: + * *M* is a property and *S* has an apparent property *N* where + * *M* and *N* have the same name, + * the type of *N* is assignable to that of *M*, + * if *M* is a required property, *N* is also a required property, and + * *M* and *N* are both public, *M* and *N* are both private and originate in the same declaration, *M* and *N* are both protected and originate in the same declaration, or *M* is protected and *N* is declared in a class derived from the class in which *M* is declared. + * *M* is an optional property and *S* has no apparent property of the same name as *M*. + * *M* is a non-specialized call or construct signature and *S* has an apparent call or construct signature *N* where, when *M* and *N* are instantiated using type Any as the type argument for all type parameters declared by *M* and *N* (if any), + * the signatures are of the same kind (call or construct), + * *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*, + * for parameter positions that are present in both signatures, each parameter type in *N* is assignable to or from the corresponding parameter type in *M*, and + * the result type of *M* is Void, or the result type of *N* is assignable to that of *M*. + * *M* is a string index signature of type *U*, and *U* is the Any type or *S* has an apparent string index signature of a type that is assignable to *U*. + * *M* is a numeric index signature of type *U*, and *U* is the Any type or *S* has an apparent string or numeric index signature of a type that is assignable to *U*. + +When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. + +Note that specialized call and construct signatures (section [3.9.2.4](#3.9.2.4)) are not significant when determining assignment compatibility. + +The assignment compatibility and subtyping rules differ only in that + +* the Any type is assignable to, but not a subtype of, all types, +* the primitive type Number is assignable to, but not a subtype of, all enum types, and +* an object type without a particular property is assignable to an object type in which that property is optional. + +The assignment compatibility rules imply that, when assigning values or passing parameters, optional properties must either be present and of a compatible type, or not be present at all. For example: + +```TypeScript +function foo(x: { id: number; name?: string; }) { } + +foo({ id: 1234 }); // Ok +foo({ id: 1234, name: "hello" }); // Ok +foo({ id: 1234, name: false }); // Error, name of wrong type +foo({ name: "hello" }); // Error, id required but missing +``` + +### 3.11.5 Excess Properties + +The subtype and assignment compatibility relationships require that source types have no excess properties with respect to their target types. The purpose of this check is to detect excess or misspelled properties in object literals. + +A source type *S* is considered to have excess properties with respect to a target type *T* if + +* *S* is a fresh object literal type, as defined below, and +* *S* has one or more properties that aren't expected in *T*. + +A property *P* is said to be expected in a type *T* if one of the following is true: + +* *T* is not an object, union, or intersection type. +* *T* is an object type and + * *T* has a property with the same name as *P*, + * *T* has a string or numeric index signature, + * *T* has no properties, or + * *T* is the global type 'Object'. +* *T* is a union or intersection type and *P* is expected in at least one of the constituent types of *T*. + +The type inferred for an object literal (as described in section [4.5](#4.5)) is considered a ***fresh object literal type***. The freshness disappears when an object literal type is widened ([3.12](#3.12)) or is the type of the expression in a type assertion ([4.16](#4.16)). + +Consider the following example: + +```TypeScript +interface CompilerOptions { + strict?: boolean; + sourcePath?: string; + targetPath?: string; +} + +var options: CompilerOptions = { + strict: true, + sourcepath: "./src", // Error, excess or misspelled property + targetpath: "./bin" // Error, excess or misspelled property +}; +``` + +The 'CompilerOptions' type contains only optional properties, so without the excess property check, *any* object literal would be assignable to the 'options' variable (because a misspelled property would just be considered an excess property of a different name). + +In cases where excess properties are expected, an index signature can be added to the target type as an indicator of intent: + +```TypeScript +interface InputElement { + name: string; + visible?: boolean; + [x: string]: any; // Allow additional properties of any type +} + +var address: InputElement = { + name: "Address", + visible: true, + help: "Enter address here", // Allowed because of index signature + shortcut: "Alt-A" // Allowed because of index signature +}; +``` + +### 3.11.6 Contextual Signature Instantiation + +During type argument inference in a function call (section [4.15.2](#4.15.2)) it is in certain circumstances necessary to instantiate a generic call signature of an argument expression in the context of a non-generic call signature of a parameter such that further inferences can be made. A generic call signature *A* is ***instantiated in the context of*** non-generic call signature *B* as follows: + +* Using the process described in [3.11.7](#3.11.7), inferences for *A*'s type parameters are made from each parameter type in *B* to the corresponding parameter type in *A* for those parameter positions that are present in both signatures, where rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. +* The inferred type argument for each type parameter is the union type of the set of inferences made for that type parameter. However, if the union type does not satisfy the constraint of the type parameter, the inferred type argument is instead the constraint. + +### 3.11.7 Type Inference + +In certain contexts, inferences for a given set of type parameters are made *from* a type *S*, in which those type parameters do not occur, *to* another type *T*, in which those type parameters do occur. Inferences consist of a set of candidate type arguments collected for each of the type parameters. The inference process recursively relates *S* and *T* to gather as many inferences as possible: + +* If *T* is one of the type parameters for which inferences are being made, *S* is added to the set of inferences for that type parameter. +* Otherwise, if *S* and *T* are references to the same generic type, inferences are made from each type argument in *S* to each corresponding type argument in *T*. +* Otherwise, if *S* and *T* are tuple types with the same number of elements, inferences are made from each element type in *S* to each corresponding element type in *T*. +* Otherwise, if *T* is a union or intersection type: + * First, inferences are made from *S* to each constituent type in *T* that isn't simply one of the type parameters for which inferences are being made. + * If the first step produced no inferences then if T is a union type and exactly one constituent type in *T* is simply a type parameter for which inferences are being made, inferences are made from *S* to that type parameter. +* Otherwise, if *S* is a union or intersection type, inferences are made from each constituent type in *S* to *T*. +* Otherwise, if *S* and *T* are object types, then for each member *M* in *T*: + * If *M* is a property and *S* contains a property *N* with the same name as *M*, inferences are made from the type of *N* to the type of *M*. + * If *M* is a call signature and a corresponding call signature *N* exists in *S*, *N* is instantiated with the Any type as an argument for each type parameter (if any) and inferences are made from parameter types in *N* to the corresponding parameter types in *M* for positions that are present in both signatures, and from the return type of *N* to the return type of *M*. + * If *M* is a construct signature and a corresponding construct signature *N* exists in *S*, *N* is instantiated with the Any type as an argument for each type parameter (if any) and inferences are made from parameter types in *N* to the corresponding parameter types in *M* for positions that are present in both signatures, and from the return type of *N* to the return type of *M*. + * If *M* is a string index signature and *S* contains a string index signature *N*, inferences are made from the type of *N* to the type of *M*. + * If *M* is a numeric index signature and *S* contains a numeric index signature *N*, inferences are made from the type of *N* to the type of *M*. + * If *M* is a numeric index signature and *S* contains a string index signature *N*, inferences are made from the type of *N* to the type of *M*. + +When comparing call or construct signatures, signatures in *S* correspond to signatures of the same kind in *T* pairwise in declaration order. If *S* and *T* have different numbers of a given kind of signature, the excess *first* signatures in declaration order of the longer list are ignored. + +*TODO: Update to reflect [improved union and intersection type inference](https://github.com/Microsoft/TypeScript/pull/5738)*. + +### 3.11.8 Recursive Types + +Classes and interfaces can reference themselves in their internal structure, in effect creating recursive types with infinite nesting. For example, the type + +```TypeScript +interface A { next: A; } +``` + +contains an infinitely nested sequence of 'next' properties. Types such as this are perfectly valid but require special treatment when determining type relationships. Specifically, when comparing types *S* and *T* for a given relationship (identity, subtype, or assignability), the relationship in question is assumed to be true for every directly or indirectly nested occurrence of the same *S* and the same *T* (where same means originating in the same declaration and, if applicable, having identical type arguments). For example, consider the identity relationship between 'A' above and 'B' below: + +```TypeScript +interface B { next: C; } + +interface C { next: D; } + +interface D { next: B; } +``` + +To determine whether 'A' and 'B' are identical, first the 'next' properties of type 'A' and 'C' are compared. That leads to comparing the 'next' properties of type 'A' and 'D', which leads to comparing the 'next' properties of type 'A' and 'B'. Since 'A' and 'B' are already being compared this relationship is by definition true. That in turn causes the other comparisons to be true, and therefore the final result is true. + +When this same technique is used to compare generic type references, two type references are considered the same when they originate in the same declaration and have identical type arguments. + +In certain circumstances, generic types that directly or indirectly reference themselves in a recursive fashion can lead to infinite series of distinct instantiations. For example, in the type + +```TypeScript +interface List { + data: T; + next: List; + owner: List>; +} +``` + +'List<T>' has a member 'owner' of type 'List<List<T>>', which has a member 'owner' of type 'List<List<List<T>>>', which has a member 'owner' of type 'List<List<List<List<T>>>>' and so on, ad infinitum. Since type relationships are determined structurally, possibly exploring the constituent types to their full depth, in order to determine type relationships involving infinitely expanding generic types it may be necessary for the compiler to terminate the recursion at some point with the assumption that no further exploration will change the outcome. + +## 3.12 Widened Types + +In several situations TypeScript infers types from context, alleviating the need for the programmer to explicitly specify types that appear obvious. For example + +```TypeScript +var name = "Steve"; +``` + +infers the type of 'name' to be the String primitive type since that is the type of the value used to initialize it. When inferring the type of a variable, property or function result from an expression, the ***widened*** form of the source type is used as the inferred type of the target. The widened form of a type is the type in which all occurrences of the Null and Undefined types have been replaced with the type `any`. + +The following example shows the results of widening types to produce inferred variable types. + +```TypeScript +var a = null; // var a: any +var b = undefined; // var b: any +var c = { x: 0, y: null }; // var c: { x: number, y: any } +var d = [ null, undefined ]; // var d: any[] +``` + +
+ +#
4 Expressions + +This chapter describes the manner in which TypeScript provides type inference and type checking for JavaScript expressions. TypeScript's type analysis occurs entirely at compile-time and adds no run-time overhead to expression evaluation. + +TypeScript's typing rules define a type for every expression construct. For example, the type of the literal 123 is the Number primitive type, and the type of the object literal { a: 10, b: "hello" } is { a: number; b: string; }. The sections in this chapter describe these rules in detail. + +In addition to type inference and type checking, TypeScript augments JavaScript expressions with the following constructs: + +* Optional parameter and return type annotations in function expressions and arrow functions. +* Type arguments in function calls. +* Type assertions. + +Unless otherwise noted in the sections that follow, TypeScript expressions and the JavaScript expressions generated from them are identical. + +## 4.1 Values and References + +Expressions are classified as ***values*** or ***references***. References are the subset of expressions that are permitted as the target of an assignment. Specifically, references are combinations of identifiers (section [4.3](#4.3)), parentheses (section [4.8](#4.8)), and property accesses (section [4.13](#4.13)). All other expression constructs described in this chapter are classified as values. + +## 4.2 The this Keyword + +The type of `this` in an expression depends on the location in which the reference takes place: + +* In a constructor, instance member function, instance member accessor, or instance member variable initializer, `this` is of the this-type (section [3.6.3](#3.6.3)) of the containing class. +* In a static member function or static member accessor, the type of `this` is the constructor function type of the containing class. +* In a function declaration or a function expression, `this` is of type Any. +* In the global namespace, `this` is of type Any. + +In all other contexts it is a compile-time error to reference `this`. + +Note that an arrow function (section [4.11](#4.11)) has no `this` parameter but rather preserves the `this` of its enclosing context. + +## 4.3 Identifiers + +When an expression is an *IdentifierReference*, the expression refers to the most nested namespace, class, enum, function, variable, or parameter with that name whose scope (section [2.4](#2.4)) includes the location of the reference. The type of such an expression is the type associated with the referenced entity: + +* For a namespace, the object type associated with the namespace instance. +* For a class, the constructor type associated with the constructor function object. +* For an enum, the object type associated with the enum object. +* For a function, the function type associated with the function object. +* For a variable, the type of the variable. +* For a parameter, the type of the parameter. + +An identifier expression that references a variable or parameter is classified as a reference. An identifier expression that references any other kind of entity is classified as a value (and therefore cannot be the target of an assignment). + +## 4.4 Literals + +Literals are typed as follows: + +* The type of the `null` literal is the Null primitive type. +* The type of the literals `true` and `false` is the Boolean primitive type. +* The type of numeric literals is the Number primitive type. +* The type of string literals is the String primitive type. +* The type of regular expression literals is the global interface type 'RegExp'. + +## 4.5 Object Literals + +Object literals are extended to support type annotations in methods and get and set accessors. + +  *PropertyDefinition:* *( Modified )* +   *IdentifierReference* +   *CoverInitializedName* +   *PropertyName* `:` *AssignmentExpression* +   *PropertyName* *CallSignature* `{` *FunctionBody* `}` +   *GetAccessor* +   *SetAccessor* + +  *GetAccessor:* +   `get` *PropertyName* `(` `)` *TypeAnnotationopt* `{` *FunctionBody* `}` + +  *SetAccessor:* +   `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotationopt* `)` `{` *FunctionBody* `}` + +The type of an object literal is an object type with the set of properties specified by the property assignments in the object literal. A get and set accessor may specify the same property name, but otherwise it is an error to specify multiple property assignments for the same property. + +A shorthand property assignment of the form + +```TypeScript +prop +``` + +is equivalent to + +```TypeScript +prop : prop +``` + +Likewise, a property assignment of the form + +```TypeScript +f ( ... ) { ... } +``` + +is equivalent to + +```TypeScript +f : function ( ... ) { ... } +``` + +Each property assignment in an object literal is processed as follows: + +* If the object literal is contextually typed and the contextual type contains a property with a matching name, the property assignment is contextually typed by the type of that property. +* Otherwise, if the object literal is contextually typed, if the contextual type contains a numeric index signature, and if the property assignment specifies a numeric property name, the property assignment is contextually typed by the type of the numeric index signature. +* Otherwise, if the object literal is contextually typed and the contextual type contains a string index signature, the property assignment is contextually typed by the type of the string index signature. +* Otherwise, the property assignment is processed without a contextual type. + +The type of a property introduced by a property assignment of the form *Name* `:` *Expr* is the type of *Expr*. + +A get accessor declaration is processed in the same manner as an ordinary function declaration (section [6.1](#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. When both a get and set accessor is declared for a property: + +* If both accessors include type annotations, the specified types must be identical. +* If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. +* If neither accessor includes a type annotation, the inferred return type of the get accessor becomes the parameter type of the set accessor. + +If a get accessor is declared for a property, the return type of the get accessor becomes the type of the property. If only a set accessor is declared for a property, the parameter type (which may be type Any if no type annotation is present) of the set accessor becomes the type of the property. + +When an object literal is contextually typed by a type that includes a string index signature, the resulting type of the object literal includes a string index signature with the union type of the types of the properties declared in the object literal, or the Undefined type if the object literal is empty. Likewise, when an object literal is contextually typed by a type that includes a numeric index signature, the resulting type of the object literal includes a numeric index signature with the union type of the types of the numerically named properties (section [3.9.4](#3.9.4)) declared in the object literal, or the Undefined type if the object literal declares no numerically named properties. + +If the *PropertyName* of a property assignment is a computed property name that doesn't denote a well-known symbol ([2.2.3](#2.2.3)), the construct is considered a ***dynamic property assignment***. The following rules apply to dynamic property assignments: + +* A dynamic property assignment does not introduce a property in the type of the object literal. +* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type. +* The name associated with a dynamic property assignment is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type. + +## 4.6 Array Literals + +An array literal + +```TypeScript +[ expr1, expr2, ..., exprN ] +``` + +denotes a value of an array type (section [3.3.2](#3.3.2)) or a tuple type (section [3.3.3](#3.3.3)) depending on context. + +Each element expression in a non-empty array literal is processed as follows: + +* If the array literal contains no spread elements, and if the array literal is contextually typed (section [4.23](#4.23)) by a type *T* and *T* has a property with the numeric name *N*, where *N* is the index of the element expression in the array literal, the element expression is contextually typed by the type of that property. +* Otherwise, if the array literal is contextually typed by a type *T* with a numeric index signature, the element expression is contextually typed by the type of the numeric index signature. +* Otherwise, the element expression is not contextually typed. + +The resulting type an array literal expression is determined as follows: + +* If the array literal is empty, the resulting type is an array type with the element type Undefined. +* Otherwise, if the array literal contains no spread elements and is contextually typed by a tuple-like type (section [3.3.3](#3.3.3)), the resulting type is a tuple type constructed from the types of the element expressions. +* Otherwise, if the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section [4.21.1](#4.21.1)), the resulting type is a tuple type constructed from the types of the element expressions. +* Otherwise, the resulting type is an array type with an element type that is the union of the types of the non-spread element expressions and the numeric index signature types of the spread element expressions. + +A spread element must specify an expression of an array-like type (section [3.3.2](#3.3.2)), or otherwise an error occurs. + +*TODO: The compiler currently doesn't support applying the spread operator to a string (to spread the individual characters of a string into a string array). This will eventually be allowed, but only when the code generation target is ECMAScript 2015 or later*. + +*TODO: Document spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array literal*. + +The rules above mean that an array literal is always of an array type, unless it is contextually typed by a tuple-like type. For example + +```TypeScript +var a = [1, 2]; // number[] +var b = ["hello", true]; // (string | boolean)[] +var c: [number, string] = [3, "three"]; // [number, string] +``` + +When the output target is ECMAScript 3 or 5, array literals containing spread elements are rewritten to invocations of the `concat` method. For example, the assignments + +```TypeScript +var a = [2, 3, 4]; +var b = [0, 1, ...a, 5, 6]; +``` + +are rewritten to + +```TypeScript +var a = [2, 3, 4]; +var b = [0, 1].concat(a, [5, 6]); +``` + +## 4.7 Template Literals + +*TODO: [Template literals](https://github.com/Microsoft/TypeScript/pull/960)*. + +## 4.8 Parentheses + +A parenthesized expression + +```TypeScript +( expr ) +``` + +has the same type and classification as the contained expression itself. Specifically, if the contained expression is classified as a reference, so is the parenthesized expression. + +## 4.9 The super Keyword + +The `super` keyword can be used in expressions to reference base class properties and the base class constructor. + +### 4.9.1 Super Calls + +Super calls consist of the keyword `super` followed by an argument list enclosed in parentheses. Super calls are only permitted in constructors of derived classes, as described in section [8.3.2](#8.3.2). + +A super call invokes the constructor of the base class on the instance referenced by `this`. A super call is processed as a function call (section [4.15](#4.15)) using the construct signatures of the base class constructor function type as the initial set of candidate signatures for overload resolution. Type arguments cannot be explicitly specified in a super call. If the base class is a generic class, the type arguments used to process a super call are always those specified in the `extends` clause that references the base class. + +The type of a super call expression is Void. + +The JavaScript code generated for a super call is specified in section [8.7.2](#8.7.2). + +### 4.9.2 Super Property Access + +A super property access consists of the keyword `super` followed by a dot and an identifier. Super property accesses are used to access base class member functions from derived classes and are permitted in contexts where `this` (section [4.2](#4.2)) references a derived class instance or a derived class constructor function. Specifically: + +* 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. + +Super property accesses are not permitted in other contexts, and it is not possible to access other kinds of base class members in a super property access. Note that super property accesses are not permitted inside function expressions nested in the above constructs because `this` is of type Any in such function expressions. + +Super property accesses are typically used to access overridden base class member functions from derived class member functions. For an example of this, see section [8.4.2](#8.4.2). + +The JavaScript code generated for a super property access is specified in section [8.7.2](#8.7.2). + +*TODO: Update section to include [bracket notation in super property access](https://github.com/Microsoft/TypeScript/issues/3970)*. + +## 4.10 Function Expressions + +Function expressions are extended from JavaScript to optionally include parameter and return type annotations. + +  *FunctionExpression:* *( Modified )* +   `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}` + +The descriptions of function declarations provided in chapter [6](#6) apply to function expressions as well, except that function expressions do not support overloading. + +The type of a function expression is an object type containing a single call signature with parameter and return types inferred from the function expression's signature and body. + +When a function expression with no type parameters and no parameter type annotations is contextually typed (section [4.23](#4.23)) by a type *T* and a contextual signature *S* can be extracted from *T*, the function expression is processed as if it had explicitly specified parameter type annotations as they exist in *S*. Parameters are matched by position and need not have matching names. If the function expression has fewer parameters than *S*, the additional parameters in *S* are ignored. If the function expression has more parameters than *S*, the additional parameters are all considered to have type Any. + +Likewise, when a function expression with no return type annotation is contextually typed (section [4.23](#4.23)) by a function type *T* and a contextual signature *S* can be extracted from *T*, expressions in contained return statements (section [5.10](#5.10)) are contextually typed by the return type of *S*. + +A contextual signature *S* is extracted from a function type *T* as follows: + +* If *T* is a function type with exactly one call signature, and if that call signature is non-generic, *S* is that signature. +* If *T* is a union type, let *U* be the set of element types in *T* that have call signatures. If each type in *U* has exactly one call signature and that call signature is non-generic, and if all of the signatures are identical ignoring return types, then *S* is a signature with the same parameters and a union of the return types. +* Otherwise, no contextual signature can be extracted from *T*. + +In the example + +```TypeScript +var f: (s: string) => string = function (s) { + return s.toLowerCase(); +}; +``` + +the function expression is contextually typed by the type of 'f', and since the function expression has no type parameters or type annotations its parameter type information is extracted from the contextual type, thus inferring the type of 's' to be the String primitive type. + +## 4.11 Arrow Functions + +Arrow functions are extended from JavaScript to optionally include parameter and return type annotations. + +  *ArrowFormalParameters:* *( Modified )* +   *CallSignature* + +The descriptions of function declarations provided in chapter [6](#6) apply to arrow functions as well, except that arrow functions do not support overloading. + +The type of an arrow function is determined in the same manner as a function expression (section [4.10](#4.10)). Likewise, parameters of an arrow function and return statements in the body of an arrow function are contextually typed in the same manner as for function expressions. + +When an arrow function with an expression body and no return type annotation is contextually typed (section [4.23](#4.23)) by a function type *T* and a contextual signature *S* can be extracted from *T*, the expression body is contextually typed by the return type of *S*. + +An arrow function expression of the form + +```TypeScript +( ... ) => expr +``` + +is exactly equivalent to + +```TypeScript +( ... ) => { return expr ; } +``` + +Furthermore, arrow function expressions of the forms + +```TypeScript +id => { ... } +id => expr +``` + +are exactly equivalent to + +```TypeScript +( id ) => { ... } +( id ) => expr +``` + +Thus, the following examples are all equivalent: + +```TypeScript +(x) => { return Math.sin(x); } +(x) => Math.sin(x) +x => { return Math.sin(x); } +x => Math.sin(x) +``` + +A function expression introduces a new dynamically bound `this`, whereas an arrow function expression preserves the `this` of its enclosing context. Arrow function expressions are particularly useful for writing callbacks, which otherwise often have an undefined or unexpected `this`. + +In the example + +```TypeScript +class Messenger { + message = "Hello World"; + start() { + setTimeout(() => alert(this.message), 3000); + } +}; + +var messenger = new Messenger(); +messenger.start(); +``` + +the use of an arrow function expression causes the callback to have the same `this` as the surrounding 'start' method. Writing the callback as a standard function expression it becomes necessary to manually arrange access to the surrounding `this`, for example by copying it into a local variable: + +```TypeScript +class Messenger { + message = "Hello World"; + start() { + var _this = this; + setTimeout(function() { alert(_this.message); }, 3000); + } +}; + +var messenger = new Messenger(); +messenger.start(); +``` + +The TypeScript compiler applies this type of transformation to rewrite arrow function expressions into standard function expressions. + +A construct of the form + +```TypeScript +< T > ( ... ) => { ... } +``` + +could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. It is resolved as the former, but parentheses can be used to select the latter meaning: + +```TypeScript +< T > ( ( ... ) => { ... } ) +``` + +## 4.12 Class Expressions + +*TODO: Document [class expressions](https://github.com/Microsoft/TypeScript/issues/497)*. + +## 4.13 Property Access + +A property access uses either dot notation or bracket notation. A property access expression is always classified as a reference. + +A dot notation property access of the form + +```TypeScript +object . name +``` + +where *object* is an expression and *name* is an identifier (including, possibly, a reserved word), is used to access the property with the given name on the given object. A dot notation property access is processed as follows at compile-time: + +* If *object* is of type Any, any *name* is permitted and the property access is of type Any. +* Otherwise, if *name* denotes an accessible apparent property (section [3.11.1](#3.11.1)) in the widened type (section [3.12](#3.12)) of *object*, the property access is of the type of that property. Public members are always accessible, but private and protected members of a class have restricted accessibility, as described in [8.2.2](#8.2.2). +* Otherwise, the property access is invalid and a compile-time error occurs. + +A bracket notation property access of the form + +```TypeScript +object [ index ] +``` + +where *object* and *index* are expressions, is used to access the property with the name computed by the index expression on the given object. A bracket notation property access is processed as follows at compile-time: + +* If *index* is a string literal or a numeric literal and *object* has an apparent property (section [3.11.1](#3.11.1)) with the name given by that literal (converted to its string representation in the case of a numeric literal), the property access is of the type of that property. +* Otherwise, if *object* has an apparent numeric index signature and *index* is of type Any, the Number primitive type, or an enum type, the property access is of the type of that index signature. +* Otherwise, if *object* has an apparent string index signature and *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature. +* Otherwise, if *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. +* Otherwise, the property access is invalid and a compile-time error occurs. + +*TODO: Indexing with [symbols](https://github.com/Microsoft/TypeScript/pull/1978)*. + +The rules above mean that properties are strongly typed when accessed using bracket notation with the literal representation of their name. For example: + +```TypeScript +var type = { + name: "boolean", + primitive: true +}; + +var s = type["name"]; // string +var b = type["primitive"]; // boolean +``` + +Tuple types assign numeric names to each of their elements and elements are therefore strongly typed when accessed using bracket notation with a numeric literal: + +```TypeScript +var data: [string, number] = ["five", 5]; +var s = data[0]; // string +var n = data[1]; // number +``` + +## 4.14 The new Operator + +A `new` operation has one of the following forms: + +```TypeScript +new C +new C ( ... ) +new C < ... > ( ... ) +``` + +where *C* is an expression. The first form is equivalent to supplying an empty argument list. *C* must be of type Any or of an object type with one or more construct or call signatures. The operation is processed as follows at compile-time: + +* If *C* is of type Any, any argument list is permitted and the result of the operation is of type Any. +* If *C* has one or more apparent construct signatures (section [3.11.1](#3.11.1)), 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. +* If *C* has no apparent construct signatures but one or more apparent 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. + +## 4.15 Function Calls + +Function calls are extended from JavaScript to support optional type arguments. + +  *Arguments:* *( Modified )* +   *TypeArgumentsopt* `(` *ArgumentListopt* `)` + +A function call takes one of the forms + +```TypeScript +func ( ... ) +func < ... > ( ... ) +``` + +where *func* is an expression of a function type or of type Any. The function expression is followed by an optional type argument list (section [3.6.2](#3.6.2)) and an argument list. + +If *func* 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***. In an untyped function call no type arguments are permitted, argument expressions can be of any type and number, no contextual types are provided for the argument expressions, and the result is always of type Any. + +If *func* has apparent call signatures (section [3.11.1](#3.11.1)) the call is a ***typed function call***. TypeScript employs ***overload resolution*** in typed function calls in order to support functions with multiple call signatures. Furthermore, TypeScript may perform ***type argument inference*** to automatically determine type arguments in generic function calls. + +### 4.15.1 Overload Resolution + +The purpose of overload resolution in a function call is to ensure that at least one signature is applicable, to provide contextual types for the arguments, and to determine the result type of the function call, which could differ between the multiple applicable signatures. Overload resolution has no impact on the run-time behavior of a function call. Since JavaScript doesn't support function overloading, all that matters at run-time is the name of the function. + +*TODO: Describe use of [wildcard function types](https://github.com/Microsoft/TypeScript/issues/3970) in overload resolution*. + +The compile-time processing of a typed function call consists of the following steps: + +* First, a list of candidate signatures is constructed from the call signatures in the function type in declaration order. For classes and interfaces, inherited signatures are considered to follow explicitly declared signatures in `extends` clause order. + * A non-generic signature is a candidate when + * the function call has no type arguments, and + * the signature is applicable with respect to the argument list of the function call. + * A generic signature is a candidate in a function call without type arguments when + * type inference (section [4.15.2](#4.15.2)) succeeds for each type parameter, + * once the inferred type arguments are substituted for their associated type parameters, the signature is applicable with respect to the argument list of the function call. + * A generic signature is a candidate in a function call with type arguments when + * The signature has the same number of type parameters as were supplied in the type argument list, + * the type arguments satisfy their constraints, and + * once the type arguments are substituted for their associated type parameters, the signature is applicable with respect to the argument list of the function call. +* If the list of candidate signatures is empty, the function call is an error. +* Otherwise, 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. + +A signature is said to be an ***applicable signature*** with respect to an argument list when + +* the number of arguments is not less than the number of required parameters, +* the number of arguments is not greater than the number of parameters, and +* for each argument expression *e* and its corresponding parameter *P,* when *e* is contextually typed (section [4.23](#4.23)) by the type of *P*, no errors ensue and the type of *e* is assignable to (section [3.11.4](#3.11.4)) the type of *P*. + +*TODO: [Spread operator in function calls](https://github.com/Microsoft/TypeScript/pull/1931) and spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into a function call*. + +### 4.15.2 Type Argument Inference + +Given a signature < *T1* , *T2* , … , *Tn* > ( *p1* : *P1* , *p2* : *P2* , … , *pm* : *Pm* ), where each parameter type *P* references zero or more of the type parameters *T*, and an argument list ( *e1* , *e2* , … , *em* ), the task of type argument inference is to find a set of type arguments *A1*…*An* to substitute for *T1*…*Tn* such that the argument list becomes an applicable signature. + +*TODO: Update [type argument inference and overload resolution rules](https://github.com/Microsoft/TypeScript/issues/1186)*. + +Type argument inference produces a set of candidate types for each type parameter. Given a type parameter *T* and set of candidate types, the actual inferred type argument is determined as follows: + +* If the set of candidate argument types is empty, the inferred type argument for *T* is *T*'s constraint. +* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the widened form (section [3.12](#3.12)) of the first such candidate type. If *C* satisfies *T*'s constraint, the inferred type argument for *T* is *C*. Otherwise, the inferred type argument for *T* is *T*'s constraint. +* Otherwise, if no candidate type is a supertype of all of the other candidate types, type inference has fails and no type argument is inferred for *T*. + +In order to compute candidate types, the argument list is processed as follows: + +* Initially all inferred type arguments are considered ***unfixed*** with an empty set of candidate types. +* Proceeding from left to right, each argument expression *e* is ***inferentially typed*** by its corresponding parameter type *P*, possibly causing some inferred type arguments to become ***fixed***, and candidate type inferences (section [3.11.7](#3.11.7)) are made for unfixed inferred type arguments from the type computed for *e* to *P*. + +The process of inferentially typing an expression *e* by a type *T* is the same as that of contextually typing *e* by *T*, with the following exceptions: + +* Where expressions contained within *e* would be contextually typed, they are instead inferentially typed. +* When a function expression is inferentially typed (section [4.10](#4.10)) and a type assigned to a parameter in that expression references type parameters for which inferences are being made, the corresponding inferred type arguments to become ***fixed*** and no further candidate inferences are made for them. +* If *e* is an expression of a function type that contains exactly one generic call signature and no other members, and *T* is a function type with exactly one non-generic call signature and no other members, then any inferences made for type parameters referenced by the parameters of *T*'s call signature are ***fixed***, and *e*'s type is changed to a function type with *e*'s call signature instantiated in the context of *T*'s call signature (section [3.11.6](#3.11.6)). + +An example: + +```TypeScript +function choose(x: T, y: T): T { + return Math.random() < 0.5 ? x : y; +} + +var x = choose(10, 20); // Ok, x of type number +var y = choose("Five", 5); // Error +``` + +In the first call to 'choose', two inferences are made from 'number' to 'T', one for each parameter. Thus, 'number' is inferred for 'T' and the call is equivalent to + +```TypeScript +var x = choose(10, 20); +``` + +In the second call to 'choose', an inference is made from type 'string' to 'T' for the first parameter and an inference is made from type 'number' to 'T' for the second parameter. Since neither 'string' nor 'number' is a supertype of the other, type inference fails. That in turn means there are no applicable signatures and the function call is an error. + +In the example + +```TypeScript +function map(a: T[], f: (x: T) => U): U[] { + var result: U[] = []; + for (var i = 0; i < a.length; i++) result.push(f(a[i])); + return result; +} + +var names = ["Peter", "Paul", "Mary"]; +var lengths = map(names, s => s.length); +``` + +inferences for 'T' and 'U' in the call to 'map' are made as follows: For the first parameter, inferences are made from the type 'string[]' (the type of 'names') to the type 'T[]', inferring 'string' for 'T'. For the second parameter, inferential typing of the arrow expression 's => s.length' causes 'T' to become fixed such that the inferred type 'string' can be used for the parameter 's'. The return type of the arrow expression can then be determined, and inferences are made from the type '(s: string) => number' to the type '(x: T) => U', inferring 'number' for 'U'. Thus the call to 'map' is equivalent to + +```TypeScript +var lengths = map(names, s => s.length); +``` + +and the resulting type of 'lengths' is therefore 'number[]'. + +In the example + +```TypeScript +function zip(x: S[], y: T[], combine: (x: S) => (y: T) => U): U[] { + var len = Math.max(x.length, y.length); + var result: U[] = []; + for (var i = 0; i < len; i++) result.push(combine(x[i])(y[i])); + return result; +} + +var names = ["Peter", "Paul", "Mary"]; +var ages = [7, 9, 12]; +var pairs = zip(names, ages, s => n => ({ name: s, age: n })); +``` + +inferences for 'S', 'T' and 'U' in the call to 'zip' are made as follows: Using the first two parameters, inferences of 'string' for 'S' and 'number' for 'T' are made. For the third parameter, inferential typing of the outer arrow expression causes 'S' to become fixed such that the inferred type 'string' can be used for the parameter 's'. When a function expression is inferentially typed, its return expression(s) are also inferentially typed. Thus, the inner arrow function is inferentially typed, causing 'T' to become fixed such that the inferred type 'number' can be used for the parameter 'n'. The return type of the inner arrow function can then be determined, which in turn determines the return type of the function returned from the outer arrow function, and inferences are made from the type '(s: string) => (n: number) => { name: string; age: number }' to the type '(x: S) => (y: T) => R', inferring '{ name: string; age: number }' for 'R'. Thus the call to 'zip' is equivalent to + +```TypeScript +var pairs = zip( + names, ages, s => n => ({ name: s, age: n })); +``` + +and the resulting type of 'pairs' is therefore '{ name: string; age: number }[]'. + +### 4.15.3 Grammar Ambiguities + +The inclusion of type arguments in the *Arguments* production (section [4.15](#4.15)) gives rise to certain ambiguities in the grammar for expressions. For example, the statement + +```TypeScript +f(g(7)); +``` + +could be interpreted as a call to 'f' with two arguments, 'g < A' and 'B > (7)'. Alternatively, it could be interpreted as a call to 'f' with one argument, which is a call to a generic function 'g' with two type arguments and one regular argument. + +The grammar ambiguity is resolved as follows: In a context where one possible interpretation of a sequence of tokens is an *Arguments* production, if the initial sequence of tokens forms a syntactically correct *TypeArguments* production and is followed by a '`(`' token, then the sequence of tokens is processed an *Arguments* production, and any other possible interpretation is discarded. Otherwise, the sequence of tokens is not considered an *Arguments* production. + +This rule means that the call to 'f' above is interpreted as a call with one argument, which is a call to a generic function 'g' with two type arguments and one regular argument. However, the statements + +```TypeScript +f(g < A, B > 7); +f(g < A, B > +(7)); +``` + +are both interpreted as calls to 'f' with two arguments. + +## 4.16 Type Assertions + +TypeScript extends the JavaScript expression grammar with the ability to assert a type for an expression: + +  *UnaryExpression:* *( Modified )* +   … +   `<` *Type* `>` *UnaryExpression* + +A type assertion expression consists of a type enclosed in `<` and `>` followed by a unary expression. Type assertion expressions are purely a compile-time construct. Type assertions are *not* checked at run-time and have no impact on the emitted JavaScript (and therefore no run-time cost). The type and the enclosing `<` and `>` are simply removed from the generated code. + +In a type assertion expression of the form < *T* > *e*, *e* is contextually typed (section [4.23](#4.23)) by *T* and the resulting type of* e* is required to be assignable to *T*, or *T* is required to be assignable to the widened form of the resulting type of *e*, or otherwise a compile-time error occurs. The type of the result is *T*. + +Type assertions check for assignment compatibility in both directions. Thus, type assertions allow type conversions that *might* be correct, but aren't *known* to be correct. In the example + +```TypeScript +class Shape { ... } + +class Circle extends Shape { ... } + +function createShape(kind: string): Shape { + if (kind === "circle") return new Circle(); + ... +} + +var circle = createShape("circle"); +``` + +the type annotations indicate that the 'createShape' function *might* return a 'Circle' (because 'Circle' is a subtype of 'Shape'), but isn't *known* to do so (because its return type is 'Shape'). Therefore, a type assertion is needed to treat the result as a 'Circle'. + +As mentioned above, type assertions are not checked at run-time and it is up to the programmer to guard against errors, for example using the `instanceof` operator: + +```TypeScript +var shape = createShape(shapeKind); +if (shape instanceof Circle) { + var circle = shape; + ... +} +``` + +*TODO: Document [as operator](https://github.com/Microsoft/TypeScript/pull/3564)*. + +## 4.17 JSX Expressions + +*TODO: Document [JSX expressions](https://github.com/Microsoft/TypeScript/issues/3203)*. + +## 4.18 Unary Operators + +The subsections that follow specify the compile-time processing rules of the unary operators. In general, if the operand of a unary operator does not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type Any in further processing. + +### 4.18.1 The ++ and -- operators + +These operators, in prefix or postfix form, require their operand to be of type Any, the Number primitive type, or an enum type, and classified as a reference (section [4.1](#4.1)). They produce a result of the Number primitive type. + +### 4.18.2 The +, –, and ~ operators + +These operators permit their operand to be of any type and produce a result of the Number primitive type. + +The unary + operator can conveniently be used to convert a value of any type to the Number primitive type: + +```TypeScript +function getValue() { ... } + +var n = +getValue(); +``` + +The example above converts the result of 'getValue()' to a number if it isn't a number already. The type inferred for 'n' is the Number primitive type regardless of the return type of 'getValue'. + +### 4.18.3 The ! operator + +The ! operator permits its operand to be of any type and produces a result of the Boolean primitive type. + +Two unary ! operators in sequence can conveniently be used to convert a value of any type to the Boolean primitive type: + +```TypeScript +function getValue() { ... } + +var b = !!getValue(); +``` + +The example above converts the result of 'getValue()' to a Boolean if it isn't a Boolean already. The type inferred for 'b' is the Boolean primitive type regardless of the return type of 'getValue'. + +### 4.18.4 The delete Operator + +The 'delete' operator takes an operand of any type and produces a result of the Boolean primitive type. + +### 4.18.5 The void Operator + +The 'void' operator takes an operand of any type and produces the value 'undefined'. The type of the result is the Undefined type ([3.2.7](#3.2.7)). + +### 4.18.6 The typeof Operator + +The 'typeof' operator takes an operand of any type and produces a value of the String primitive type. In positions where a type is expected, 'typeof' can also be used in a type query (section [3.8.10](#3.8.10)) to produce the type of an expression. + +```TypeScript +var x = 5; +var y = typeof x; // Use in an expression +var z: typeof x; // Use in a type query +``` + +In the example above, 'x' is of type 'number', 'y' is of type 'string' because when used in an expression, 'typeof' produces a value of type string (in this case the string "number"), and 'z' is of type 'number' because when used in a type query, 'typeof' obtains the type of an expression. + +## 4.19 Binary Operators + +The subsections that follow specify the compile-time processing rules of the binary operators. In general, if the operands of a binary operator do not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type any in further processing. Tables that summarize the compile-time processing rules for operands of the Any type, the Boolean, Number, and String primitive types, and all other types (the Other column in the tables) are provided. + +### 4.19.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators + +These operators require their operands to be of type Any, the Number primitive type, or an enum type. Operands of an enum type are treated as having the primitive type Number. If one operand is the `null` or `undefined` value, it is treated as having the type of the other operand. The result is always of the Number primitive type. + +||Any|Boolean|Number|String|Other| +|:---:|:---:|:---:|:---:|:---:|:---:| +|Any|Number||Number||| +|Boolean|||||| +|Number|Number||Number||| +|String|||||| +|Other|||||| + +*TODO: Document the [exponentation operator](https://github.com/Microsoft/TypeScript/issues/4812)*. + +### 4.19.2 The + operator + +The binary + operator requires both operands to be of the Number primitive type or an enum type, or at least one of the operands to be of type Any or the String primitive type. Operands of an enum type are treated as having the primitive type Number. If one operand is the `null` or `undefined` value, it is treated as having the type of the other operand. If both operands are of the Number primitive type, the result is of the Number primitive type. If one or both operands are of the String primitive type, the result is of the String primitive type. Otherwise, the result is of type Any. + +||Any|Boolean|Number|String|Other| +|:---:|:---:|:---:|:---:|:---:|:---:| +|Any|Any|Any|Any|String|Any| +|Boolean|Any|||String|| +|Number|Any||Number|String|| +|String|String|String|String|String|String| +|Other|Any|||String|| + +A value of any type can converted to the String primitive type by adding an empty string: + +```TypeScript +function getValue() { ... } + +var s = getValue() + ""; +``` + +The example above converts the result of 'getValue()' to a string if it isn't a string already. The type inferred for 's' is the String primitive type regardless of the return type of 'getValue'. + +### 4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators + +These operators require one or both of the operand types to be assignable to the other. The result is always of the Boolean primitive type. + +||Any|Boolean|Number|String|Other| +|:---:|:---:|:---:|:---:|:---:|:---:| +|Any|Boolean|Boolean|Boolean|Boolean|Boolean| +|Boolean|Boolean|Boolean|||| +|Number|Boolean||Boolean||| +|String|Boolean|||Boolean|| +|Other|Boolean||||Boolean| + +### 4.19.4 The instanceof operator + +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 or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type. + +Note that object types containing one or more call or construct signatures are automatically subtypes of the 'Function' interface type, as described in section [3.3](#3.3). + +### 4.19.5 The in operator + +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. + +### 4.19.6 The && operator + +The && operator permits the operands to be of any type and produces a result of the same type as the second operand. + +||Any|Boolean|Number|String|Other| +|:---:|:---:|:---:|:---:|:---:|:---:| +|Any|Any|Boolean|Number|String|Other| +|Boolean|Any|Boolean|Number|String|Other| +|Number|Any|Boolean|Number|String|Other| +|String|Any|Boolean|Number|String|Other| +|Other|Any|Boolean|Number|String|Other| + +### 4.19.7 The || operator + +The || operator permits the operands to be of any type. + +If the || expression is contextually typed (section [4.23](#4.23)), the operands are contextually typed by the same type. Otherwise, the left operand is not contextually typed and the right operand is contextually typed by the type of the left operand. + +The type of the result is the union type of the two operand types. + +||Any|Boolean|Number|String|Other| +|:---:|:---:|:---:|:---:|:---:|:---:| +|Any|Any|Any|Any|Any|Any| +|Boolean|Any|Boolean|N | B|S | B|B | O| +|Number|Any|N | B|Number|S | N|N | O| +|String|Any|S | B|S | N|String|S | O| +|Other|Any|B | O|N | O|S | O|Other| + +## 4.20 The Conditional Operator + +In a conditional expression of the form + +```TypeScript +test ? expr1 : expr2 +``` + +the *test* expression may be of any type. + +If the conditional expression is contextually typed (section [4.23](#4.23)), *expr1* and *expr2* are contextually typed by the same type. Otherwise, *expr1* and *expr2* are not contextually typed. + +The type of the result is the union type of the types of *expr1* and *expr2*. + +## 4.21 Assignment Operators + +An assignment of the form + +```TypeScript +v = expr +``` + +requires *v* to be classified as a reference (section [4.1](#4.1)) or as an assignment pattern (section [4.21.1](#4.21.1)). The *expr* expression is contextually typed (section [4.23](#4.23)) by the type of *v*, and the type of *expr* must be assignable to (section [3.11.4](#3.11.4)) the type of *v*, or otherwise a compile-time error occurs. The result is a value with the type of *expr*. + +A compound assignment of the form + +```TypeScript +v ??= expr +``` + +where ??= is one of the compound assignment operators + +```TypeScript +*= /= %= += -= <<= >>= >>>= &= ^= |= +``` + +is subject to the same requirements, and produces a value of the same type, as the corresponding non-compound operation. A compound assignment furthermore requires *v* to be classified as a reference (section [4.1](#4.1)) and the type of the non-compound operation to be assignable to the type of *v*. Note that *v* is not permitted to be an assignment pattern in a compound assignment. + +### 4.21.1 Destructuring Assignment + +A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern as defined by the *AssignmentPattern* production in the ECMAScript 2015 specification. + +In a destructuring assignment expression, the type of the expression on the right must be assignable to the assignment target on the left. An expression of type *S* is considered assignable to an assignment target *V* if one of the following is true: + +* *V* is variable and *S* is assignable to the type of *V*. +* *V* is an object assignment pattern and, for each assignment property *P* in *V*, + * *S* is the type Any, or + * *S* has an apparent property with the property name specified in *P* of a type that is assignable to the target given in *P*, or + * *P* specifies a numeric property name and *S* has a numeric index signature of a type that is assignable to the target given in *P*, or + * *S* has a string index signature of a type that is assignable to the target given in *P*. +* *V* is an array assignment pattern, *S* is the type Any or an array-like type (section [3.3.2](#3.3.2)), and, for each assignment element *E* in *V*, + * *S* is the type Any, or + * *S* is a tuple-like type (section [3.3.3](#3.3.3)) with a property named *N* of a type that is assignable to the target given in *E*, where *N* is the numeric index of *E* in the array assignment pattern, or + * *S* is not a tuple-like type and the numeric index signature type of *S* is assignable to the target given in *E*. + +*TODO: [Update to specify behavior when assignment element E is a rest element](https://github.com/Microsoft/TypeScript/issues/2713)*. + +In an assignment property or element that includes a default value, the type of the default value must be assignable to the target given in the assignment property or element. + +When the output target is ECMAScript 2015 or higher, destructuring variable assignments remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring variable assignments are rewritten to series of simple assignments. For example, the destructuring assignment + +```TypeScript +var x = 1; +var y = 2; +[x, y] = [y, x]; +``` + +is rewritten to the simple variable assignments + +```TypeScript +var x = 1; +var y = 2; +_a = [y, x], x = _a[0], y = _a[1]; +var _a; +``` + +## 4.22 The Comma Operator + +The comma operator permits the operands to be of any type and produces a result that is of the same type as the second operand. + +## 4.23 Contextually Typed Expressions + +Type checking of an expression is improved in several contexts by factoring in the type of the destination of the value computed by the expression. In such situations, the expression is said to be ***contextually typed*** by the type of the destination. An expression is contextually typed in the following circumstances: + +* In a variable, parameter, binding property, binding element, or member declaration, an initializer expression is contextually typed by + * the type given in the declaration's type annotation, if any, or otherwise + * for a parameter, the type provided by a contextual signature (section [4.10](#4.10)), if any, or otherwise + * the type implied by the binding pattern in the declaration (section [5.2.3](#5.2.3)), if any. +* In the body of a function declaration, function expression, arrow function, method declaration, or get accessor declaration that has a return type annotation, return expressions are contextually typed by the type given in the return type annotation. +* In the body of a function expression or arrow function that has no return type annotation, if the function expression or arrow function is contextually typed by a function type with exactly one call signature, and if that call signature is non-generic, return expressions are contextually typed by the return type of that call signature. +* In the body of a constructor declaration, return expressions are contextually typed by the containing class type. +* In the body of a get accessor with no return type annotation, if a matching set accessor exists and that set accessor has a parameter type annotation, return expressions are contextually typed by the type given in the set accessor's parameter type annotation. +* In a typed function call, argument expressions are contextually typed by their corresponding parameter types. +* In a contextually typed object literal, each property value expression is contextually typed by + * the type of the property with a matching name in the contextual type, if any, or otherwise + * for a numerically named property, the numeric index type of the contextual type, if any, or otherwise + * the string index type of the contextual type, if any. +* In a contextually typed array literal expression containing no spread elements, an element expression at index *N* is contextually typed by + * the type of the property with the numeric name *N* in the contextual type, if any, or otherwise + * the numeric index type of the contextual type, if any. +* In a contextually typed array literal expression containing one or more spread elements, an element expression at index *N* is contextually typed by the numeric index type of the contextual type, if any. +* In a contextually typed parenthesized expression, the contained expression is contextually typed by the same type. +* In a type assertion, the expression is contextually typed by the indicated type. +* In a || operator expression, if the expression is contextually typed, the operands are contextually typed by the same type. Otherwise, the right expression is contextually typed by the type of the left expression. +* In a contextually typed conditional operator expression, the operands are contextually typed by the same type. +* In an assignment expression, the right hand expression is contextually typed by the type of the left hand expression. + +In the following example + +```TypeScript +interface EventObject { + x: number; + y: number; +} + +interface EventHandlers { + mousedown?: (event: EventObject) => void; + mouseup?: (event: EventObject) => void; + mousemove?: (event: EventObject) => void; +} + +function setEventHandlers(handlers: EventHandlers) { ... } + +setEventHandlers({ + mousedown: e => { startTracking(e.x, e.y); }, + mouseup: e => { endTracking(); } +}); +``` + +the object literal passed to 'setEventHandlers' is contextually typed to the 'EventHandlers' type. This causes the two property assignments to be contextually typed to the unnamed function type '(event: EventObject) => void', which in turn causes the 'e' parameters in the arrow function expressions to automatically be typed as 'EventObject'. + +## 4.24 Type Guards + +Type guards are particular expression patterns involving the 'typeof' and 'instanceof' operators that cause the types of variables or parameters to be ***narrowed*** to more specific types. For example, in the code below, knowledge of the static type of 'x' in combination with a 'typeof' check makes it safe to narrow the type of 'x' to string in the first branch of the 'if' statement and number in the second branch of the 'if' statement. + +```TypeScript +function foo(x: number | string) { + if (typeof x === "string") { + return x.length; // x has type string here + } + else { + return x + 1; // x has type number here + } +} +``` + +The type of a variable or parameter is narrowed in the following situations: + +* In the true branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when true*, provided no part of the 'if' statement contains assignments to the variable or parameter. +* In the false branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when false*, provided no part of the 'if' statement contains assignments to the variable or parameter. +* In the true expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when true*, provided no part of the conditional expression contains assignments to the variable or parameter. +* In the false expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when false*, provided no part of the conditional expression contains assignments to the variable or parameter. +* In the right operand of a && operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when true*, provided neither operand contains assignments to the variable or parameter. +* In the right operand of a || operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when false*, provided neither operand contains assignments to the variable or parameter. + +A type guard is simply an expression that follows a particular pattern. The process of narrowing the type of a variable *x* by a type guard *when true* or *when false* depends on the type guard as follows: + +* A type guard of the form `x instanceof C`, where *x* is not of type Any, *C* is of a subtype of the global type 'Function', and *C* has a property named 'prototype' + * *when true*, narrows the type of *x* to the type of the 'prototype' property in *C* provided it is a subtype of the type of *x*, or, if the type of *x* is a union type, removes from the type of *x* all constituent types that aren't subtypes of the type of the 'prototype' property in *C*, or + * *when false*, has no effect on the type of *x*. +* A type guard of the form `typeof x === s`, where *s* is a string literal with the value 'string', 'number', or 'boolean', + * *when true*, narrows the type of *x* to the given primitive type provided it is a subtype of the type of *x*, or, if the type of *x* is a union type, removes from the type of *x* all constituent types that aren't subtypes of the given primitive type, or + * *when false*, removes the primitive type from the type of *x*. +* A type guard of the form `typeof x === s`, where *s* is a string literal with any value but 'string', 'number', or 'boolean', + * *when true*, if *x* is a union type, removes from the type of *x* all constituent types that are subtypes of the string, number, or boolean primitive type, or + * *when false*, has no effect on the type of *x*. +* A type guard of the form `typeof x !== s`, where *s* is a string literal, + * *when true*, narrows the type of x by `typeof x === s` *when false*, or + * *when false*, narrows the type of x by `typeof x === s` *when true*. +* A type guard of the form `!expr` + * *when true*, narrows the type of *x* by *expr* *when false*, or + * *when false*, narrows the type of *x* by *expr* *when true*. +* A type guard of the form `expr1 && expr2` + * *when true*, narrows the type of *x* by *expr1* *when true* and then by *expr2* *when true*, or + * *when false*, narrows the type of *x* to *T1* | *T2*, where *T1* is the type of *x* narrowed by *expr1* *when false*, and *T2* is the type of *x* narrowed by *expr1* *when true* and then by *expr2* *when false*. +* A type guard of the form `expr1 || expr2` + * *when true*, narrows the type of *x* to *T1* | *T2*, where *T1* is the type of *x* narrowed by *expr1* *when true*, and *T2* is the type of *x* narrowed by *expr1* *when false* and then by *expr2* *when true*, or + * *when false*, narrows the type of *x* by *expr1* *when false* and then by *expr2* *when false*. +* A type guard of any other form has no effect on the type of *x*. + +In the rules above, when a narrowing operation would remove all constituent types from a union type, the operation has no effect on the union type. + +Note that type guards affect types of variables and parameters only and have no effect on members of objects such as properties. Also note that it is possible to defeat a type guard by calling a function that changes the type of the guarded variable. + +*TODO: Document [user defined type guard functions](https://github.com/Microsoft/TypeScript/issues/1007)*. + +In the example + +```TypeScript +function isLongString(obj: any) { + return typeof obj === "string" && obj.length > 100; +} +``` + +the `obj` parameter has type `string` in the right operand of the && operator. + +In the example + +```TypeScript +function processValue(value: number | (() => number)) { + var x = typeof value !== "number" ? value() : value; + // Process number in x +} +``` + +the value parameter has type `() => number` in the first conditional expression and type `number` in the second conditional expression, and the inferred type of x is `number`. + +In the example + +```TypeScript +function f(x: string | number | boolean) { + if (typeof x === "string" || typeof x === "number") { + var y = x; // Type of y is string | number + } + else { + var z = x; // Type of z is boolean + } +} +``` + +the type of x is `string | number | boolean` in the left operand of the || operator, `number | boolean` in the right operand of the || operator, `string | number` in the first branch of the if statement, and `boolean` in the second branch of the if statement. + +In the example + +```TypeScript +class C { + data: string | string[]; + getData() { + var data = this.data; + return typeof data === "string" ? data : data.join(" "); + } +} +``` + +the type of the `data` variable is `string` in the first conditional expression and `string[]` in the second conditional expression, and the inferred type of `getData` is `string`. Note that the `data` property must be copied to a local variable for the type guard to have an effect. + +In the example + +```TypeScript +class NamedItem { + name: string; +} + +function getName(obj: Object) { + return obj instanceof NamedItem ? obj.name : "unknown"; +} +``` + +the type of `obj` is narrowed to `NamedItem` in the first conditional expression, and the inferred type of the `getName` function is `string`. + +
+ +#
5 Statements + +This chapter describes the static type checking TypeScript provides for JavaScript statements. TypeScript itself does not introduce any new statement constructs, but it does extend the grammar for local declarations to include interface, type alias, and enum declarations. + +## 5.1 Blocks + +Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 2015 grammar). + +  *Declaration:* *( Modified )* +   … +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *EnumDeclaration* + +Local class, interface, type alias, and enum declarations are block scoped, similar to let and const declarations. + +## 5.2 Variable Statements + +Variable statements are extended to include optional type annotations. + +  *VariableDeclaration:* *( Modified )* +   *SimpleVariableDeclaration* +   *DestructuringVariableDeclaration* + +A variable declaration is either a simple variable declaration or a destructuring variable declaration. + +### 5.2.1 Simple Variable Declarations + +A ***simple variable declaration*** introduces a single named variable and optionally assigns it an initial value. + +  *SimpleVariableDeclaration:* +   *BindingIdentifier* *TypeAnnotationopt* *Initializeropt* + +The type *T* of a variable introduced by a simple variable declaration is determined as follows: + +* If the declaration includes a type annotation, *T* is that type. +* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.12](#3.12)) of the type of the initializer expression. +* Otherwise, *T* is the Any type. + +When a variable declaration specifies both a type annotation and an initializer expression, the type of the initializer expression is required to be assignable to (section [3.11.4](#3.11.4)) the type given in the type annotation. + +Multiple declarations for the same variable name in the same declaration space are permitted, provided that each declaration associates the same type with the variable. + +When a variable declaration has a type annotation, it is an error for that type annotation to use the `typeof` operator to reference the variable being declared. + +Below are some examples of simple variable declarations and their associated types. + +```TypeScript +var a; // any +var b: number; // number +var c = 1; // number +var d = { x: 1, y: "hello" }; // { x: number; y: string; } +var e: any = "test"; // any +``` + +The following is permitted because all declarations of the single variable 'x' associate the same type (Number) with 'x'. + +```TypeScript +var x = 1; +var x: number; +if (x == 1) { + var x = 2; +} +``` + +In the following example, all five variables are of the same type, '{ x: number; y: number; }'. + +```TypeScript +interface Point { x: number; y: number; } + +var a = { x: 0, y: undefined }; +var b: Point = { x: 0, y: undefined }; +var c = { x: 0, y: undefined }; +var d: { x: number; y: number; } = { x: 0, y: undefined }; +var e = <{ x: number; y: number; }> { x: 0, y: undefined }; +``` + +### 5.2.2 Destructuring Variable Declarations + +A ***destructuring variable declaration*** introduces zero or more named variables and initializes them with values extracted from properties of an object or elements of an array. + +  *DestructuringVariableDeclaration:* +   *BindingPattern* *TypeAnnotationopt* *Initializer* + +Each binding property or element that specifies an identifier introduces a variable by that name. The type of the variable is the widened form (section [3.12](#3.12)) of the type associated with the binding property or element, as defined in the following. + +*TODO: Document destructuring an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array*. + +The type *T* associated with a destructuring variable declaration is determined as follows: + +* If the declaration includes a type annotation, *T* is that type. +* Otherwise, if the declaration includes an initializer expression, *T* is the type of that initializer expression. +* Otherwise, *T* is the Any type. + +The type *T* associated with a binding property is determined as follows: + +* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element. +* If *S* is the Any type: + * If the binding property specifies an initializer expression, *T* is the type of that initializer expression. + * Otherwise, *T* is the Any type. +* Let *P* be the property name specified in the binding property. +* If *S* has an apparent property with the name *P*, *T* is the type of that property. +* Otherwise, if *S* has a numeric index signature and *P* is a numerical name, *T* is the type of the numeric index signature. +* Otherwise, if *S* has a string index signature, *T* is the type of the string index signature. +* Otherwise, no type is associated with the binding property and an error occurs. + +The type *T* associated with a binding element is determined as follows: + +* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element. +* If *S* is the Any type: + * If the binding element specifies an initializer expression, *T* is the type of that initializer expression. + * Otherwise, *T* is the Any type. +* If *S* is not an array-like type (section [3.3.2](#3.3.2)), no type is associated with the binding property and an error occurs. +* If the binding element is a rest element, *T* is an array type with an element type *E*, where *E* is the type of the numeric index signature of *S*. +* Otherwise, if *S* is a tuple-like type (section [3.3.3](#3.3.3)): + * Let *N* be the zero-based index of the binding element in the array binding pattern. + * If *S* has a property with the numerical name *N*, *T* is the type of that property. + * Otherwise, no type is associated with the binding element and an error occurs. +* Otherwise, if *S* has a numeric index signature, *T* is the type of the numeric index signature. +* Otherwise, no type is associated with the binding element and an error occurs. + +When a destructuring variable declaration, binding property, or binding element specifies an initializer expression, the type of the initializer expression is required to be assignable to the widened form of the type associated with the destructuring variable declaration, binding property, or binding element. + +*TODO: Update rules to reflect [improved checking of destructuring with literal initializers](https://github.com/Microsoft/TypeScript/pull/4598)*. + +When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code. + +When the output target is ECMAScript 3 or 5, destructuring variable declarations are rewritten to simple variable declarations. For example, an object destructuring declaration of the form + +```TypeScript +var { x, p: y, q: z = false } = getSomeObject(); +``` + +is rewritten to the simple variable declarations + +```TypeScript +var _a = getSomeObject(), + x = _a.x, + y = _a.p, + _b = _a.q, + z = _b === void 0 ? false : _b; +``` + +The '_a' and '_b' temporary variables exist to ensure the assigned expression is evaluated only once, and the expression 'void 0' simply denotes the JavaScript value 'undefined'. + +Similarly, an array destructuring declaration of the form + +```TypeScript +var [x, y, z = 10] = getSomeArray(); +``` + +is rewritten to the simple variable declarations + +```TypeScript +var _a = getSomeArray(), + x = _a[0], + y = _a[1], + _b = _a[2], + z = _b === void 0 ? 10 : _b; +``` + +Combining both forms of destructuring, the example + +```TypeScript +var { x, p: [y, z = 10] = getSomeArray() } = getSomeObject(); +``` + +is rewritten to + +```TypeScript +var _a = getSomeObject(), + x = _a.x, + _b = _a.p, + _c = _b === void 0 ? getSomeArray() : _b, + y = _c[0], + _d = _c[1], + z = _d === void 0 ? 10 : _d; +``` + +### 5.2.3 Implied Type + +A variable, parameter, binding property, or binding element declaration that specifies a binding pattern has an ***implied type*** which is determined as follows: + +* If the declaration specifies an object binding pattern, the implied type is an object type with a set of properties corresponding to the specified binding property declarations. The type of each property is the type implied by its binding property declaration, and a property is optional when its binding property declaration specifies an initializer expression. +* If the declaration specifies an array binding pattern without a rest element, the implied type is a tuple type with elements corresponding to the specified binding element declarations. The type of each element is the type implied by its binding element declaration. +* If the declaration specifies an array binding pattern with a rest element, the implied type is an array type with an element type of Any. + +The implied type of a binding property or binding element declaration is + +* the type of the declaration's initializer expression, if any, or otherwise +* the implied type of the binding pattern specified in the declaration, if any, or otherwise +* the type Any. + +In the example + +```TypeScript +function f({ a, b = "hello", c = 1 }) { ... } +``` + +the implied type of the binding pattern in the function's parameter is '{ a: any; b?: string; c?: number; }'. Since the parameter has no type annotation, this becomes the type of the parameter. + +In the example + +```TypeScript +var [a, b, c] = [1, "hello", true]; +``` + +the array literal initializer expression is contextually typed by the implied type of the binding pattern, specifically the tuple type '[any, any, any]'. Because the contextual type is a tuple type, the resulting type of the array literal is the tuple type '[number, string, boolean]', and the destructuring declaration thus gives the types number, string, and boolean to a, b, and c respectively. + +## 5.3 Let and Const Declarations + +Let and const declarations are exended to include optional type annotations. + +  *LexicalBinding:* *( Modified )* +   *SimpleLexicalBinding* +   *DestructuringLexicalBinding* + +  *SimpleLexicalBinding:* +   *BindingIdentifier* *TypeAnnotationopt* *Initializeropt* + +  *DestructuringLexicalBinding:* +   *BindingPattern* *TypeAnnotationopt* *Initializeropt* + +*TODO: Document scoping and types of [let and const declarations](https://github.com/Microsoft/TypeScript/pull/904)*. + +## 5.4 If, Do, and While Statements + +Expressions controlling 'if', 'do', and 'while' statements can be of any type (and not just type Boolean). + +## 5.5 For Statements + +Variable declarations in 'for' statements are extended in the same manner as variable declarations in variable statements (section [5.2](#5.2)). + +## 5.6 For-In Statements + +In a 'for-in' statement of the form + +```TypeScript +for (v in expr) statement +``` + +*v* 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. + +In a 'for-in' statement of the form + +```TypeScript +for (var v in expr) statement +``` + +*v* 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. + +## 5.7 For-Of Statements + +*TODO: Document [for-of statements](https://github.com/Microsoft/TypeScript/issues/7)*. + +## 5.8 Continue Statements + +A 'continue' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') statement. When a 'continue' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) iteration statement. + +## 5.9 Break Statements + +A 'break' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') or 'switch' statement. When a 'break' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) statement. + +## 5.10 Return Statements + +It is an error for a 'return' statement to occur outside a function body. Specifically, 'return' statements are not permitted at the global level or in namespace bodies. + +A 'return' statement without an expression returns the value 'undefined' and is permitted in the body of any function, regardless of the return type of the function. + +When a 'return' statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section [4.23](#4.23)) by that return type and must be of a type that is assignable to the return type. Otherwise, if the containing function is contextually typed by a type *T*, *Expr* is contextually typed by *T*'s return type. + +In a function implementation without a return type annotation, the return type is inferred from the 'return' statements in the function body, as described in section [6.3](#6.3). + +In the example + +```TypeScript +function f(): (x: string) => number { + return s => s.length; +} +``` + +the arrow expression in the 'return' statement is contextually typed by the return type of 'f', thus giving type 'string' to 's'. + +## 5.11 With Statements + +Use of the 'with' statement in TypeScript is an error, as is the case in ECMAScript 5's strict mode. Furthermore, within the body of a 'with' statement, TypeScript considers every identifier occurring in an expression (section [4.3](#4.3)) to be of the Any type regardless of its declared type. Because the 'with' statement puts a statically unknown set of identifiers in scope in front of those that are statically known, it is not possible to meaningfully assign a static type to any identifier. + +## 5.12 Switch Statements + +In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from (section [3.11.4](#3.11.4)) the type of the 'switch' expression. + +## 5.13 Throw Statements + +The expression specified in a 'throw' statement can be of any type. + +## 5.14 Try Statements + +The variable introduced by a 'catch' clause of a 'try' statement is always of type Any. It is not possible to include a type annotation in a 'catch' clause. + +
+ +#
6 Functions + +TypeScript extends JavaScript functions to include type parameters, parameter and return type annotations, overloads, default parameter values, and rest parameters. + +## 6.1 Function Declarations + +Function declarations are extended to permit the function body to be omitted in overload declarations. + +  *FunctionDeclaration:* *( Modified )* +   `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}` +   `function` *BindingIdentifieropt* *CallSignature* `;` + +A *FunctionDeclaration* introduces a named value of a function type in the containing declaration space. The *BindingIdentifier* is optional only when the function declaration occurs in an export default declaration (section [11.3.4.2](#11.3.4.2)). + +Function declarations that specify a body are called ***function implementations*** and function declarations without a body are called ***function overloads***. It is possible to specify multiple overloads for the same function (i.e. for the same name in the same declaration space), but a function can have at most one implementation. All declarations for the same function must specify the same set of modifiers (i.e. the same combination of `declare`, `export`, and `default`). + +When a function has overload declarations, the overloads determine the call signatures of the type given to the function object and the function implementation signature (if any) must be assignable to that type. Otherwise, the function implementation itself determines the call signature. + +When a function has both overloads and an implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements. + +## 6.2 Function Overloads + +Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads it is possible to statically describe the manner in which a function's return type varies based on its arguments. Overload resolution in function calls is described further in section [4.15](#4.15). + +Function overloads are purely a compile-time construct. They have no impact on the emitted JavaScript and thus no run-time cost. + +The parameter list of a function overload cannot specify default values for parameters. In other words, an overload may use only the `?` form when specifying optional parameters. + +The following is an example of a function with overloads. + +```TypeScript +function attr(name: string): string; +function attr(name: string, value: string): Accessor; +function attr(map: any): Accessor; +function attr(nameOrMap: any, value?: string): any { + if (nameOrMap && typeof nameOrMap === "string") { + // handle string case + } + else { + // handle map case + } +} +``` + +Note that each overload and the final implementation specify the same identifier. The type of the local variable 'attr' introduced by this declaration is + +```TypeScript +var attr: { + (name: string): string; + (name: string, value: string): Accessor; + (map: any): Accessor; +}; +``` + +Note that the signature of the actual function implementation is not included in the type. + +## 6.3 Function Implementations + +A function implementation without a return type annotation is said to be an ***implicitly typed function***. The return type of an implicitly typed function *f* is inferred from its function body as follows: + +* If there are no return statements with expressions in *f*'s function body, the inferred return type is Void. +* Otherwise, if *f*'s function body directly references *f* or references any implicitly typed functions that through this same analysis reference *f*, the inferred return type is Any. +* Otherwise, if *f* is a contextually typed function expression (section [4.10](#4.10)), the inferred return type is the union type (section [3.4](#3.4)) of the types of the return statement expressions in the function body, ignoring return statements with no expressions. +* Otherwise, the inferred return type is the first of the types of the return statement expressions in the function body that is a supertype (section [3.11.3](#3.11.3)) of each of the others, ignoring return statements with no expressions. A compile-time error occurs if no return statement expression has a type that is a supertype of each of the others. + +In the example + +```TypeScript +function f(x: number) { + if (x <= 0) return x; + return g(x); +} + +function g(x: number) { + return f(x - 1); +} +``` + +the inferred return type for 'f' and 'g' is Any because the functions reference themselves through a cycle with no return type annotations. Adding an explicit return type 'number' to either breaks the cycle and causes the return type 'number' to be inferred for the other. + +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. + +The type of 'this' in a function implementation is the Any type. + +In the signature of a function implementation, a parameter can be marked optional by following it with an initializer. When a parameter declaration includes both a type annotation and an initializer, the initializer expression is contextually typed (section [4.23](#4.23)) by the stated type and must be assignable to the stated type, or otherwise a compile-time error occurs. When a parameter declaration has no type annotation but includes an initializer, the type of the parameter is the widened form (section [3.12](#3.12)) of the type of the initializer expression. + +Initializer expressions are evaluated in the scope of the function body but are not permitted to reference local variables and are only permitted to access parameters that are declared to the left of the parameter they initialize, unless the parameter reference occurs in a nested function expression. + +When the output target is ECMAScript 3 or 5, for each parameter with an initializer, a statement that substitutes the default value for an omitted argument is included in the generated JavaScript, as described in section [6.6](#6.6). The example + +```TypeScript +function strange(x: number, y = x * 2, z = x + y) { + return z; +} +``` + +generates JavaScript that is equivalent to + +```TypeScript +function strange(x, y, z) { + if (y === void 0) { y = x * 2; } + if (z === void 0) { z = x + y; } + return z; +} +``` + +In the example + +```TypeScript +var x = 1; +function f(a = x) { + var x = "hello"; +} +``` + +the local variable 'x' is in scope in the parameter initializer (thus hiding the outer 'x'), but it is an error to reference it because it will always be uninitialized at the time the parameter initializer is evaluated. + +## 6.4 Destructuring Parameter Declarations + +Parameter declarations can specify binding patterns (section [3.9.2.2](#3.9.2.2)) and are then called ***destructuring parameter declarations***. Similar to a destructuring variable declaration (section [5.2.2](#5.2.2)), a destructuring parameter declaration introduces zero or more named locals and initializes them with values extracted from properties or elements of the object or array passed as an argument for the parameter. + +The type of local introduced in a destructuring parameter declaration is determined in the same manner as a local introduced by a destructuring variable declaration, except the type *T* associated with a destructuring parameter declaration is determined as follows: + +* If the declaration includes a type annotation, *T* is that type. +* If the declaration occurs in a function expression for which a contextual signature is available (section [4.10](#4.10)), *T* is the type obtained from the contextual signature. +* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.12](#3.12)) of the type of the initializer expression. +* Otherwise, if the declaration specifies a binding pattern, *T* is the implied type of that binding pattern (section [5.2.3](#5.2.3)). +* Otherwise, if the parameter is a rest parameter, *T* is `any[]`. +* Otherwise, *T* is `any`. + +When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations. + +The example + +```TypeScript +function drawText({ text = "", location: [x, y] = [0, 0], bold = false }) { + // Draw text +} +``` + +declares a function `drawText` that takes a single parameter of the type + +```TypeScript +{ text?: string; location?: [number, number]; bold?: boolean; } +``` + +When the output target is ECMAScript 3 or 5, the function is rewritten to + +```TypeScript +function drawText(_a) { + var _b = _a.text, + text = _b === void 0 ? "" : _b, + _c = _a.location, + _d = _c === void 0 ? [0, 0] : _c, + x = _d[0], + y = _d[1], + _e = _a.bold, + bold = _e === void 0 ? false : _e; + // Draw text +} +``` + +Destructuring parameter declarations do not permit type annotations on the individual binding patterns, as such annotations would conflict with the already established meaning of colons in object literals. Type annotations must instead be written on the top-level parameter declaration. For example + +```TypeScript +interface DrawTextInfo { + text?: string; + location?: [number, number]; + bold?: boolean; +} + +function drawText({ text, location: [x, y], bold }: DrawTextInfo) { + // Draw text +} +``` + +## 6.5 Generic Functions + +A function implementation may include type parameters in its signature (section [3.9.2.1](#3.9.2.1)) and is then called a ***generic function***. Type parameters provide a mechanism for expressing relationships between parameter and return types in call operations. Type parameters have no run-time representation—they are purely a compile-time construct. + +Type parameters declared in the signature of a function implementation are in scope in the signature and body of that function implementation. + +The following is an example of a generic function: + +```TypeScript +interface Comparable { + localeCompare(other: any): number; +} + +function compare(x: T, y: T): number { + if (x == null) return y == null ? 0 : -1; + if (y == null) return 1; + return x.localeCompare(y); +} +``` + +Note that the 'x' and 'y' parameters are known to be subtypes of the constraint 'Comparable' and therefore have a 'compareTo' member. This is described further in section [3.6.1](#3.6.1). + +The type arguments of a call to a generic function may be explicitly specified in a call operation or may, when possible, be inferred (section [4.15.2](#4.15.2)) from the types of the regular arguments in the call. In the example + +```TypeScript +class Person { + name: string; + localeCompare(other: Person) { + return compare(this.name, other.name); + } +} +``` + +the type argument to 'compare' is automatically inferred to be the String type because the two arguments are strings. + +## 6.6 Code Generation + +A function declaration generates JavaScript code that is equivalent to: + +```TypeScript +function () { + + +} +``` + +*FunctionName* is the name of the function (or nothing in the case of a function expression). + +*FunctionParameters* is a comma separated list of the function's parameter names. + +*DefaultValueAssignments* is a sequence of default property value assignments, one for each parameter with a default value, in the order they are declared, of the form + +```TypeScript +if ( === void 0) { = ; } +``` + +where *Parameter* is the parameter name and *Default* is the default value expression. + +*FunctionStatements* is the code generated for the statements specified in the function body. + +## 6.7 Generator Functions + +*TODO: Document [generator functions](https://github.com/Microsoft/TypeScript/issues/2873)*. + +## 6.8 Asynchronous Functions + +*TODO: Document [asynchronous functions](https://github.com/Microsoft/TypeScript/issues/1664)*. + +## 6.9 Type Guard Functions + +*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007), including [this type predicates](https://github.com/Microsoft/TypeScript/pull/5906)*. + +
+ +#
7 Interfaces + +Interfaces provide the ability to name and parameterize object types and to compose existing named object types into new ones. + +Interfaces have no run-time representation—they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions. + +Because TypeScript has a structural type system, an interface type with a particular set of members is considered identical to, and can be substituted for, another interface type or object type literal with an identical set of members (see section [3.11.2](#3.11.2)). + +Class declarations may reference interfaces in their implements clause to validate that they provide an implementation of the interfaces. + +## 7.1 Interface Declarations + +An interface declaration declares an ***interface type***. + +  *InterfaceDeclaration:* +   `interface` *BindingIdentifier* *TypeParametersopt* *InterfaceExtendsClauseopt* *ObjectType* + +  *InterfaceExtendsClause:* +   `extends` *ClassOrInterfaceTypeList* + +  *ClassOrInterfaceTypeList:* +   *ClassOrInterfaceType* +   *ClassOrInterfaceTypeList* `,` *ClassOrInterfaceType* + +  *ClassOrInterfaceType:* +   *TypeReference* + +An *InterfaceDeclaration* introduces a named type (section [3.7](#3.7)) in the containing declaration space. The *BindingIdentifier* of an interface declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). + +An interface may optionally have type parameters (section [3.6.1](#3.6.1)) that serve as placeholders for actual types to be provided when the interface is referenced in type references. An interface with type parameters is called a ***generic interface***. The type parameters of a generic interface declaration are in scope in the entire declaration and may be referenced in the *InterfaceExtendsClause* and *ObjectType* body. + +An interface can inherit from zero or more ***base types*** which are specified in the *InterfaceExtendsClause*. The base types must be type references to class or interface types. + +An interface has the members specified in the *ObjectType* of its declaration and furthermore inherits all base type members that aren't hidden by declarations in the interface: + +* A property declaration hides a public base type property with the same name. +* A string index signature declaration hides a base type string index signature. +* A numeric index signature declaration hides a base type numeric index signature. + +The following constraints must be satisfied by an interface declaration or otherwise a compile-time error occurs: + +* An interface declaration may not, directly or indirectly, specify a base type that originates in the same declaration. In other words an interface cannot, directly or indirectly, be a base type of itself, regardless of type arguments. +* An interface cannot declare a property with the same name as an inherited private or protected property. +* Inherited properties with the same name must be identical (section [3.11.2](#3.11.2)). +* All properties of the interface must satisfy the constraints implied by the index signatures of the interface as specified in section [3.9.4](#3.9.4). +* The this-type (section [3.6.3](#3.6.3)) of the declared interface must be assignable (section [3.11.4](#3.11.4)) to each of the base type references. + +An interface is permitted to inherit identical members from multiple base types and will in that case only contain one occurrence of each particular member. + +Below is an example of two interfaces that contain properties with the same name but different types: + +```TypeScript +interface Mover { + move(): void; + getStatus(): { speed: number; }; +} + +interface Shaker { + shake(): void; + getStatus(): { frequency: number; }; +} +``` + +An interface that extends 'Mover' and 'Shaker' must declare a new 'getStatus' property as it would otherwise inherit two 'getStatus' properties with different types. The new 'getStatus' property must be declared such that the resulting 'MoverShaker' is a subtype of both 'Mover' and 'Shaker': + +```TypeScript +interface MoverShaker extends Mover, Shaker { + getStatus(): { speed: number; frequency: number; }; +} +``` + +Since function and constructor types are just object types containing call and construct signatures, interfaces can be used to declare named function and constructor types. For example: + +```TypeScript +interface StringComparer { (a: string, b: string): number; } +``` + +This declares type 'StringComparer' to be a function type taking two strings and returning a number. + +## 7.2 Declaration Merging + +Interfaces are "open-ended" and interface declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single interface. + +When a generic interface has multiple declarations, all declarations must have identical type parameter lists, i.e. identical type parameter names with identical constraints in identical order. + +In an interface with multiple declarations, the `extends` clauses are merged into a single set of base types and the bodies of the interface declarations are merged into a single object type. Declaration merging produces a declaration order that corresponds to *prepending* the members of each interface declaration, in the order the members are written, to the combined list of members in the order of the interface declarations. Thus, members declared in the last interface declaration will appear first in the declaration order of the merged type. + +For example, a sequence of declarations in this order: + +```TypeScript +interface Document { + createElement(tagName: any): Element; +} + +interface Document { + createElement(tagName: string): HTMLElement; +} + +interface Document { + createElement(tagName: "div"): HTMLDivElement; + createElement(tagName: "span"): HTMLSpanElement; + createElement(tagName: "canvas"): HTMLCanvasElement; +} +``` + +is equivalent to the following single declaration: + +```TypeScript +interface Document { + createElement(tagName: "div"): HTMLDivElement; + createElement(tagName: "span"): HTMLSpanElement; + createElement(tagName: "canvas"): HTMLCanvasElement; + createElement(tagName: string): HTMLElement; + createElement(tagName: any): Element; +} +``` + +Note that the members of the last interface declaration appear first in the merged declaration. Also note that the relative order of members declared in the same interface body is preserved. + +*TODO: Document [class and interface declaration merging](https://github.com/Microsoft/TypeScript/pull/3333)*. + +## 7.3 Interfaces Extending Classes + +When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. When a class containing private or protected members is the base type of an interface type, that interface type can only be implemented by that class or a descendant class. For example: + +```TypeScript +class Control { + private state: any; +} + +interface SelectableControl extends Control { + select(): void; +} + +class Button extends Control { + select() { } +} + +class TextBox extends Control { + select() { } +} + +class Image extends Control { +} + +class Location { + select() { } +} +``` + +In the above example, 'SelectableControl' contains all of the members of 'Control', including the private 'state' property. Since 'state' is a private member it is only possible for descendants of 'Control' to implement 'SelectableControl'. This is because only descendants of 'Control' will have a 'state' private member that originates in the same declaration, which is a requirement for private members to be compatible (section [3.11](#3.11)). + +Within the 'Control' class it is possible to access the 'state' private member through an instance of 'SelectableControl'. Effectively, a 'SelectableControl' acts like a 'Control' that is known to have a 'select' method. The 'Button' and 'TextBox' classes are subtypes of 'SelectableControl' (because they both inherit from 'Control' and have a 'select' method), but the 'Image' and 'Location' classes are not. + +## 7.4 Dynamic Type Checks + +TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface. Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example, given the declarations in section [7.1](#7.1), the following is a dynamic check for the 'MoverShaker' interface: + +```TypeScript +var obj: any = getSomeObject(); +if (obj && obj.move && obj.shake && obj.getStatus) { + var moverShaker = obj; + ... +} +``` + +If such a check is used often it can be abstracted into a function: + +```TypeScript +function asMoverShaker(obj: any): MoverShaker { + return obj && obj.move && obj.shake && obj.getStatus ? obj : null; +} +``` + +
+ +#
8 Classes + +TypeScript extends JavaScript classes to include type parameters, implements clauses, accessibility modifiers, member variable declarations, and parameter property declarations in constructors. + +*TODO: Document [abstract classes](https://github.com/Microsoft/TypeScript/issues/3578)*. + +## 8.1 Class Declarations + +A class declaration declares a ***class type*** and a ***constructor function***. + +  *ClassDeclaration:* *( Modified )* +   `class` *BindingIdentifieropt* *TypeParametersopt* *ClassHeritage* `{` *ClassBody* `}` + +A *ClassDeclaration* introduces a named type (the class type) and a named value (the constructor function) in the containing declaration space. The class type is formed from the instance members declared in the class body and the instance members inherited from the base class. The constructor function is given an anonymous type formed from the constructor declaration, the static member declarations in the class body, and the static members inherited from the base class. The constructor function initializes and returns an instance of the class type. + +The *BindingIdentifier* of a class declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). The *BindingIdentifier* is optional only when the class declaration occurs in an export default declaration (section [11.3.4.2](#11.3.4.2)). + +A class may optionally have type parameters (section [3.6.1](#3.6.1)) that serve as placeholders for actual types to be provided when the class is referenced in type references. A class with type parameters is called a ***generic class***. The type parameters of a generic class declaration are in scope in the entire declaration and may be referenced in the *ClassHeritage* and *ClassBody*. + +The following example introduces both a named type called 'Point' (the class type) and a named value called 'Point' (the constructor function) in the containing declaration space. + +```TypeScript +class Point { + constructor(public x: number, public y: number) { } + public length() { return Math.sqrt(this.x * this.x + this.y * this.y); } + static origin = new Point(0, 0); +} +``` + +The named type 'Point' is exactly equivalent to + +```TypeScript +interface Point { + x: number; + y: number; + length(): number; +} +``` + +The named value 'Point' is a constructor function whose type corresponds to the declaration + +```TypeScript +var Point: { + new(x: number, y: number): Point; + origin: Point; +}; +``` + +The context in which a class is referenced distinguishes between the class type and the constructor function. For example, in the assignment statement + +```TypeScript +var p: Point = new Point(10, 20); +``` + +the identifier 'Point' in the type annotation refers to the class type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object. + +### 8.1.1 Class Heritage Specification + +*TODO: Update this section to reflect [expressions in class extends clauses](https://github.com/Microsoft/TypeScript/pull/3516)*. + +The heritage specification of a class consists of optional `extends` and `implements` clauses. The `extends` clause specifies the base class of the class and the `implements` clause specifies a set of interfaces for which to validate the class provides an implementation. + +  *ClassHeritage:* *( Modified )* +   *ClassExtendsClauseopt* *ImplementsClauseopt* + +  *ClassExtendsClause:* +   `extends`  *ClassType* + +  *ClassType:* +   *TypeReference* + +  *ImplementsClause:* +   `implements` *ClassOrInterfaceTypeList* + +A class that includes an `extends` clause is called a ***derived class***, and the class specified in the `extends` clause is called the ***base class*** of the derived class. When a class heritage specification omits the `extends` clause, the class does not have a base class. However, as is the case with every object type, type references (section [3.3.1](#3.3.1)) to the class will appear to have the members of the global interface type named 'Object' unless those members are hidden by members with the same name in the class. + +The following constraints must be satisfied by the class heritage specification or otherwise a compile-time error occurs: + +* If present, the type reference specified in the `extends` clause must denote a class type. Furthermore, the *TypeName* part of the type reference is required to be a reference to the class constructor function when evaluated as an expression. +* A class declaration may not, directly or indirectly, specify a base class that originates in the same declaration. In other words a class cannot, directly or indirectly, be a base class of itself, regardless of type arguments. +* The this-type (section [3.6.3](#3.6.3)) of the declared class must be assignable (section [3.11.4](#3.11.4)) to the base type reference and each of the type references listed in the `implements` clause. +* The constructor function type created by the class declaration must be assignable to the base class constructor function type, ignoring construct signatures. + +The following example illustrates a situation in which the first rule above would be violated: + +```TypeScript +class A { a: number; } + +namespace Foo { + var A = 1; + class B extends A { b: string; } +} +``` + +When evaluated as an expression, the type reference 'A' in the `extends` clause doesn't reference the class constructor function of 'A' (instead it references the local variable 'A'). + +The only situation in which the last two constraints above are violated is when a class overrides one or more base class members with incompatible new members. + +Note that because TypeScript has a structural type system, a class doesn't need to explicitly state that it implements an interface—it suffices for the class to simply contain the appropriate set of instance members. The `implements` clause of a class provides a mechanism to assert and validate that the class contains the appropriate sets of instance members, but otherwise it has no effect on the class type. + +### 8.1.2 Class Body + +The class body consists of zero or more constructor or member declarations. Statements are not allowed in the body of a class—they must be placed in the constructor or in members. + +  *ClassElement:* *( Modified )* +   *ConstructorDeclaration* +   *PropertyMemberDeclaration* +   *IndexMemberDeclaration* + +The body of class may optionally contain a single constructor declaration. Constructor declarations are described in section [8.3](#8.3). + +Member declarations are used to declare instance and static members of the class. Property member declarations are described in section [8.4](#8.4) and index member declarations are described in section [8.5](#8.5). + +## 8.2 Members + +The members of a class consist of the members introduced through member declarations in the class body and the members inherited from the base class. + +### 8.2.1 Instance and Static Members + +Members are either ***instance members*** or ***static members***. + +Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated this-type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of the class. + +Static members are declared using the `static` modifier and are members of the constructor function type (section [8.2.5](#8.2.5)). Within static member functions and static member accessors, the type of `this` is the constructor function type. + +Class type parameters cannot be referenced in static member declarations. + +### 8.2.2 Accessibility + +Property members have either ***public***, ***private***, or ***protected*** accessibility. The default is public accessibility, but property member declarations may include a `public`, `private`, or `protected` modifier to explicitly specify the desired accessibility. + +Public property members can be accessed everywhere without restrictions. + +Private property members can be accessed only within their declaring class. Specifically, a private member *M* declared in a class *C* can be accessed only within the class body of *C*. + +Protected property members can be accessed only within their declaring class and classes derived from their declaring class, and a protected instance property member must be accessed *through* an instance of the enclosing class or a subclass thereof. Specifically, a protected member *M* declared in a class *C* can be accessed only within the class body of *C* or the class body of a class derived from *C*. Furthermore, when a protected instance member *M* is accessed in a property access *E*`.`*M* within the body of a class *D*, the type of *E* is required to be *D* or a type that directly or indirectly has *D* as a base type, regardless of type arguments. + +Private and protected accessibility is enforced only at compile-time and serves as no more than an *indication of intent*. Since JavaScript provides no mechanism to create private and protected properties on an object, it is not possible to enforce the private and protected modifiers in dynamic code at run-time. For example, private and protected accessibility can be defeated by changing an object's static type to Any and accessing the member dynamically. + +The following example demonstrates private and protected accessibility: + +```TypeScript +class A { + private x: number; + protected y: number; + static f(a: A, b: B) { + a.x = 1; // Ok + b.x = 1; // Ok + a.y = 1; // Ok + b.y = 1; // Ok + } +} + +class B extends A { + static f(a: A, b: B) { + a.x = 1; // Error, x only accessible within A + b.x = 1; // Error, x only accessible within A + a.y = 1; // Error, y must be accessed through instance of B + b.y = 1; // Ok + } +} +``` + +In class 'A', the accesses to 'x' are permitted because 'x' is declared in 'A', and the accesses to 'y' are permitted because both take place through an instance of 'A' or a type derived from 'A'. In class 'B', access to 'x' is not permitted, and the first access to 'y' is an error because it takes place through an instance of 'A', which is not derived from the enclosing class 'B'. + +### 8.2.3 Inheritance and Overriding + +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. Only public and protected 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.11.4](#3.11.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. + +Base class static property members can be overridden by derived class static property members of any kind as long as the types are compatible, as described above. + +An index member in a derived class is said to override an index member in a base class when the derived class index member is of the same index kind (string or numeric) as the base class index member. The type of an overriding index member must be assignable (section [3.11.4](#3.11.4)) to the type of the overridden index member, or otherwise a compile-time error occurs. + +### 8.2.4 Class Types + +A class declaration declares a new named type (section [3.7](#3.7)) called a class type. Within the constructor and instance member functions of a class, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of that class type. The class type has the following members: + +* A property for each instance member variable declaration in the class body. +* A property of a function type for each instance member function declaration in the class body. +* A property for each uniquely named instance member accessor declaration in the class body. +* A property for each constructor parameter declared with a `public`, `private`, or `protected` modifier. +* An index signature for each instance index member declaration in the class body. +* All base class instance property or index members that are not overridden in the class. + +All instance property members (including those that are private or protected) of a class must satisfy the constraints implied by the index members of the class as specified in section [3.9.4](#3.9.4). + +In the example + +```TypeScript +class A { + public x: number; + public f() { } + public g(a: any) { return undefined; } + static s: string; +} + +class B extends A { + public y: number; + public g(b: boolean) { return false; } +} +``` + +the class type of 'A' is equivalent to + +```TypeScript +interface A { + x: number; + f: () => void; + g: (a: any) => any; +} +``` + +and the class type of 'B' is equivalent to + +```TypeScript +interface B { + x: number; + y: number; + f: () => void; + g: (b: boolean) => boolean; +} +``` + +Note that static declarations in a class do not contribute to the class type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of 'g' in 'B' overrides the member inherited from 'A'. + +### 8.2.5 Constructor Function Types + +The type of the constructor function introduced by a class declaration is called the constructor function type. The constructor function type has the following members: + +* If the class contains no constructor declaration and has no base class, a single construct signature with no parameters, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. +* If the class contains no constructor declaration and has a base class, a set of construct signatures with the same parameters as those of the base class constructor function type following substitution of type parameters with the type arguments specified in the base class type reference, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. +* If the class contains a constructor declaration with no overloads, a construct signature with the parameter list of the constructor implementation, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. +* If the class contains a constructor declaration with overloads, a set of construct signatures with the parameter lists of the overloads, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. +* A property for each static member variable declaration in the class body. +* A property of a function type for each static member function declaration in the class body. +* A property for each uniquely named static member accessor declaration in the class body. +* A property 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. +* All base class constructor function type properties that are not overridden in the class. + +Every class automatically contains a static property member named 'prototype', the type of which is the containing class with type Any substituted for each type parameter. + +The example + +```TypeScript +class Pair { + constructor(public item1: T1, public item2: T2) { } +} + +class TwoArrays extends Pair { } +``` + +introduces two named types corresponding to + +```TypeScript +interface Pair { + item1: T1; + item2: T2; +} + +interface TwoArrays { + item1: T[]; + item2: T[]; +} +``` + +and two constructor functions corresponding to + +```TypeScript +var Pair: { + new (item1: T1, item2: T2): Pair; +} + +var TwoArrays: { + new (item1: T[], item2: T[]): TwoArrays; +} +``` + +Note that each construct signature in the constructor function types has the same type parameters as its class and returns an instantiation of its class with those type parameters passed as type arguments. Also note that when a derived class doesn't declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type. + +## 8.3 Constructor Declarations + +A constructor declaration declares the constructor function of a class. + +  *ConstructorDeclaration:* +   *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `{` *FunctionBody* `}` +   *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `;` + +Constructor declarations that specify a body are called ***constructor implementations*** and constructor declarations without a body are called ***constructor overloads***. It is possible to specify multiple constructor overloads in a class, but a class can have at most one constructor implementation. All constructor declarations in a class must specify the same set of modifiers. Only public constructors are supported and private or protected constructors result in an error. + +In a class with no constructor declaration, an automatic constructor is provided, as described in section [8.3.3](#8.3.3). + +When a class has constructor overloads, the overloads determine the construct signatures of the type given to the constructor function object, and the constructor implementation signature (if any) must be assignable to that type. Otherwise, the constructor implementation itself determines the construct signature. This exactly parallels the way overloads are processed in a function declaration (section [6.2](#6.2)). + +When a class has both constructor overloads and a constructor implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements. + +The function body of a constructor is permitted to contain return statements. If return statements specify expressions, those expressions must be of types that are assignable to the this-type (section [3.6.3](#3.6.3)) of the class. + +The type parameters of a generic class are in scope and accessible in a constructor declaration. + +### 8.3.1 Constructor Parameters + +Similar to functions, only the constructor implementation (and not constructor overloads) can specify default value expressions for optional parameters. It is a compile-time error for such default value expressions to reference `this`. When the output target is ECMAScript 3 or 5, for each parameter with a default value, a statement that substitutes the default value for an omitted argument is included in the JavaScript generated for the constructor function. + +A parameter of a *ConstructorImplementation* may be prefixed with a `public`, `private`, or `protected` modifier. This is called a ***parameter property declaration*** and is shorthand for declaring a property with the same name as the parameter and initializing it with the value of the parameter. For example, the declaration + +```TypeScript +class Point { + constructor(public x: number, public y: number) { + // Constructor body + } +} +``` + +is equivalent to writing + +```TypeScript +class Point { + public x: number; + public y: number; + constructor(x: number, y: number) { + this.x = x; + this.y = y; + // Constructor body + } +} +``` + +A parameter property declaration may declare an optional parameter (by including a question mark or a default value), but the property introduced by such a declaration is always considered a required property (section [3.3.6](#3.3.6)). + +### 8.3.2 Super Calls + +Super calls (section [4.9.1](#4.9.1)) are used to call the constructor of the base class. A super call consists of the keyword `super` followed by an argument list enclosed in parentheses. For example: + +```TypeScript +class ColoredPoint extends Point { + constructor(x: number, y: number, public color: string) { + super(x, y); + } +} +``` + +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. Super calls are not permitted outside constructors or in local functions inside constructors. + +The first statement in the body of a constructor *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. + +In such a required super call, it is a compile-time error for argument expressions to reference `this`. + +Initialization of parameter properties and instance member variables with initializers takes place immediately at the beginning of the constructor body if the class has no base class, or immediately following the super call if the class is a derived class. + +### 8.3.3 Automatic Constructors + +If a class omits a constructor declaration, an ***automatic constructor*** is provided. + +In a class with no `extends` clause, the automatic constructor has no parameters and performs no action other than executing the instance member variable initializers (section [8.4.1](#8.4.1)), if any. + +In a derived class, the automatic constructor has the same parameter list (and possibly overloads) as the base class constructor. The automatically provided constructor first forwards the call to the base class constructor using a call equivalent to + +```TypeScript +BaseClass.apply(this, arguments); +``` + +and then executes the instance member variable initializers, if any. + +## 8.4 Property Member Declarations + +Property member declarations can be member variable declarations, member function declarations, or member accessor declarations. + +  *PropertyMemberDeclaration:* +   *MemberVariableDeclaration* +   *MemberFunctionDeclaration* +   *MemberAccessorDeclaration* + +Member declarations without a `static` modifier are called instance member declarations. Instance property member declarations declare properties in the class type (section [8.2.4](#8.2.4)), and must specify names that are unique among all instance property member and parameter property declarations in the containing class, with the exception that instance get and set accessor declarations may pairwise specify the same name. + +Member declarations with a `static` modifier are called static member declarations. Static property member declarations declare properties in the constructor function type (section [8.2.5](#8.2.5)), and must specify names that are unique among all static property member declarations in the containing class, with the exception that static get and set accessor declarations may pairwise specify the same name. + +Note that the declaration spaces of instance and static property members are separate. Thus, it is possible to have instance and static property members with the same name. + +Except for overrides, as described in section [8.2.3](#8.2.3), it is an error for a derived class to declare a property member with the same name and kind (instance or static) as a base class member. + +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'. + +Below is an example of a class containing both instance and static property member declarations: + +```TypeScript +class Point { + constructor(public x: number, public y: number) { } + public distance(p: Point) { + var dx = this.x - p.x; + var dy = this.y - p.y; + return Math.sqrt(dx * dx + dy * dy); + } + static origin = new Point(0, 0); + static distance(p1: Point, p2: Point) { return p1.distance(p2); } +} +``` + +The class type 'Point' has the members: + +```TypeScript +interface Point { + x: number; + y: number; + distance(p: Point); +} +``` + +and the constructor function 'Point' has a type corresponding to the declaration: + +```TypeScript +var Point: { + new(x: number, y: number): Point; + origin: Point; + distance(p1: Point, p2: Point): number; +} +``` + +### 8.4.1 Member Variable Declarations + +A member variable declaration declares an instance member variable or a static member variable. + +  *MemberVariableDeclaration:* +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* *Initializeropt* `;` + +The type associated with a member variable declaration is determined in the same manner as an ordinary variable declaration (see section [5.2](#5.2)). + +An instance member variable declaration introduces a member in the class type and optionally initializes a property on instances of the class. Initializers in instance member variable declarations are executed once for every new instance of the class and are equivalent to assignments to properties of `this` in the constructor. In an initializer expression for an instance member variable, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. + +A static member variable declaration introduces a property in the constructor function type and optionally initializes a property on the constructor function object. Initializers in static member variable declarations are executed once when the containing script or module is loaded. + +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. + +Since instance member variable initializers are equivalent to assignments to properties of `this` in the constructor, the example + +```TypeScript +class Employee { + public name: string; + public address: string; + public retired = false; + public manager: Employee = null; + public reports: Employee[] = []; +} +``` + +is equivalent to + +```TypeScript +class Employee { + public name: string; + public address: string; + public retired: boolean; + public manager: Employee; + public reports: Employee[]; + constructor() { + this.retired = false; + this.manager = null; + this.reports = []; + } +} +``` + +### 8.4.2 Member Function Declarations + +A member function declaration declares an instance member function or a static member function. + +  *MemberFunctionDeclaration:* +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `{` *FunctionBody* `}` +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;` + +A member function declaration is processed in the same manner as an ordinary function declaration (section [6](#6)), except that in a member function `this` has a known type. + +All declarations for the same member function must specify the same accessibility (public, private, or protected) and kind (instance or static). + +An instance member function declaration declares a property in the class type and assigns a function object to a property on the prototype object of the class. In the body of an instance member function declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. + +A static member function declaration declares a property in the constructor function type and assigns a function object to a property on the constructor function object. In the body of a static member function declaration, the type of `this` is the constructor function type. + +A member function can access overridden base class members using a super property access (section [4.9.2](#4.9.2)). For example + +```TypeScript +class Point { + constructor(public x: number, public y: number) { } + public toString() { + return "x=" + this.x + " y=" + this.y; + } +} + +class ColoredPoint extends Point { + constructor(x: number, y: number, public color: string) { + super(x, y); + } + public toString() { + return super.toString() + " color=" + this.color; + } +} +``` + +In a static member function, `this` represents the constructor function object on which the static member function was invoked. Thus, a call to 'new this()' may actually invoke a derived class constructor: + +```TypeScript +class A { + a = 1; + static create() { + return new this(); + } +} + +class B extends A { + b = 2; +} + +var x = A.create(); // new A() +var y = B.create(); // new B() +``` + +Note that TypeScript doesn't require or verify that derived constructor functions are subtypes of base constructor functions. In other words, changing the declaration of 'B' to + +```TypeScript +class B extends A { + constructor(public b: number) { + super(); + } +} +``` + +does not cause errors in the example, even though the call to the constructor from the 'create' function doesn't specify an argument (thus giving the value 'undefined' to 'b'). + +### 8.4.3 Member Accessor Declarations + +A member accessor declaration declares an instance member accessor or a static member accessor. + +  *MemberAccessorDeclaration:* +   *AccessibilityModifieropt* `static`*opt* *GetAccessor* +   *AccessibilityModifieropt* `static`*opt* *SetAccessor* + +Get and set accessors are processed in the same manner as in an object literal (section [4.5](#4.5)), except that a contextual type is never available in a member accessor declaration. + +Accessors for the same member name must specify the same accessibility. + +An instance member accessor declaration declares a property in the class type and defines a property on the prototype object of the class with a get or set accessor. In the body of an instance member accessor declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. + +A static member accessor declaration declares a property in the constructor function type and defines a property on the constructor function object of the class with a get or set accessor. In the body of a static member accessor declaration, the type of `this` is the constructor function type. + +Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.7.1](#8.7.1). + +### 8.4.4 Dynamic Property Declarations + +If the *PropertyName* of a property member declaration is a computed property name that doesn't denote a well-known symbol ([2.2.3](#2.2.3)), the construct is considered a ***dynamic property declaration***. The following rules apply to dynamic property declarations: + +* A dynamic property declaration does not introduce a property in the class type or constructor function type. +* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type. +* The name associated with a dynamic property declarations is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type. + +## 8.5 Index Member Declarations + +An index member declaration introduces an index signature (section [3.9.4](#3.9.4)) in the class type. + +  *IndexMemberDeclaration:* +   *IndexSignature* `;` + +Index member declarations have no body and cannot specify an accessibility modifier. + +A class declaration can have at most one string index member declaration and one numeric index member declaration. All instance property members of a class must satisfy the constraints implied by the index members of the class as specified in section [3.9.4](#3.9.4). + +It is not possible to declare index members for the static side of a class. + +Note that it is seldom meaningful to include a string index signature in a class because it constrains all instance properties of the class. However, numeric index signatures can be useful to control the element type when a class is used in an array-like manner. + +## 8.6 Decorators + +*TODO: Document [decorators](https://github.com/Microsoft/TypeScript/issues/2249)*. + +## 8.7 Code Generation + +When the output target is ECMAScript 2015 or higher, type parameters, implements clauses, accessibility modifiers, and member variable declarations are removed in the emitted code, but otherwise class declarations are emitted as written. When the output target is ECMAScript 3 or 5, more comprehensive rewrites are performed, as described in this section. + +### 8.7.1 Classes Without Extends Clauses + +A class with no `extends` clause generates JavaScript equivalent to the following: + +```TypeScript +var = (function () { + function () { + + + + + } + + + return ; +})(); +``` + +*ClassName* is the name of the class. + +*ConstructorParameters* is a comma separated list of the constructor's parameter names. + +*DefaultValueAssignments* is a sequence of default property value assignments corresponding to those generated for a regular function declaration, as described in section [6.6](#6.6). + +*ParameterPropertyAssignments* is a sequence of assignments, one for each parameter property declaration in the constructor, in order they are declared, of the form + +```TypeScript +this. = ; +``` + +where *ParameterName* is the name of a parameter property. + +*MemberVariableAssignments* is a sequence of assignments, one for each instance member variable declaration with an initializer, in the order they are declared, of the form + +```TypeScript +this. = ; +``` + +where *MemberName* is the name of the member variable and *InitializerExpression* is the code generated for the initializer expression. + +*ConstructorStatements* is the code generated for the statements specified in the constructor body. + +*MemberFunctionStatements* is a sequence of statements, one for each member function declaration or member accessor declaration, in the order they are declared. + +An instance member function declaration generates a statement of the form + +```TypeScript +.prototype. = function () { + + +} +``` + +and static member function declaration generates a statement of the form + +```TypeScript +. = function () { + + +} +``` + +where *MemberName* is the name of the member function, and *FunctionParameters*, *DefaultValueAssignments*, and *FunctionStatements* correspond to those generated for a regular function declaration, as described in section [6.6](#6.6). + +A get or set instance member accessor declaration, or a pair of get and set instance member accessor declarations with the same name, generates a statement of the form + +```TypeScript +Object.defineProperty(.prototype, "", { + get: function () { + + }, + set: function () { + + }, + enumerable: true, + configurable: true +}; +``` + +and a get or set static member accessor declaration, or a pair of get and set static member accessor declarations with the same name, generates a statement of the form + +```TypeScript +Object.defineProperty(, "", { + get: function () { + + }, + set: function () { + + }, + enumerable: true, + configurable: true +}; +``` + +where *MemberName* is the name of the member accessor, *GetAccessorStatements* is the code generated for the statements in the get acessor's function body, *ParameterName* is the name of the set accessor parameter, and *SetAccessorStatements* is the code generated for the statements in the set accessor's function body. The 'get' property is included only if a get accessor is declared and the 'set' property is included only if a set accessor is declared. + +*StaticVariableAssignments* is a sequence of statements, one for each static member variable declaration with an initializer, in the order they are declared, of the form + +```TypeScript +. = ; +``` + +where *MemberName* is the name of the static variable, and *InitializerExpression* is the code generated for the initializer expression. + +### 8.7.2 Classes With Extends Clauses + +A class with an `extends` clause generates JavaScript equivalent to the following: + +```TypeScript +var = (function (_super) { + __extends(, _super); + function () { + + + + + + } + + + return ; +})(); +``` + +In addition, the '__extends' function below is emitted at the beginning of the JavaScript source file. It copies all properties from the base constructor function object to the derived constructor function object (in order to inherit static members), and appropriately establishes the 'prototype' property of the derived constructor function object. + +```TypeScript +var __extends = this.__extends || function(d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function f() { this.constructor = d; } + f.prototype = b.prototype; + d.prototype = new f(); +} +``` + +*BaseClassName* is the class name specified in the `extends` clause. + +If the class has no explicitly declared constructor, the *SuperCallStatement* takes the form + +```TypeScript +_super.apply(this, arguments); +``` + +Otherwise the *SuperCallStatement* is present if the constructor function is required to start with a super call, as discussed in section [8.3.2](#8.3.2), and takes the form + +```TypeScript +_super.call(this, ) +``` + +where *SuperCallArguments* is the argument list specified in the super call. Note that this call precedes the code generated for parameter properties and member variables with initializers. Super calls elsewhere in the constructor generate similar code, but the code generated for such calls will be part of the *ConstructorStatements* section. + +A super property access in the constructor, an instance member function, or an instance member accessor generates JavaScript equivalent to + +```TypeScript +_super.prototype. +``` + +where *PropertyName* is the name of the referenced base class property. When the super property access appears in a function call, the generated JavaScript is equivalent to + +```TypeScript +_super.prototype..call(this, ) +``` + +where Arguments is the code generated for the argument list specified in the function call. + +A super property access in a static member function or a static member accessor generates JavaScript equivalent to + +```TypeScript +_super. +``` + +where *PropertyName* is the name of the referenced base class property. When the super property access appears in a function call, the generated JavaScript is equivalent to + +```TypeScript +_super..call(this, ) +``` + +where Arguments is the code generated for the argument list specified in the function call. + +
+ +#
9 Enums + +An enum type is a distinct subtype of the Number primitive type with an associated set of named constants that define the possible values of the enum type. + +## 9.1 Enum Declarations + +An enum declaration declares an ***enum type*** and an ***enum object***. + +  *EnumDeclaration:* +   `const`*opt* `enum` *BindingIdentifier* `{` *EnumBodyopt* `}` + +An *EnumDeclaration* introduces a named type (the enum type) and a named value (the enum object) in the containing declaration space. The enum type is a distinct subtype of the Number primitive type. The enum object is a value of an anonymous object type containing a set of properties, all of the enum type, corresponding to the values declared for the enum type in the body of the declaration. The enum object's type furthermore includes a numeric index signature with the signature '[x: number]: string'. + +The *BindingIdentifier* of an enum declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). + +When an enum declaration includes a `const` modifier it is said to be a constant enum declaration. The members of a constant enum declaration must all have constant values that can be computed at compile time. Constant enum declarations are discussed in section [9.4](#9.4). + +The example + +```TypeScript +enum Color { Red, Green, Blue } +``` + +declares a subtype of the Number primitive type called 'Color' and introduces a variable 'Color' with a type that corresponds to the declaration + +```TypeScript +var Color: { + [x: number]: string; + Red: Color; + Green: Color; + Blue: Color; +}; +``` + +The numeric index signature reflects a "reverse mapping" that is automatically generated in every enum object, as described in section [9.5](#9.5). The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example + +```TypeScript +var c = Color.Red; +console.log(Color[c]); // Outputs "Red" +``` + +## 9.2 Enum Members + +The body of an enum declaration defines zero or more enum members which are the named values of the enum type. Each enum member has an associated numeric value of the primitive type introduced by the enum declaration. + +  *EnumBody:* +   *EnumMemberList* `,`*opt* + +  *EnumMemberList:* +   *EnumMember* +   *EnumMemberList* `,` *EnumMember* + +  *EnumMember:* +   *PropertyName* +   *PropertyName* = *EnumValue* + +  *EnumValue:* +   *AssignmentExpression* + +The *PropertyName* of an enum member cannot be a computed property name ([2.2.3](#2.2.3)). + +Enum members are either ***constant members*** or ***computed members***. Constant members have known constant values that are substituted in place of references to the members in the generated JavaScript code. Computed members have values that are computed at run-time and not known at compile-time. No substitution is performed for references to computed members. + +An enum member is classified as follows: + +* 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 the member declaration specifies a value that can be classified as a constant enum expression (as defined below), the member is considered a constant enum member. +* Otherwise, the member is considered a computed enum member. + +Enum value expressions must be of type Any, the Number primitive type, or the enum type itself. + +A ***constant enum expression*** is a subset of the expression grammar that can be evaluated fully at compile time. An expression is considered a constant enum expression if it is one of the following: + +* A numeric literal. +* An identifier or property access that denotes a previously declared member in the same constant enum declaration. +* A parenthesized constant enum expression. +* A +, –, or ~ unary operator applied to a constant enum expression. +* A +, –, *, /, %, <<, >>, >>>, &, ^, or | operator applied to two constant enum expressions. + +In the example + +```TypeScript +enum Test { + A, + B, + C = Math.floor(Math.random() * 1000), + D = 10, + E +} +``` + +'A', 'B', 'D', and 'E' are constant members with values 0, 1, 10, and 11 respectively, and 'C' is a computed member. + +In the example + +```TypeScript +enum Style { + None = 0, + Bold = 1, + Italic = 2, + Underline = 4, + Emphasis = Bold | Italic, + Hyperlink = Bold | Underline +} +``` + +all members are constant members. Note that enum member declarations can reference other enum members without qualification. Also, because enums are subtypes of the Number primitive type, numeric operators, such as the bitwise OR operator, can be used to compute enum values. + +## 9.3 Declaration Merging + +Enums are "open-ended" and enum declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) define a single enum type and contribute to a single enum object. + +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. + +When enum declarations are merged, they must either all specify a `const` modifier or all specify no `const` modifier. + +## 9.4 Constant Enum Declarations + +An enum declaration that specifies a `const` modifier is a ***constant enum declaration***. In a constant enum declaration, all members must have constant values and it is an error for a member declaration to specify an expression that isn't classified as a constant enum expression. + +Unlike regular enum declarations, constant enum declarations are completely erased in the emitted JavaScript code. For this reason, it is an error to reference a constant enum object in any other context than a property access that selects one of the enum's members. For example: + +```TypeScript +const enum Comparison { + LessThan = -1, + EqualTo = 0, + GreaterThan = 1 +} + +var x = Comparison.EqualTo; // Ok, replaced with 0 in emitted code +var y = Comparison[Comparison.EqualTo]; // Error +var z = Comparison; // Error +``` + +The entire const enum declaration is erased in the emitted JavaScript code. Thus, the only permitted references to the enum object are those that are replaced with an enum member value. + +## 9.5 Code Generation + +An enum declaration generates JavaScript equivalent to the following: + +```TypeScript +var ; +(function () { + +})(||(={})); +``` + +*EnumName* is the name of the enum. + +*EnumMemberAssignments* is a sequence of assignments, one for each enum member, in order they are declared, of the form + +```TypeScript +[[""] = ] = ""; +``` + +where *MemberName* is the name of the enum member and *Value* is the assigned constant value or the code generated for the computed value expression. + +For example, the 'Color' enum example from section [9.1](#9.1) generates the following JavaScript: + +```TypeScript +var Color; +(function (Color) { + Color[Color["Red"] = 0] = "Red"; + Color[Color["Green"] = 1] = "Green"; + Color[Color["Blue"] = 2] = "Blue"; +})(Color||(Color={})); +``` + +
+ +#
10 Namespaces + +Namespaces provide a mechanism for organizing code and declarations in hierarchies of named containers. Namespaces have named members that each denote a value, a type, or a namespace, or some combination thereof, and those members may be local or exported. The body of a namespace corresponds to a function that is executed once, thereby providing a mechanism for maintaining local state with assured isolation. Namespaces can be thought of as a formalization of the [immediately-invoked function expression](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) (IIFE) pattern. + +## 10.1 Namespace Declarations + +A namespace declaration introduces a name with a namespace meaning and, in the case of an instantiated namespace, a value meaning in the containing declaration space. + +  *NamespaceDeclaration:* +   `namespace` *IdentifierPath* `{` *NamespaceBody* `}` + +  *IdentifierPath:* +   *BindingIdentifier* +   *IdentifierPath* `.` *BindingIdentifier* + +Namespaces are declared using the `namespace` keyword, but for backward compatibility of earlier versions of TypeScript a `module` keyword can also be used. + +Namespaces are either ***instantiated*** or ***non-instantiated***. A non-instantiated namespace is a namespace containing only interface types, type aliases, and other non-instantiated namespace. An instantiated namespace is a namespace that doesn't meet this definition. In intuitive terms, an instantiated namespace is one for which a namespace instance is created, whereas a non-instantiated namespace is one for which no code is generated. + +When a namespace identifier is referenced as a *NamespaceName* (section [3.8.2](#3.8.2)) it denotes a container of namespace and type names, and when a namespace identifier is referenced as a *PrimaryExpression* (section [4.3](#4.3)) it denotes the singleton namespace instance. For example: + +```TypeScript +namespace M { + export interface P { x: number; y: number; } + export var a = 1; +} + +var p: M.P; // M used as NamespaceName +var m = M; // M used as PrimaryExpression +var x1 = M.a; // M used as PrimaryExpression +var x2 = m.a; // Same as M.a +var q: m.P; // Error +``` + +Above, when 'M' is used as a *PrimaryExpression* it denotes an object instance with a single member 'a' and when 'M' is used as a *NamespaceName* it denotes a container with a single type member 'P'. The final line in the example is an error because 'm' is a variable which cannot be referenced in a type name. + +If the declaration of 'M' above had excluded the exported variable 'a', 'M' would be a non-instantiated namespace and it would be an error to reference 'M' as a *PrimaryExpression*. + +A namespace declaration that specifies an *IdentifierPath* with more than one identifier is equivalent to a series of nested single-identifier namespace declarations where all but the outermost are automatically exported. For example: + +```TypeScript +namespace A.B.C { + export var x = 1; +} +``` + +corresponds to + +```TypeScript +namespace A { + export namespace B { + export namespace C { + export var x = 1; + } + } +} +``` + +The hierarchy formed by namespace and named type names partially mirrors that formed by namespace instances and members. The example + +```TypeScript +namespace A { + export namespace B { + export class C { } + } +} +``` + +introduces a named type with the qualified name 'A.B.C' and also introduces a constructor function that can be accessed using the expression 'A.B.C'. Thus, in the example + +```TypeScript +var c: A.B.C = new A.B.C(); +``` + +the two occurrences of 'A.B.C' in fact refer to different entities. It is the context of the occurrences that determines whether 'A.B.C' is processed as a type name or an expression. + +## 10.2 Namespace Body + +The body of a namespace corresponds to a function that is executed once to initialize the namespace instance. + +  *NamespaceBody:* +   *NamespaceElementsopt* + +  *NamespaceElements:* +   *NamespaceElement* +   *NamespaceElements* *NamespaceElement* + +  *NamespaceElement:* +   *Statement* +   *LexicalDeclaration* +   *FunctionDeclaration* +   *GeneratorDeclaration* +   *ClassDeclaration* +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *EnumDeclaration* +   *NamespaceDeclaration +   AmbientDeclaration +   ImportAliasDeclaration +   ExportNamespaceElement* + +  *ExportNamespaceElement:* +   `export` *VariableStatement* +   `export` *LexicalDeclaration* +   `export` *FunctionDeclaration* +   `export` *GeneratorDeclaration* +   `export` *ClassDeclaration* +   `export` *InterfaceDeclaration* +   `export` *TypeAliasDeclaration* +   `export` *EnumDeclaration* +   `export` *NamespaceDeclaration* +   `export` *AmbientDeclaration* +   `export` *ImportAliasDeclaration* + +## 10.3 Import Alias Declarations + +Import alias declarations are used to create local aliases for entities in other namespaces. + +  *ImportAliasDeclaration:* +   `import` *BindingIdentifier* `=` *EntityName* `;` + +  *EntityName:* +   *NamespaceName* +   *NamespaceName* `.` *IdentifierReference* + +An *EntityName* consisting of a single identifier is resolved as a *NamespaceName* and is thus required to reference a namespace. The resulting local alias references the given namespace and is itself classified as a namespace. + +An *EntityName* consisting of more than one identifier is resolved as a *NamespaceName* followed by an identifier that names an exported entity in the given namespace. The resulting local alias has all the meanings of the referenced entity. (As many as three distinct meanings are possible for an entity name—value, type, and namespace.) In effect, it is as if the imported entity was declared locally with the local alias name. + +In the example + +```TypeScript +namespace A { + export interface X { s: string } + export var X: X; +} + +namespace B { + interface A { n: number } + import Y = A; // Alias for namespace A + import Z = A.X; // Alias for type and value A.X + var v: Z = Z; +} +``` + +within 'B', 'Y' is an alias only for namespace 'A' and not the local interface 'A', whereas 'Z' is an alias for all exported meanings of 'A.X', thus denoting both an interface type and a variable. + +If the *NamespaceName* portion of an *EntityName* references an instantiated namespace, the *NamespaceName* is required to reference the namespace instance when evaluated as an expression. In the example + +```TypeScript +namespace A { + export interface X { s: string } +} + +namespace B { + var A = 1; + import Y = A; +} +``` + +'Y' is a local alias for the non-instantiated namespace 'A'. If the declaration of 'A' is changed such that 'A' becomes an instantiated namespace, for example by including a variable declaration in 'A', the import statement in 'B' above would be an error because the expression 'A' doesn't reference the namespace instance of namespace 'A'. + +When an import statement includes an export modifier, all meanings of the local alias are exported. + +## 10.4 Export Declarations + +An export declaration declares an externally accessible namespace member. An export declaration is simply a regular declaration prefixed with the keyword `export`. + +The members of a namespace's export declaration space (section [2.3](#2.3)) constitute the namespace's ***export member set***. A namespace's ***instance type*** is an object type with a property for each member in the namespace's export member set that denotes a value. + +An exported member depends on a (possibly empty) set of named types (section [3.7](#3.7)). Those named types must be at least as accessible as the exported member, or otherwise an error occurs. + +The named types upon which a member depends are the named types occurring in the transitive closure of the ***directly depends on*** relationship defined as follows: + +* A variable directly depends on the *Type* specified in its type annotation. +* A function directly depends on each *Type* specified in a parameter or return type annotation. +* A class directly depends on each *Type* specified as a type parameter constraint, each *TypeReference* specified as a base class or implemented interface, and each *Type* specified in a constructor parameter type annotation, public member variable type annotation, public member function parameter or return type annotation, public member accessor parameter or return type annotation, or index signature type annotation. +* An interface directly depends on each *Type* specified as a type parameter constraint, each *TypeReference* specified as a base interface, and the *ObjectType* specified as its body. +* A namespace directly depends on its exported members. +* A *Type* or *ObjectType* directly depends on every *TypeReference* that occurs within the type at any level of nesting. +* A *TypeReference* directly depends on the type it references and on each *Type* specified as a type argument. + +A named type *T* having a root namespace *R* (section [2.3](#2.3)) is said to be ***at least as accessible as*** a member *M* if + +* *R* is the global namespace or a module, or +* *R* is a namespace in the parent namespace chain of *M*. + +In the example + +```TypeScript +interface A { x: string; } + +namespace M { + export interface B { x: A; } + export interface C { x: B; } + export function foo(c: C) { … } +} +``` + +the 'foo' function depends upon the named types 'A', 'B', and 'C'. In order to export 'foo' it is necessary to also export 'B' and 'C' as they otherwise would not be at least as accessible as 'foo'. The 'A' interface is already at least as accessible as 'foo' because I t is declared in a parent namespace of foo's namespace. + +## 10.5 Declaration Merging + +Namespaces are "open-ended" and namespace declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single namespace. For example, the following two declarations of a namespace 'outer' might be located in separate source files. + +File a.ts: + +```TypeScript +namespace outer { + var local = 1; // Non-exported local variable + export var a = local; // outer.a + export namespace inner { + export var x = 10; // outer.inner.x + } +} +``` + +File b.ts: + +```TypeScript +namespace outer { + var local = 2; // Non-exported local variable + export var b = local; // outer.b + export namespace inner { + export var y = 20; // outer.inner.y + } +} +``` + +Assuming the two source files are part of the same program, the two declarations will have the global namespace as their common root and will therefore contribute to the same namespace instance, the instance type of which will be: + +```TypeScript +{ + a: number; + b: number; + inner: { + x: number; + y: number; + }; +} +``` + +Declaration merging does not apply to local aliases created by import alias declarations. In other words, it is not possible have an import alias declaration and a namespace declaration for the same name within the same namespace body. + +*TODO: Clarify rules for [alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*. + +Declaration merging also extends to namespace declarations with the same qualified name relative to a common root as a function, class, or enum declaration: + +* When merging a function and a namespace, the type of the function object is merged with the instance type of the namespace. In effect, the overloads or implementation of the function provide the call signatures and the exported members of the namespace provide the properties of the combined type. +* When merging a class and a namespace, the type of the constructor function object is merged with the instance type of the namespace. In effect, the overloads or implementation of the class constructor provide the construct signatures, and the static members of the class and exported members of the namespace provide the properties of the combined type. It is an error to have static class members and exported namespace members with the same name. +* When merging an enum and a namespace, the type of the enum object is merged with the instance type of the namespace. In effect, the members of the enum and the exported members of the namespace provide the properties of the combined type. It is an error to have enum members and exported namespace members with the same name. + +When merging a non-ambient function or class declaration and a non-ambient namespace declaration, the function or class declaration must be located prior to the namespace declaration in the same source file. This ensures that the shared object instance is created as a function object. (While it is possible to add properties to an object after its creation, it is not possible to make an object "callable" after the fact.) + +The example + +```TypeScript +interface Point { + x: number; + y: number; +} + +function point(x: number, y: number): Point { + return { x: x, y: y }; +} + +namespace point { + export var origin = point(0, 0); + export function equals(p1: Point, p2: Point) { + return p1.x == p2.x && p1.y == p2.y; + } +} + +var p1 = point(0, 0); +var p2 = point.origin; +var b = point.equals(p1, p2); +``` + +declares 'point' as a function object with two properties, 'origin' and 'equals'. Note that the namespace declaration for 'point' is located after the function declaration. + +## 10.6 Code Generation + +A namespace generates JavaScript code that is equivalent to the following: + +```TypeScript +var ; +(function() { + +})(||(={})); +``` + +where *NamespaceName* is the name of the namespace and *NamespaceStatements* is the code generated for the statements in the namespace body. The *NamespaceName* function parameter may be prefixed with one or more underscore characters to ensure the name is unique within the function body. Note that the entire namespace is emitted as an anonymous function that is immediately executed. This ensures that local variables are in their own lexical environment isolated from the surrounding context. Also note that the generated function doesn't create and return a namespace instance, but rather it extends the existing instance (which may have just been created in the function call). This ensures that namespaces can extend each other. + +An import statement generates code of the form + +```TypeScript +var = ; +``` + +This code is emitted only if the imported entity is referenced as a *PrimaryExpression* somewhere in the body of the importing namespace. If an imported entity is referenced only as a *TypeName* or *NamespaceName*, nothing is emitted. This ensures that types declared in one namespace can be referenced through an import alias in another namespace with no run-time overhead. + +When a variable is exported, all references to the variable in the body of the namespace are replaced with + +```TypeScript +. +``` + +This effectively promotes the variable to be a property on the namespace instance and ensures that all references to the variable become references to the property. + +When a function, class, enum, or namespace is exported, the code generated for the entity is followed by an assignment statement of the form + +```TypeScript +. = ; +``` + +This copies a reference to the entity into a property on the namespace instance. + +
+ +#
11 Scripts and Modules + +TypeScript implements support for ECMAScript 2015 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems. + +## 11.1 Programs and Source Files + +A TypeScript ***program*** consists of one or more source files. + +  *SourceFile:* +   *ImplementationSourceFile* +   *DeclarationSourceFile* + +  *ImplementationSourceFile:* +   *ImplementationScript* +   *ImplementationModule* + +  *DeclarationSourceFile:* +   *DeclarationScript* +   *DeclarationModule* + +Source files with extension '.ts' are ***implementation source files*** containing statements and declarations, and source files with extension '.d.ts' are ***declaration source files*** containing declarations only. + +Declaration source files are a strict subset of implementation source files and are used to declare the static type information associated with existing JavaScript code in an adjunct manner. They are entirely optional but enable the TypeScript compiler and tools to provide better verification and assistance when integrating existing JavaScript code and libraries in a TypeScript application. + +When a TypeScript program is compiled, all of the program's source files are processed together. Statements and declarations in different source files can depend on each other, possibly in a circular fashion. By default, a JavaScript output file is generated for each implementation source file in a compilation, but no output is generated from declaration source files. + +### 11.1.1 Source Files Dependencies + +The TypeScript compiler automatically determines a source file's dependencies and includes those dependencies in the program being compiled. The determination is made from "reference comments" and module import declarations as follows: + +* A comment of the form /// <reference path="…"/> that occurs before the first token in a source file adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file. +* A module import declaration that specifies a relative module name (section [11.3.1](#11.3.1)) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension '.ts' exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension '.d.ts' exists, that file is added as a dependency. +* A module import declaration that specifies a top-level module name (section [11.3.1](#11.3.1)) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension '.ts' or '.d.ts' corresponding to the reference is located, that file is added as a dependency. + +Any files included as dependencies in turn have their references analyzed in a transitive manner until all dependencies have been determined. + +## 11.2 Scripts + +Source files that contain no module import or export declarations are classified as ***scripts***. Scripts form the single ***global namespace*** and entities declared in scripts are in scope everywhere in a program. + +  *ImplementationScript:* +   *ImplementationScriptElementsopt* + +  *ImplementationScriptElements:* +   *ImplementationScriptElement* +   *ImplementationScriptElements* *ImplementationScriptElement* + +  *ImplementationScriptElement:* +   *ImplementationElement* +   *AmbientModuleDeclaration* + +  *ImplementationElement:* +   *Statement* +   *LexicalDeclaration* +   *FunctionDeclaration* +   *GeneratorDeclaration* +   *ClassDeclaration* +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *EnumDeclaration* +   *NamespaceDeclaration* +   *AmbientDeclaration* +   *ImportAliasDeclaration* + +  *DeclarationScript:* +   *DeclarationScriptElementsopt* + +  *DeclarationScriptElements:* +   *DeclarationScriptElement* +   *DeclarationScriptElements* *DeclarationScriptElement* + +  *DeclarationScriptElement:* +   *DeclarationElement* +   *AmbientModuleDeclaration* + +  *DeclarationElement:* +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *NamespaceDeclaration* +   *AmbientDeclaration* +   *ImportAliasDeclaration* + +The initialization order of the scripts that make up the global namespace ultimately depends on the order in which the generated JavaScript files are loaded at run-time (which, for example, may be controlled by <script/> tags that reference the generated JavaScript files). + +## 11.3 Modules + +Source files that contain at least one module import or export declaration are considered separate ***modules***. Non-exported entities declared in a module are in scope only in that module, but exported entities can be imported into other modules using import declarations. + +  *ImplementationModule:* +   *ImplementationModuleElementsopt* + +  *ImplementationModuleElements:* +   *ImplementationModuleElement* +   *ImplementationModuleElements* *ImplementationModuleElement* + +  *ImplementationModuleElement:* +   *ImplementationElement* +   *ImportDeclaration* +   *ImportAliasDeclaration* +   *ImportRequireDeclaration* +   *ExportImplementationElement* +   *ExportDefaultImplementationElement* +   *ExportListDeclaration* +   *ExportAssignment* + +  *DeclarationModule:* +   *DeclarationModuleElementsopt* + +  *DeclarationModuleElements:* +   *DeclarationModuleElement* +   *DeclarationModuleElements* *DeclarationModuleElement* + +  *DeclarationModuleElement:* +   *DeclarationElement* +   *ImportDeclaration* +   *ImportAliasDeclaration* +   *ExportDeclarationElement* +   *ExportDefaultDeclarationElement* +   *ExportListDeclaration* +   *ExportAssignment* + +Initialization order of modules is determined by the module loader being used and is not specified by the TypeScript language. However, it is generally the case that non-circularly dependent modules are automatically loaded and initialized in the correct order. + +Modules can additionally be declared using *AmbientModuleDeclarations* in declaration scripts that directly specify the module names as string literals. This is described further in section [12.2](#12.2). + +Below is an example of two modules written in separate source files: + +```TypeScript +// -------- main.ts -------- +import { message } from "./log"; +message("hello"); + +// -------- log.ts -------- +export function message(s: string) { + console.log(s); +} +``` + +The import declaration in the 'main' module references the 'log' module and compiling the 'main.ts' file causes the 'log.ts' file to also be compiled as part of the program. + +TypeScript supports multiple patterns of JavaScript code generation for modules: + +* CommonJS. This format is used by server frameworks such as node.js. +* AMD (Asynchronous Module Definition). This format is used by asynchronous module loaders such as RequireJS. +* UMD (Universal Module Definition). A variation of the AMD format that allows modules to also be loaded by CommonJS loaders. +* System. This format is used to represent ECMAScript 2015 semantics with high fidelity in down-level environments. + +The desired module code generation pattern is selected through a compiler option and does not affect the TypeScript source code. Indeed, it is possible to author modules that can be compiled for use both on the server side (e.g. using node.js) and on the client side (using an AMD compliant loader) with no changes to the TypeScript source code. + +### 11.3.1 Module Names + +Modules are identified and referenced using module names. The following definition is aligned with that provided in the [CommonJS Modules](http://www.commonjs.org/specs/modules/1.0/) 1.0 specification. + +* A module name is a string of terms delimited by forward slashes. +* Module names may not have file-name extensions like ".js". +* Module names may be relative or top-level. A module name is relative if the first term is "." or "..". +* Top-level names are resolved off the conceptual module name space root. +* Relative names are resolved relative to the name of the module in which they occur. + +For purposes of resolving module references, TypeScript associates a file path with every module. The file path is simply the path of the module's source file without the file extension. For example, a module contained in the source file 'C:\src\lib\io.ts' has the file path 'C:/src/lib/io' and a module contained in the source file 'C:\src\ui\editor.d.ts' has the file path 'C:/src/ui/editor'. + +A module name in an import declaration is resolved as follows: + +* If the import declaration specifies a relative module name, the name is resolved relative to the directory of the referencing module's file path. The program must contain a module with the resulting file path or otherwise an error occurs. For example, in a module with the file path 'C:/src/ui/main', the module names './editor' and '../lib/io' reference modules with the file paths 'C:/src/ui/editor' and 'C:/src/lib/io'. +* If the import declaration specifies a top-level module name and the program contains an *AmbientModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, then the import declaration references that ambient module. +* If the import declaration specifies a top-level module name and the program contains no *AmbientModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, the name is resolved in a host dependent manner (for example by considering the name relative to a module name space root). If a matching module cannot be found an error occurs. + +### 11.3.2 Import Declarations + +Import declarations are used to import entities from other modules and provide bindings for them in the current module. + +An import declaration of the form + +```TypeScript +import * as m from "mod"; +``` + +imports the module with the given name and creates a local binding for the module itself. The local binding is classified as a value (representing the module instance) and a namespace (representing a container of types and namespaces). + +An import declaration of the form + +```TypeScript +import { x, y, z } from "mod"; +``` + +imports a given module and creates local bindings for a specified list of exported members of the module. The specified names must each reference an entity in the export member set ([11.3.4.4](#11.3.4.4)) of the given module. The local bindings have the same names and classifications as the entities they represent unless `as` clauses are used to that specify different local names: + +```TypeScript +import { x as a, y as b } from "mod"; +``` + +An import declaration of the form + +```TypeScript +import d from "mod"; +``` + +is exactly equivalent to the import declaration + +```TypeScript +import { default as d } from "mod"; +``` + +An import declaration of the form + +```TypeScript +import "mod"; +``` + +imports the given module without creating any local bindings (this is useful only if the imported module has side effects). + +### 11.3.3 Import Require Declarations + +Import require declarations exist for backward compatibility with earlier versions of TypeScript. + +  *ImportRequireDeclaration:* +   `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;` + +An import require declaration introduces a local identifier that references a given module. The string literal specified in an import require declaration is interpreted as a module name (section [11.3.1](#11.3.1)). The local identifier introduced by the declaration becomes an alias for, and is classified exactly like, the entity exported from the referenced module. Specifically, if the referenced module contains no export assignment the identifier is classified as a value and a namespace, and if the referenced module contains an export assignment the identifier is classified exactly like the entity named in the export assignment. + +An import require declaration of the form + +```TypeScript +import m = require("mod"); +``` + +is equivalent to the ECMAScript 2015 import declaration + +```TypeScript +import * as m from "mod"; +``` + +provided the referenced module contains no export assignment. + +### 11.3.4 Export Declarations + +An export declaration declares one or more exported module members. The exported members of a module can be imported in other modules using import declarations ([11.3.2](#11.3.2)). + +#### 11.3.4.1 Export Modifiers + +In the body of a module, a declaration can export the declared entity by including an `export` modifier. + +  *ExportImplementationElement:* +   `export` *VariableStatement* +   `export` *LexicalDeclaration* +   `export` *FunctionDeclaration* +   `export` *GeneratorDeclaration* +   `export` *ClassDeclaration* +   `export` *InterfaceDeclaration* +   `export` *TypeAliasDeclaration* +   `export` *EnumDeclaration* +   `export` *NamespaceDeclaration* +   `export` *AmbientDeclaration* +   `export` *ImportAliasDeclaration* + +  *ExportDeclarationElement:* +   `export` *InterfaceDeclaration* +   `export` *TypeAliasDeclaration* +   `export` *AmbientDeclaration* +   `export` *ImportAliasDeclaration* + +In addition to introducing a name in the local declaration space of the module, an exported declaration introduces the same name with the same classification in the module's export declaration space. For example, the declaration + +```TypeScript +export function point(x: number, y: number) { + return { x, y }; +} +``` + +introduces a local name `point` and an exported name `point` that both reference the function. + +#### 11.3.4.2 Export Default Declarations + +Export default declarations provide short-hand syntax for exporting an entity named `default`. + +  *ExportDefaultImplementationElement:* +   `export` `default` *FunctionDeclaration* +   `export` `default` *GeneratorDeclaration* +   `export` `default` *ClassDeclaration* +   `export` `default` *AssignmentExpression* `;` + +  *ExportDefaultDeclarationElement:* +   `export` `default` *AmbientFunctionDeclaration* +   `export` `default` *AmbientClassDeclaration* +   `export` `default` *IdentifierReference* `;` + +An *ExportDefaultImplementationElement* or *ExportDefaultDeclarationElement* for a function, generator, or class introduces a value named `default`, and in the case of a class, a type named `default`, in the containing module's export declaration space. The declaration may optionally specify a local name for the exported function, generator, or class. For example, the declaration + +```TypeScript +export default function point(x: number, y: number) { + return { x, y }; +} +``` + +introduces a local name `point` and an exported name `default` that both reference the function. The declaration is effectively equivalent to + +```TypeScript +function point(x: number, y: number) { + return { x, y }; +} + +export default point; +``` + +which again is equivalent to + +```TypeScript +function point(x: number, y: number) { + return { x, y }; +} + +export { point as default }; +``` + +An *ExportDefaultImplementationElement* or *ExportDefaultDeclarationElement* for an expression consisting of a single identifier must name an entity declared in the current module or the global namespace. The declaration introduces an entity named `default`, with the same classification as the referenced entity, in the containing module's export declaration space. For example, the declarations + +```TypeScript +interface Point { + x: number; + y: number; +} + +function Point(x: number, y: number): Point { + return { x, y }; +} + +export default Point; +``` + +introduce a local name `Point` and an exported name `default`, both with a value and a type meaning. + +An *ExportDefaultImplementationElement* for any expression but a single identifier introduces a value named `default` in the containing module's export declaration space. For example, the declaration + +```TypeScript +export default "hello"; +``` + +introduces an exported value named `default` of type string. + +#### 11.3.4.3 Export List Declarations + +An export list declaration exports one or more entities from the current module or a specified module. + +  *ExportListDeclaration:* +   `export` `*` *FromClause* `;` +   `export` *ExportClause* *FromClause* `;` +   `export` *ExportClause* `;` + +An *ExportListDeclaration* without a *FromClause* exports entities from the current module. In a declaration of the form + +```TypeScript +export { x }; +``` + +the name `x` must reference an entity declared in the current module or the global namespace, and the declaration introduces an entity with the same name and meaning in the containing module's export declaration space. + +An *ExportListDeclaration* with a *FromClause* re-exports entities from a specified module. In a declaration of the form + +```TypeScript +export { x } from "mod"; +``` + +the name `x` must reference an entity in the export member set of the specified module, and the declaration introduces an entity with the same name and meaning in the containing module's export declaration space. No local bindings are created for `x`. + +The *ExportClause* of an *ExportListDeclaration* can specify multiple entities and may optionally specify different names to be used for the exported entities. For example, the declaration + +```TypeScript +export { x, y as b, z as c }; +``` + +introduces entities named `x`, `b`, and `c` in the containing module's export declaration space with the same meaning as the local entities named `x`, `y`, and `z` respectively. + +An *ExportListDeclaration* that specifies `*` instead of an *ExportClause* is called an ***export star*** declaration. An export star declaration re-exports all members of a specified module. + +```TypeScript +export * from "mod"; +``` + +Explicitly exported members take precedence over members re-exported using export star declarations, as described in the following section. + +#### 11.3.4.4 Export Member Set + +The ***export member set*** of a particular module is determined by starting with an empty set of members *E* and an empty set of processed modules *P*, and then processing the module as described below to form the full set of exported members in *E*. Processing a module *M* consists of these steps: + +* Add *M* to *P*. +* Add to *E* each member in the export declaration space of *M* with a name that isn't already in *E*. +* For each export star declaration in *M*, in order of declaration, process the referenced module if it is not already in *P*. + +A module's ***instance type*** is an object type with a property for each member in the module's export member set that denotes a value. + +If a module contains an export assignment it is an error for the module to also contain export declarations. The two types of exports are mutually exclusive. + +### 11.3.5 Export Assignments + +Export assignments exist for backward compatibility with earlier versions of TypeScript. An export assignment designates a module member as the entity to be exported in place of the module itself. + +  *ExportAssignment:* +   `export` `=` *IdentifierReference* `;` + +A module containing an export assignment can be imported using an import require declaration ([11.3.3](#11.3.3)), and the local alias introduced by the import require declaration then takes on all meanings of the identifier named in the export assignment. + +A module containing an export assignment can also be imported using a regular import declaration ([11.3.2](#11.3.2)) provided the entity referenced in the export assignment is declared as a namespace or as a variable with a type annotation. + +Assume the following example resides in the file 'point.ts': + +```TypeScript +export = Point; + +class Point { + constructor(public x: number, public y: number) { } + static origin = new Point(0, 0); +} +``` + +When 'point.ts' is imported in another module, the import alias references the exported class and can be used both as a type and as a constructor function: + +```TypeScript +import Pt = require("./point"); + +var p1 = new Pt(10, 20); +var p2 = Pt.origin; +``` + +Note that there is no requirement that the import alias use the same name as the exported entity. + +### 11.3.6 CommonJS Modules + +The [CommonJS Modules](http://www.commonjs.org/specs/modules/1.0/) definition specifies a methodology for writing JavaScript modules with implied privacy, the ability to import other modules, and the ability to explicitly export members. A CommonJS compliant system provides a 'require' function that can be used to synchronously load other modules to obtain their singleton module instance, as well as an 'exports' variable to which a module can add properties to define its external API. + +The 'main' and 'log' example from section [11.3](#11.3) above generates the following JavaScript code when compiled for the CommonJS Modules pattern: + +File main.js: + +```TypeScript +var log_1 = require("./log"); +log_1.message("hello"); +``` + +File log.js: + +```TypeScript +function message(s) { + console.log(s); +} +exports.message = message; +``` + +A module import declaration is represented in the generated JavaScript as a variable initialized by a call to the 'require' function provided by the module system host. A variable declaration and 'require' call is emitted for a particular imported module only if the imported module, or a local alias (section [10.3](#10.3)) that references the imported module, is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *NamespaceName* or *TypeQueryExpression*, nothing is emitted. + +An example: + +File geometry.ts: + +```TypeScript +export interface Point { x: number; y: number }; + +export function point(x: number, y: number): Point { + return { x, y }; +} +``` + +File game.ts: + +```TypeScript +import * as g from "./geometry"; +let p = g.point(10, 20); +``` + +The 'game' module references the imported 'geometry' module in an expression (through its alias 'g') and a 'require' call is therefore included in the emitted JavaScript: + +```TypeScript +var g = require("./geometry"); +var p = g.point(10, 20); +``` + +Had the 'game' module instead been written to only reference 'geometry' in a type position + +```TypeScript +import * as g from "./geometry"; +let p: g.Point = { x: 10, y: 20 }; +``` + +the emitted JavaScript would have no dependency on the 'geometry' module and would simply be + +```TypeScript +var p = { x: 10, y: 20 }; +``` + +### 11.3.7 AMD Modules + +The [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) (AMD) specification extends the CommonJS Modules specification with a pattern for authoring asynchronously loadable modules with associated dependencies. Using the AMD pattern, modules are emitted as calls to a global 'define' function taking an array of dependencies, specified as module names, and a callback function containing the module body. The global 'define' function is provided by including an AMD compliant loader in the application. The loader arranges to asynchronously load the module's dependencies and, upon completion, calls the callback function passing resolved module instances as arguments in the order they were listed in the dependency array. + +The "main" and "log" example from above generates the following JavaScript code when compiled for the AMD pattern. + +File main.js: + +```TypeScript +define(["require", "exports", "./log"], function(require, exports, log_1) { + log_1.message("hello"); +} +``` + +File log.js: + +```TypeScript +define(["require", "exports"], function(require, exports) { + function message(s) { + console.log(s); + } + exports.message = message; +} +``` + +The special 'require' and 'exports' dependencies are always present. Additional entries are added to the dependencies array and the parameter list as required to represent imported modules. Similar to the code generation for CommonJS Modules, a dependency entry is generated for a particular imported module only if the imported module is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *NamespaceName*, no dependency is generated for that module. + +
+ +#
12 Ambients + +Ambient declarations are used to provide static typing over existing JavaScript code. Ambient declarations differ from regular declarations in that no JavaScript code is emitted for them. Instead of introducing new variables, functions, classes, enums, or namespaces, ambient declarations provide type information for entities that exist "ambiently" and are included in a program by external means, for example by referencing a JavaScript library in a <script/> tag. + +## 12.1 Ambient Declarations + +Ambient declarations are written using the `declare` keyword and can declare variables, functions, classes, enums, namespaces, or modules. + +  *AmbientDeclaration:* +   `declare` *AmbientVariableDeclaration* +   `declare` *AmbientFunctionDeclaration* +   `declare` *AmbientClassDeclaration* +   `declare` *AmbientEnumDeclaration* +   `declare` *AmbientNamespaceDeclaration* + +### 12.1.1 Ambient Variable Declarations + +An ambient variable declaration introduces a variable in the containing declaration space. + +  *AmbientVariableDeclaration:* +   `var` *AmbientBindingList* `;` +   `let` *AmbientBindingList* `;` +   `const` *AmbientBindingList* `;` + +  *AmbientBindingList:* +   *AmbientBinding* +   *AmbientBindingList* `,` *AmbientBinding* + +  *AmbientBinding:* +   *BindingIdentifier* *TypeAnnotationopt* + +An ambient variable declaration may optionally include a type annotation. If no type annotation is present, the variable is assumed to have type Any. + +An ambient variable declaration does not permit an initializer expression to be present. + +### 12.1.2 Ambient Function Declarations + +An ambient function declaration introduces a function in the containing declaration space. + +  *AmbientFunctionDeclaration:* +   `function` *BindingIdentifier* *CallSignature* `;` + +Ambient functions may be overloaded by specifying multiple ambient function declarations with the same name, but it is an error to declare multiple overloads that are considered identical (section [3.11.2](#3.11.2)) or differ only in their return types. + +Ambient function declarations cannot specify a function bodies and do not permit default parameter values. + +### 12.1.3 Ambient Class Declarations + +An ambient class declaration declares a class type and a constructor function in the containing declaration space. + +  *AmbientClassDeclaration:* +   `class` *BindingIdentifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}` + +  *AmbientClassBody:* +   *AmbientClassBodyElementsopt* + +  *AmbientClassBodyElements:* +   *AmbientClassBodyElement* +   *AmbientClassBodyElements* *AmbientClassBodyElement* + +  *AmbientClassBodyElement:* +   *AmbientConstructorDeclaration* +   *AmbientPropertyMemberDeclaration* +   *IndexSignature* + +  *AmbientConstructorDeclaration:* +   `constructor` `(` *ParameterListopt* `)` `;` + +  *AmbientPropertyMemberDeclaration:* +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* `;` +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;` + +### 12.1.4 Ambient Enum Declarations + +An ambient enum is grammatically equivalent to a non-ambient enum declaration. + +  *AmbientEnumDeclaration:* +   *EnumDeclaration* + +Ambient enum declarations differ from non-ambient enum declarations in two ways: + +* In ambient enum declarations, all values specified in enum member declarations must be classified as constant enum expressions. +* 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 assigned). + +Ambient enum declarations are otherwise processed in the same manner as non-ambient enum declarations. + +### 12.1.5 Ambient Namespace Declarations + +An ambient namespace declaration declares a namespace. + +  *AmbientNamespaceDeclaration:* +   `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}` + +  *AmbientNamespaceBody:* +   *AmbientNamespaceElementsopt* + +  *AmbientNamespaceElements:* +   *AmbientNamespaceElement* +   *AmbientNamespaceElements* *AmbientNamespaceElement* + +  *AmbientNamespaceElement:* +   `export`*opt* *AmbientVariableDeclaration* +   `export`*opt* *AmbientLexicalDeclaration* +   `export`*opt* *AmbientFunctionDeclaration* +   `export`*opt* *AmbientClassDeclaration* +   `export`*opt* *InterfaceDeclaration* +   `export`*opt* *AmbientEnumDeclaration* +   `export`*opt* *AmbientNamespaceDeclaration* +   `export`*opt* *ImportAliasDeclaration* + +Except for *ImportAliasDeclarations*, *AmbientNamespaceElements* always declare exported entities regardless of whether they include the optional `export` modifier. + +## 12.2 Ambient Module Declarations + +An *AmbientModuleDeclaration* declares a module. This type of declaration is permitted only at the top level in a source file that contributes to the global namespace (section [11.1](#11.1)). The *StringLiteral* must specify a top-level module name. Relative module names are not permitted. + +  *AmbientModuleDeclaration:* +   `declare` `module` *StringLiteral* `{`  *DeclarationModule* `}` + +An *ImportRequireDeclaration* in an *AmbientModuleDeclaration* may reference other modules only through top-level module names. Relative module names are not permitted. + +If an ambient module declaration includes an export assignment, it is an error for any of the declarations within the module to specify an `export` modifier. If an ambient module declaration contains no export assignment, entities declared in the module are exported regardless of whether their declarations include the optional `export` modifier. + +Ambient modules are "open-ended" and ambient module declarations with the same string literal name contribute to a single module. For example, the following two declarations of a module 'io' might be located in separate source files. + +```TypeScript +declare module "io" { + export function readFile(filename: string): string; +} + +declare module "io" { + export function writeFile(filename: string, data: string): void; +} +``` + +This has the same effect as a single combined declaration: + +```TypeScript +declare module "io" { + export function readFile(filename: string): string; + export function writeFile(filename: string, data: string): void; +} +``` + +
+ +#
A Grammar + +This appendix contains a summary of the grammar found in the main document. As described in section [2.1](#2.1), the TypeScript grammar is a superset of the grammar defined in the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar. + +## A.1 Types + +  *TypeParameters:* +   `<` *TypeParameterList* `>` + +  *TypeParameterList:* +   *TypeParameter* +   *TypeParameterList* `,` *TypeParameter* + +  *TypeParameter:* +   *BindingIdentifier* *Constraintopt* + +  *Constraint:* +   `extends` *Type* + +  *TypeArguments:* +   `<` *TypeArgumentList* `>` + +  *TypeArgumentList:* +   *TypeArgument* +   *TypeArgumentList* `,` *TypeArgument* + +  *TypeArgument:* +   *Type* + +  *Type:* +   *UnionOrIntersectionOrPrimaryType* +   *FunctionType* +   *ConstructorType* + +  *UnionOrIntersectionOrPrimaryType:* +   *UnionType* +   *IntersectionOrPrimaryType* + +  *IntersectionOrPrimaryType:* +   *IntersectionType* +   *PrimaryType* + +  *PrimaryType:* +   *ParenthesizedType* +   *PredefinedType* +   *TypeReference* +   *ObjectType* +   *ArrayType* +   *TupleType* +   *TypeQuery* +   *ThisType* + +  *ParenthesizedType:* +   `(` *Type* `)` + +  *PredefinedType:* +   `any` +   `number` +   `boolean` +   `string` +   `symbol` +   `void` + +  *TypeReference:* +   *TypeName* *[no LineTerminator here]* *TypeArgumentsopt* + +  *TypeName:* +   *IdentifierReference* +   *NamespaceName* `.` *IdentifierReference* + +  *NamespaceName:* +   *IdentifierReference* +   *NamespaceName* `.` *IdentifierReference* + +  *ObjectType:* +   `{` *TypeBodyopt* `}` + +  *TypeBody:* +   *TypeMemberList* `;`*opt* +   *TypeMemberList* `,`*opt* + +  *TypeMemberList:* +   *TypeMember* +   *TypeMemberList* `;` *TypeMember* +   *TypeMemberList* `,` *TypeMember* + +  *TypeMember:* +   *PropertySignature* +   *CallSignature* +   *ConstructSignature* +   *IndexSignature* +   *MethodSignature* + +  *ArrayType:* +   *PrimaryType* *[no LineTerminator here]* `[` `]` + +  *TupleType:* +   `[` *TupleElementTypes* `]` + +  *TupleElementTypes:* +   *TupleElementType* +   *TupleElementTypes* `,` *TupleElementType* + +  *TupleElementType:* +   *Type* + +  *UnionType:* +   *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType* + +  *IntersectionType:* +   *IntersectionOrPrimaryType* `&` *PrimaryType* + +  *FunctionType:* +   *TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type* + +  *ConstructorType:* +   `new` *TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type* + +  *TypeQuery:* +   `typeof` *TypeQueryExpression* + +  *TypeQueryExpression:* +   *IdentifierReference* +   *TypeQueryExpression* `.` *IdentifierName* + +  *ThisType:* +   `this` + +  *PropertySignature:* +   *PropertyName* `?`*opt* *TypeAnnotationopt* + +  *PropertyName:* +   *IdentifierName* +   *StringLiteral* +   *NumericLiteral* + +  *TypeAnnotation:* +   `:` *Type* + +  *CallSignature:* +   *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt* + +  *ParameterList:* +   *RequiredParameterList* +   *OptionalParameterList* +   *RestParameter* +   *RequiredParameterList* `,` *OptionalParameterList* +   *RequiredParameterList* `,` *RestParameter* +   *OptionalParameterList* `,` *RestParameter* +   *RequiredParameterList* `,` *OptionalParameterList* `,` *RestParameter* + +  *RequiredParameterList:* +   *RequiredParameter* +   *RequiredParameterList* `,` *RequiredParameter* + +  *RequiredParameter:* +   *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* +   *BindingIdentifier* `:` *StringLiteral* + +  *AccessibilityModifier:* +   `public` +   `private` +   `protected` + +  *BindingIdentifierOrPattern:* +   *BindingIdentifier* +   *BindingPattern* + +  *OptionalParameterList:* +   *OptionalParameter* +   *OptionalParameterList* `,` *OptionalParameter* + +  *OptionalParameter:* +   *AccessibilityModifieropt* *BindingIdentifierOrPattern* `?` *TypeAnnotationopt* +   *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* *Initializer* +   *BindingIdentifier* `?` `:` *StringLiteral* + +  *RestParameter:* +   `...` *BindingIdentifier* *TypeAnnotationopt* + +  *ConstructSignature:* +   `new` *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt* + +  *IndexSignature:* +   `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation* +   `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation* + +  *MethodSignature:* +   *PropertyName* `?`*opt* *CallSignature* + +  *TypeAliasDeclaration:* +   `type` *BindingIdentifier* *TypeParametersopt* `=` *Type* `;` + +## A.2 Expressions + +  *PropertyDefinition:* *( Modified )* +   *IdentifierReference* +   *CoverInitializedName* +   *PropertyName* `:` *AssignmentExpression* +   *PropertyName* *CallSignature* `{` *FunctionBody* `}` +   *GetAccessor* +   *SetAccessor* + +  *GetAccessor:* +   `get` *PropertyName* `(` `)` *TypeAnnotationopt* `{` *FunctionBody* `}` + +  *SetAccessor:* +   `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotationopt* `)` `{` *FunctionBody* `}` + +  *FunctionExpression:* *( Modified )* +   `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}` + +  *ArrowFormalParameters:* *( Modified )* +   *CallSignature* + +  *Arguments:* *( Modified )* +   *TypeArgumentsopt* `(` *ArgumentListopt* `)` + +  *UnaryExpression:* *( Modified )* +   … +   `<` *Type* `>` *UnaryExpression* + +## A.3 Statements + +  *Declaration:* *( Modified )* +   … +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *EnumDeclaration* + +  *VariableDeclaration:* *( Modified )* +   *SimpleVariableDeclaration* +   *DestructuringVariableDeclaration* + +  *SimpleVariableDeclaration:* +   *BindingIdentifier* *TypeAnnotationopt* *Initializeropt* + +  *DestructuringVariableDeclaration:* +   *BindingPattern* *TypeAnnotationopt* *Initializer* + +  *LexicalBinding:* *( Modified )* +   *SimpleLexicalBinding* +   *DestructuringLexicalBinding* + +  *SimpleLexicalBinding:* +   *BindingIdentifier* *TypeAnnotationopt* *Initializeropt* + +  *DestructuringLexicalBinding:* +   *BindingPattern* *TypeAnnotationopt* *Initializeropt* + +## A.4 Functions + +  *FunctionDeclaration:* *( Modified )* +   `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}` +   `function` *BindingIdentifieropt* *CallSignature* `;` + +## A.5 Interfaces + +  *InterfaceDeclaration:* +   `interface` *BindingIdentifier* *TypeParametersopt* *InterfaceExtendsClauseopt* *ObjectType* + +  *InterfaceExtendsClause:* +   `extends` *ClassOrInterfaceTypeList* + +  *ClassOrInterfaceTypeList:* +   *ClassOrInterfaceType* +   *ClassOrInterfaceTypeList* `,` *ClassOrInterfaceType* + +  *ClassOrInterfaceType:* +   *TypeReference* + +## A.6 Classes + +  *ClassDeclaration:* *( Modified )* +   `class` *BindingIdentifieropt* *TypeParametersopt* *ClassHeritage* `{` *ClassBody* `}` + +  *ClassHeritage:* *( Modified )* +   *ClassExtendsClauseopt* *ImplementsClauseopt* + +  *ClassExtendsClause:* +   `extends`  *ClassType* + +  *ClassType:* +   *TypeReference* + +  *ImplementsClause:* +   `implements` *ClassOrInterfaceTypeList* + +  *ClassElement:* *( Modified )* +   *ConstructorDeclaration* +   *PropertyMemberDeclaration* +   *IndexMemberDeclaration* + +  *ConstructorDeclaration:* +   *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `{` *FunctionBody* `}` +   *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `;` + +  *PropertyMemberDeclaration:* +   *MemberVariableDeclaration* +   *MemberFunctionDeclaration* +   *MemberAccessorDeclaration* + +  *MemberVariableDeclaration:* +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* *Initializeropt* `;` + +  *MemberFunctionDeclaration:* +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `{` *FunctionBody* `}` +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;` + +  *MemberAccessorDeclaration:* +   *AccessibilityModifieropt* `static`*opt* *GetAccessor* +   *AccessibilityModifieropt* `static`*opt* *SetAccessor* + +  *IndexMemberDeclaration:* +   *IndexSignature* `;` + +## A.7 Enums + +  *EnumDeclaration:* +   `const`*opt* `enum` *BindingIdentifier* `{` *EnumBodyopt* `}` + +  *EnumBody:* +   *EnumMemberList* `,`*opt* + +  *EnumMemberList:* +   *EnumMember* +   *EnumMemberList* `,` *EnumMember* + +  *EnumMember:* +   *PropertyName* +   *PropertyName* = *EnumValue* + +  *EnumValue:* +   *AssignmentExpression* + +## A.8 Namespaces + +  *NamespaceDeclaration:* +   `namespace` *IdentifierPath* `{` *NamespaceBody* `}` + +  *IdentifierPath:* +   *BindingIdentifier* +   *IdentifierPath* `.` *BindingIdentifier* + +  *NamespaceBody:* +   *NamespaceElementsopt* + +  *NamespaceElements:* +   *NamespaceElement* +   *NamespaceElements* *NamespaceElement* + +  *NamespaceElement:* +   *Statement* +   *LexicalDeclaration* +   *FunctionDeclaration* +   *GeneratorDeclaration* +   *ClassDeclaration* +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *EnumDeclaration* +   *NamespaceDeclaration +   AmbientDeclaration +   ImportAliasDeclaration +   ExportNamespaceElement* + +  *ExportNamespaceElement:* +   `export` *VariableStatement* +   `export` *LexicalDeclaration* +   `export` *FunctionDeclaration* +   `export` *GeneratorDeclaration* +   `export` *ClassDeclaration* +   `export` *InterfaceDeclaration* +   `export` *TypeAliasDeclaration* +   `export` *EnumDeclaration* +   `export` *NamespaceDeclaration* +   `export` *AmbientDeclaration* +   `export` *ImportAliasDeclaration* + +  *ImportAliasDeclaration:* +   `import` *BindingIdentifier* `=` *EntityName* `;` + +  *EntityName:* +   *NamespaceName* +   *NamespaceName* `.` *IdentifierReference* + +## A.9 Scripts and Modules + +  *SourceFile:* +   *ImplementationSourceFile* +   *DeclarationSourceFile* + +  *ImplementationSourceFile:* +   *ImplementationScript* +   *ImplementationModule* + +  *DeclarationSourceFile:* +   *DeclarationScript* +   *DeclarationModule* + +  *ImplementationScript:* +   *ImplementationScriptElementsopt* + +  *ImplementationScriptElements:* +   *ImplementationScriptElement* +   *ImplementationScriptElements* *ImplementationScriptElement* + +  *ImplementationScriptElement:* +   *ImplementationElement* +   *AmbientModuleDeclaration* + +  *ImplementationElement:* +   *Statement* +   *LexicalDeclaration* +   *FunctionDeclaration* +   *GeneratorDeclaration* +   *ClassDeclaration* +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *EnumDeclaration* +   *NamespaceDeclaration* +   *AmbientDeclaration* +   *ImportAliasDeclaration* + +  *DeclarationScript:* +   *DeclarationScriptElementsopt* + +  *DeclarationScriptElements:* +   *DeclarationScriptElement* +   *DeclarationScriptElements* *DeclarationScriptElement* + +  *DeclarationScriptElement:* +   *DeclarationElement* +   *AmbientModuleDeclaration* + +  *DeclarationElement:* +   *InterfaceDeclaration* +   *TypeAliasDeclaration* +   *NamespaceDeclaration* +   *AmbientDeclaration* +   *ImportAliasDeclaration* + +  *ImplementationModule:* +   *ImplementationModuleElementsopt* + +  *ImplementationModuleElements:* +   *ImplementationModuleElement* +   *ImplementationModuleElements* *ImplementationModuleElement* + +  *ImplementationModuleElement:* +   *ImplementationElement* +   *ImportDeclaration* +   *ImportAliasDeclaration* +   *ImportRequireDeclaration* +   *ExportImplementationElement* +   *ExportDefaultImplementationElement* +   *ExportListDeclaration* +   *ExportAssignment* + +  *DeclarationModule:* +   *DeclarationModuleElementsopt* + +  *DeclarationModuleElements:* +   *DeclarationModuleElement* +   *DeclarationModuleElements* *DeclarationModuleElement* + +  *DeclarationModuleElement:* +   *DeclarationElement* +   *ImportDeclaration* +   *ImportAliasDeclaration* +   *ExportDeclarationElement* +   *ExportDefaultDeclarationElement* +   *ExportListDeclaration* +   *ExportAssignment* + +  *ImportRequireDeclaration:* +   `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;` + +  *ExportImplementationElement:* +   `export` *VariableStatement* +   `export` *LexicalDeclaration* +   `export` *FunctionDeclaration* +   `export` *GeneratorDeclaration* +   `export` *ClassDeclaration* +   `export` *InterfaceDeclaration* +   `export` *TypeAliasDeclaration* +   `export` *EnumDeclaration* +   `export` *NamespaceDeclaration* +   `export` *AmbientDeclaration* +   `export` *ImportAliasDeclaration* + +  *ExportDeclarationElement:* +   `export` *InterfaceDeclaration* +   `export` *TypeAliasDeclaration* +   `export` *AmbientDeclaration* +   `export` *ImportAliasDeclaration* + +  *ExportDefaultImplementationElement:* +   `export` `default` *FunctionDeclaration* +   `export` `default` *GeneratorDeclaration* +   `export` `default` *ClassDeclaration* +   `export` `default` *AssignmentExpression* `;` + +  *ExportDefaultDeclarationElement:* +   `export` `default` *AmbientFunctionDeclaration* +   `export` `default` *AmbientClassDeclaration* +   `export` `default` *IdentifierReference* `;` + +  *ExportListDeclaration:* +   `export` `*` *FromClause* `;` +   `export` *ExportClause* *FromClause* `;` +   `export` *ExportClause* `;` + +  *ExportAssignment:* +   `export` `=` *IdentifierReference* `;` + +## A.10 Ambients + +  *AmbientDeclaration:* +   `declare` *AmbientVariableDeclaration* +   `declare` *AmbientFunctionDeclaration* +   `declare` *AmbientClassDeclaration* +   `declare` *AmbientEnumDeclaration* +   `declare` *AmbientNamespaceDeclaration* + +  *AmbientVariableDeclaration:* +   `var` *AmbientBindingList* `;` +   `let` *AmbientBindingList* `;` +   `const` *AmbientBindingList* `;` + +  *AmbientBindingList:* +   *AmbientBinding* +   *AmbientBindingList* `,` *AmbientBinding* + +  *AmbientBinding:* +   *BindingIdentifier* *TypeAnnotationopt* + +  *AmbientFunctionDeclaration:* +   `function` *BindingIdentifier* *CallSignature* `;` + +  *AmbientClassDeclaration:* +   `class` *BindingIdentifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}` + +  *AmbientClassBody:* +   *AmbientClassBodyElementsopt* + +  *AmbientClassBodyElements:* +   *AmbientClassBodyElement* +   *AmbientClassBodyElements* *AmbientClassBodyElement* + +  *AmbientClassBodyElement:* +   *AmbientConstructorDeclaration* +   *AmbientPropertyMemberDeclaration* +   *IndexSignature* + +  *AmbientConstructorDeclaration:* +   `constructor` `(` *ParameterListopt* `)` `;` + +  *AmbientPropertyMemberDeclaration:* +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* `;` +   *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;` + +  *AmbientEnumDeclaration:* +   *EnumDeclaration* + +  *AmbientNamespaceDeclaration:* +   `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}` + +  *AmbientNamespaceBody:* +   *AmbientNamespaceElementsopt* + +  *AmbientNamespaceElements:* +   *AmbientNamespaceElement* +   *AmbientNamespaceElements* *AmbientNamespaceElement* + +  *AmbientNamespaceElement:* +   `export`*opt* *AmbientVariableDeclaration* +   `export`*opt* *AmbientLexicalDeclaration* +   `export`*opt* *AmbientFunctionDeclaration* +   `export`*opt* *AmbientClassDeclaration* +   `export`*opt* *InterfaceDeclaration* +   `export`*opt* *AmbientEnumDeclaration* +   `export`*opt* *AmbientNamespaceDeclaration* +   `export`*opt* *ImportAliasDeclaration* + +  *AmbientModuleDeclaration:* +   `declare` `module` *StringLiteral* `{`  *DeclarationModule* `}` + From adf30dd694b1572e1ab27651dcbdbb44ab382a17 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 28 Mar 2018 10:41:24 -0700 Subject: [PATCH 33/75] isMethodLike recognises prototype-assignment methods (#22935) * isMethodLike recognises prototype-assignment methods * Require js prototype methods to be in JS files --- src/compiler/checker.ts | 4 ++- .../typeFromPropertyAssignment23.symbols | 24 +++++++++++++++++ .../typeFromPropertyAssignment23.types | 26 +++++++++++++++++++ .../salsa/typeFromPropertyAssignment23.ts | 17 ++++++++++++ 4 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/typeFromPropertyAssignment23.symbols create mode 100644 tests/baselines/reference/typeFromPropertyAssignment23.types create mode 100644 tests/cases/conformance/salsa/typeFromPropertyAssignment23.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 89c799db46d..a2c9faacfcb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16103,7 +16103,9 @@ namespace ts { } function isMethodLike(symbol: Symbol) { - return !!(symbol.flags & SymbolFlags.Method || getCheckFlags(symbol) & CheckFlags.SyntheticMethod); + return !!(symbol.flags & SymbolFlags.Method || + getCheckFlags(symbol) & CheckFlags.SyntheticMethod || + isInJavaScriptFile(symbol.valueDeclaration) && isFunctionLikeDeclaration(getAssignedJavascriptInitializer(symbol.valueDeclaration))); } /** diff --git a/tests/baselines/reference/typeFromPropertyAssignment23.symbols b/tests/baselines/reference/typeFromPropertyAssignment23.symbols new file mode 100644 index 00000000000..879685fc357 --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment23.symbols @@ -0,0 +1,24 @@ +=== tests/cases/conformance/salsa/a.js === +class Ex { +>Ex : Symbol(Ex, Decl(a.js, 0, 0)) + + foo() { +>foo : Symbol(Ex.foo, Decl(a.js, 0, 10)) + } +} + +class MyClass extends Ex { +>MyClass : Symbol(MyClass, Decl(a.js, 3, 1)) +>Ex : Symbol(Ex, Decl(a.js, 0, 0)) + +} + +// this override should be fine (even if it's a little odd) +MyClass.prototype.foo = function() { +>MyClass.prototype.foo : Symbol(MyClass.foo, Decl(a.js, 7, 1)) +>MyClass.prototype : Symbol(MyClass.foo, Decl(a.js, 7, 1)) +>MyClass : Symbol(MyClass, Decl(a.js, 3, 1)) +>prototype : Symbol(MyClass.prototype) +>foo : Symbol(MyClass.foo, Decl(a.js, 7, 1)) +} + diff --git a/tests/baselines/reference/typeFromPropertyAssignment23.types b/tests/baselines/reference/typeFromPropertyAssignment23.types new file mode 100644 index 00000000000..093d681032b --- /dev/null +++ b/tests/baselines/reference/typeFromPropertyAssignment23.types @@ -0,0 +1,26 @@ +=== tests/cases/conformance/salsa/a.js === +class Ex { +>Ex : Ex + + foo() { +>foo : () => void + } +} + +class MyClass extends Ex { +>MyClass : MyClass +>Ex : Ex + +} + +// this override should be fine (even if it's a little odd) +MyClass.prototype.foo = function() { +>MyClass.prototype.foo = function() {} : () => void +>MyClass.prototype.foo : () => void +>MyClass.prototype : MyClass +>MyClass : typeof MyClass +>prototype : MyClass +>foo : () => void +>function() {} : () => void +} + diff --git a/tests/cases/conformance/salsa/typeFromPropertyAssignment23.ts b/tests/cases/conformance/salsa/typeFromPropertyAssignment23.ts new file mode 100644 index 00000000000..c96d3b4ebdc --- /dev/null +++ b/tests/cases/conformance/salsa/typeFromPropertyAssignment23.ts @@ -0,0 +1,17 @@ +// @noEmit: true +// @strict: true +// @checkJs: true +// @allowJs: true +// @Filename: a.js +class Ex { + foo() { + } +} + +class MyClass extends Ex { + +} + +// this override should be fine (even if it's a little odd) +MyClass.prototype.foo = function() { +} From cb9f436b54d2899655db9f8fff89d692ebd0a9d0 Mon Sep 17 00:00:00 2001 From: Wenlu Wang Date: Thu, 29 Mar 2018 01:59:09 +0800 Subject: [PATCH 34/75] fix accessor parse with line terminator (#22893) --- src/compiler/parser.ts | 38 +++++++++---------- .../reference/accessorWithLineTerminator.js | 21 ++++++++++ .../accessorWithLineTerminator.symbols | 13 +++++++ .../accessorWithLineTerminator.types | 14 +++++++ .../compiler/accessorWithLineTerminator.ts | 9 +++++ 5 files changed, 76 insertions(+), 19 deletions(-) create mode 100644 tests/baselines/reference/accessorWithLineTerminator.js create mode 100644 tests/baselines/reference/accessorWithLineTerminator.symbols create mode 100644 tests/baselines/reference/accessorWithLineTerminator.types create mode 100644 tests/cases/compiler/accessorWithLineTerminator.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index c3709fa4e0c..e72ce3ad5ac 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1344,26 +1344,26 @@ namespace ts { } function nextTokenCanFollowModifier() { - if (token() === SyntaxKind.ConstKeyword) { - // 'const' is only a modifier if followed by 'enum'. - return nextToken() === SyntaxKind.EnumKeyword; + switch (token()) { + case SyntaxKind.ConstKeyword: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === SyntaxKind.EnumKeyword; + case SyntaxKind.ExportKeyword: + nextToken(); + if (token() === SyntaxKind.DefaultKeyword) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== SyntaxKind.AsteriskToken && token() !== SyntaxKind.AsKeyword && token() !== SyntaxKind.OpenBraceToken && canFollowModifier(); + case SyntaxKind.DefaultKeyword: + return nextTokenCanFollowDefaultKeyword(); + case SyntaxKind.StaticKeyword: + case SyntaxKind.GetKeyword: + case SyntaxKind.SetKeyword: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === SyntaxKind.ExportKeyword) { - nextToken(); - if (token() === SyntaxKind.DefaultKeyword) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== SyntaxKind.AsteriskToken && token() !== SyntaxKind.AsKeyword && token() !== SyntaxKind.OpenBraceToken && canFollowModifier(); - } - if (token() === SyntaxKind.DefaultKeyword) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === SyntaxKind.StaticKeyword) { - nextToken(); - return canFollowModifier(); - } - - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier(): boolean { diff --git a/tests/baselines/reference/accessorWithLineTerminator.js b/tests/baselines/reference/accessorWithLineTerminator.js new file mode 100644 index 00000000000..51310c101a8 --- /dev/null +++ b/tests/baselines/reference/accessorWithLineTerminator.js @@ -0,0 +1,21 @@ +//// [accessorWithLineTerminator.ts] +class C { + get + x() { return 1 } + + set + x(v) { } +} + +//// [accessorWithLineTerminator.js] +var C = /** @class */ (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { return 1; }, + set: function (v) { }, + enumerable: true, + configurable: true + }); + return C; +}()); diff --git a/tests/baselines/reference/accessorWithLineTerminator.symbols b/tests/baselines/reference/accessorWithLineTerminator.symbols new file mode 100644 index 00000000000..c73192977f6 --- /dev/null +++ b/tests/baselines/reference/accessorWithLineTerminator.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/accessorWithLineTerminator.ts === +class C { +>C : Symbol(C, Decl(accessorWithLineTerminator.ts, 0, 0)) + + get + x() { return 1 } +>x : Symbol(C.x, Decl(accessorWithLineTerminator.ts, 0, 9), Decl(accessorWithLineTerminator.ts, 2, 20)) + + set + x(v) { } +>x : Symbol(C.x, Decl(accessorWithLineTerminator.ts, 0, 9), Decl(accessorWithLineTerminator.ts, 2, 20)) +>v : Symbol(v, Decl(accessorWithLineTerminator.ts, 5, 6)) +} diff --git a/tests/baselines/reference/accessorWithLineTerminator.types b/tests/baselines/reference/accessorWithLineTerminator.types new file mode 100644 index 00000000000..327ff8e4234 --- /dev/null +++ b/tests/baselines/reference/accessorWithLineTerminator.types @@ -0,0 +1,14 @@ +=== tests/cases/compiler/accessorWithLineTerminator.ts === +class C { +>C : C + + get + x() { return 1 } +>x : number +>1 : 1 + + set + x(v) { } +>x : number +>v : number +} diff --git a/tests/cases/compiler/accessorWithLineTerminator.ts b/tests/cases/compiler/accessorWithLineTerminator.ts new file mode 100644 index 00000000000..184a2e9660a --- /dev/null +++ b/tests/cases/compiler/accessorWithLineTerminator.ts @@ -0,0 +1,9 @@ +// @target: es5 + +class C { + get + x() { return 1 } + + set + x(v) { } +} \ No newline at end of file From dc3eb3c27eb0723cd8d8ea93c200dab3445719cc Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 28 Mar 2018 13:16:11 -0700 Subject: [PATCH 35/75] Erase 'infer T' locations in conditional type constraints --- src/compiler/checker.ts | 14 ++++++++++++-- src/compiler/types.ts | 4 ++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 89c799db46d..4c5f9b93967 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6233,7 +6233,7 @@ namespace ts { } function getDefaultConstraintOfConditionalType(type: ConditionalType) { - return getUnionType([getTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); + return getUnionType([getInferredTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); } function getConstraintOfDistributiveConditionalType(type: ConditionalType): Type { @@ -8343,16 +8343,19 @@ namespace ts { // If this is a distributive conditional type and the check type is generic we need to defer // resolution of the conditional type such that a later instantiation will properly distribute // over union types. - if (!root.isDistributive || !maybeTypeOfKind(checkType, TypeFlags.Instantiable)) { + const isDeferred = root.isDistributive && maybeTypeOfKind(checkType, TypeFlags.Instantiable); let combinedMapper: TypeMapper; if (root.inferTypeParameters) { const context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, InferenceFlags.None); + if (!isDeferred) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. inferTypes(context.inferences, checkType, extendsType, InferencePriority.NoConstraints | InferencePriority.AlwaysStrict); + } combinedMapper = combineTypeMappers(mapper, context); } + if (!isDeferred) { // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & TypeFlags.Any) { return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); @@ -8381,6 +8384,7 @@ namespace ts { result.checkType = erasedCheckType; result.extendsType = extendsType; result.mapper = mapper; + result.combinedMapper = combinedMapper; result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); return result; @@ -8394,6 +8398,12 @@ namespace ts { return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); } + function getInferredTrueTypeFromConditionalType(type: ConditionalType) { + return type.combinedMapper ? + type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper)) : + getTrueTypeFromConditionalType(type); + } + function getInferTypeParameters(node: ConditionalTypeNode): TypeParameter[] { let result: TypeParameter[]; if (node.locals) { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 51b1d984bf6..7775543dee6 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3878,7 +3878,11 @@ namespace ts { resolvedTrueType?: Type; resolvedFalseType?: Type; /* @internal */ + resolvedInferredTrueType?: Type; + /* @internal */ mapper?: TypeMapper; + /* @internal */ + combinedMapper?: TypeMapper; } // Type parameter substitution (TypeFlags.Substitution) From 0e446fe8c2b1a85c38e349320a93a52707c2b3dd Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 28 Mar 2018 13:16:29 -0700 Subject: [PATCH 36/75] Add regression test --- .../cases/conformance/types/conditional/conditionalTypes1.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/cases/conformance/types/conditional/conditionalTypes1.ts b/tests/cases/conformance/types/conditional/conditionalTypes1.ts index e138798cb3c..4005e896ce1 100644 --- a/tests/cases/conformance/types/conditional/conditionalTypes1.ts +++ b/tests/cases/conformance/types/conditional/conditionalTypes1.ts @@ -215,6 +215,10 @@ type T50 = IsNever; // true type T51 = IsNever; // false type T52 = IsNever; // false +function f22(x: T extends (infer U)[] ? U[] : never) { + let e = x[0]; // {} +} + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; From dc42febf1e6f19f8ee1097c1c1d97d5b47fbd23f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 28 Mar 2018 13:16:36 -0700 Subject: [PATCH 37/75] Accept new baselines --- .../reference/conditionalTypes1.errors.txt | 8 +- .../baselines/reference/conditionalTypes1.js | 8 + .../reference/conditionalTypes1.symbols | 597 +++++++++--------- .../reference/conditionalTypes1.types | 15 + 4 files changed, 334 insertions(+), 294 deletions(-) diff --git a/tests/baselines/reference/conditionalTypes1.errors.txt b/tests/baselines/reference/conditionalTypes1.errors.txt index d96030fbeca..b96ecf6254c 100644 --- a/tests/baselines/reference/conditionalTypes1.errors.txt +++ b/tests/baselines/reference/conditionalTypes1.errors.txt @@ -64,8 +64,8 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(159,5): error TS2 tests/cases/conformance/types/conditional/conditionalTypes1.ts(160,5): error TS2322: Type 'T' is not assignable to type 'ZeroOf'. Type 'string | number' is not assignable to type 'ZeroOf'. Type 'string' is not assignable to type 'ZeroOf'. -tests/cases/conformance/types/conditional/conditionalTypes1.ts(255,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'z' must be of type 'T1', but here has type 'Foo'. -tests/cases/conformance/types/conditional/conditionalTypes1.ts(280,43): error TS2322: Type 'T95' is not assignable to type 'T94'. +tests/cases/conformance/types/conditional/conditionalTypes1.ts(259,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'z' must be of type 'T1', but here has type 'Foo'. +tests/cases/conformance/types/conditional/conditionalTypes1.ts(284,43): error TS2322: Type 'T95' is not assignable to type 'T94'. Type 'boolean' is not assignable to type 'true'. @@ -370,6 +370,10 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(280,43): error TS type T51 = IsNever; // false type T52 = IsNever; // false + function f22(x: T extends (infer U)[] ? U[] : never) { + let e = x[0]; // {} + } + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; diff --git a/tests/baselines/reference/conditionalTypes1.js b/tests/baselines/reference/conditionalTypes1.js index 87821ee17c1..f0acf03c967 100644 --- a/tests/baselines/reference/conditionalTypes1.js +++ b/tests/baselines/reference/conditionalTypes1.js @@ -213,6 +213,10 @@ type T50 = IsNever; // true type T51 = IsNever; // false type T52 = IsNever; // false +function f22(x: T extends (infer U)[] ? U[] : never) { + let e = x[0]; // {} +} + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; @@ -398,6 +402,9 @@ function f21(x, y) { x = y; // Error y = x; // Error } +function f22(x) { + var e = x[0]; // {} +} var convert = function (value) { return value; }; var convert2 = function (value) { return value; }; function f31() { @@ -590,6 +597,7 @@ declare type IsNever = [T] extends [never] ? true : false; declare type T50 = IsNever; declare type T51 = IsNever; declare type T52 = IsNever; +declare function f22(x: T extends (infer U)[] ? U[] : never): void; declare type Eq = T extends U ? U extends T ? true : false : false; declare type T60 = Eq; declare type T61 = Eq; diff --git a/tests/baselines/reference/conditionalTypes1.symbols b/tests/baselines/reference/conditionalTypes1.symbols index bc64848213d..6a59d7da9db 100644 --- a/tests/baselines/reference/conditionalTypes1.symbols +++ b/tests/baselines/reference/conditionalTypes1.symbols @@ -819,475 +819,488 @@ type T52 = IsNever; // false >T52 : Symbol(T52, Decl(conditionalTypes1.ts, 211, 27)) >IsNever : Symbol(IsNever, Decl(conditionalTypes1.ts, 206, 47)) +function f22(x: T extends (infer U)[] ? U[] : never) { +>f22 : Symbol(f22, Decl(conditionalTypes1.ts, 212, 24)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 214, 13)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 214, 16)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 214, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 214, 35)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 214, 35)) + + let e = x[0]; // {} +>e : Symbol(e, Decl(conditionalTypes1.ts, 215, 7)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 214, 16)) +} + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 212, 24)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 216, 8)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 216, 10)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 216, 8)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 216, 10)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 216, 10)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 216, 8)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 220, 8)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 220, 10)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 220, 8)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 220, 10)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 220, 10)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 220, 8)) type T60 = Eq; // true ->T60 : Symbol(T60, Decl(conditionalTypes1.ts, 216, 65)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 212, 24)) +>T60 : Symbol(T60, Decl(conditionalTypes1.ts, 220, 65)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) type T61 = Eq; // false ->T61 : Symbol(T61, Decl(conditionalTypes1.ts, 217, 26)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 212, 24)) +>T61 : Symbol(T61, Decl(conditionalTypes1.ts, 221, 26)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) type T62 = Eq; // false ->T62 : Symbol(T62, Decl(conditionalTypes1.ts, 218, 27)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 212, 24)) +>T62 : Symbol(T62, Decl(conditionalTypes1.ts, 222, 27)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) type T63 = Eq; // true ->T63 : Symbol(T63, Decl(conditionalTypes1.ts, 219, 27)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 212, 24)) +>T63 : Symbol(T63, Decl(conditionalTypes1.ts, 223, 27)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) type Eq1 = Eq extends false ? false : true; ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 220, 28)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 222, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 222, 11)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 212, 24)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 222, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 222, 11)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 226, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 226, 11)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 226, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 226, 11)) type T70 = Eq1; // true ->T70 : Symbol(T70, Decl(conditionalTypes1.ts, 222, 55)) ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 220, 28)) +>T70 : Symbol(T70, Decl(conditionalTypes1.ts, 226, 55)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) type T71 = Eq1; // false ->T71 : Symbol(T71, Decl(conditionalTypes1.ts, 223, 27)) ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 220, 28)) +>T71 : Symbol(T71, Decl(conditionalTypes1.ts, 227, 27)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) type T72 = Eq1; // false ->T72 : Symbol(T72, Decl(conditionalTypes1.ts, 224, 28)) ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 220, 28)) +>T72 : Symbol(T72, Decl(conditionalTypes1.ts, 228, 28)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) type T73 = Eq1; // true ->T73 : Symbol(T73, Decl(conditionalTypes1.ts, 225, 28)) ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 220, 28)) +>T73 : Symbol(T73, Decl(conditionalTypes1.ts, 229, 28)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) type Eq2 = Eq extends true ? true : false; ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 226, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 228, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 228, 11)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 212, 24)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 228, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 228, 11)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 232, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 232, 11)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 232, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 232, 11)) type T80 = Eq2; // true ->T80 : Symbol(T80, Decl(conditionalTypes1.ts, 228, 54)) ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 226, 29)) +>T80 : Symbol(T80, Decl(conditionalTypes1.ts, 232, 54)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) type T81 = Eq2; // false ->T81 : Symbol(T81, Decl(conditionalTypes1.ts, 229, 27)) ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 226, 29)) +>T81 : Symbol(T81, Decl(conditionalTypes1.ts, 233, 27)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) type T82 = Eq2; // false ->T82 : Symbol(T82, Decl(conditionalTypes1.ts, 230, 28)) ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 226, 29)) +>T82 : Symbol(T82, Decl(conditionalTypes1.ts, 234, 28)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) type T83 = Eq2; // true ->T83 : Symbol(T83, Decl(conditionalTypes1.ts, 231, 28)) ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 226, 29)) +>T83 : Symbol(T83, Decl(conditionalTypes1.ts, 235, 28)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) // Repro from #21756 type Foo = T extends string ? boolean : number; ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 232, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 236, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 236, 9)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 240, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 240, 9)) type Bar = T extends string ? boolean : number; ->Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 236, 50)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 237, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 237, 9)) +>Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 240, 50)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 241, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 241, 9)) const convert = (value: Foo): Bar => value; ->convert : Symbol(convert, Decl(conditionalTypes1.ts, 238, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 238, 17)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 238, 20)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 232, 29)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 238, 17)) ->Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 236, 50)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 238, 17)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 238, 20)) +>convert : Symbol(convert, Decl(conditionalTypes1.ts, 242, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 242, 17)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 242, 20)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 242, 17)) +>Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 240, 50)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 242, 17)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 242, 20)) type Baz = Foo; ->Baz : Symbol(Baz, Decl(conditionalTypes1.ts, 238, 52)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 240, 9)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 232, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 240, 9)) +>Baz : Symbol(Baz, Decl(conditionalTypes1.ts, 242, 52)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 244, 9)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 244, 9)) const convert2 = (value: Foo): Baz => value; ->convert2 : Symbol(convert2, Decl(conditionalTypes1.ts, 241, 5)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 241, 18)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 241, 21)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 232, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 241, 18)) ->Baz : Symbol(Baz, Decl(conditionalTypes1.ts, 238, 52)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 241, 18)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 241, 21)) +>convert2 : Symbol(convert2, Decl(conditionalTypes1.ts, 245, 5)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 245, 18)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 245, 21)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 245, 18)) +>Baz : Symbol(Baz, Decl(conditionalTypes1.ts, 242, 52)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 245, 18)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 245, 21)) function f31() { ->f31 : Symbol(f31, Decl(conditionalTypes1.ts, 241, 53)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 243, 13)) +>f31 : Symbol(f31, Decl(conditionalTypes1.ts, 245, 53)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 247, 13)) type T1 = T extends string ? boolean : number; ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 243, 19)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 243, 13)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 247, 19)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 247, 13)) type T2 = T extends string ? boolean : number; ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 244, 50)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 243, 13)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 248, 50)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 247, 13)) var x: T1; ->x : Symbol(x, Decl(conditionalTypes1.ts, 246, 7), Decl(conditionalTypes1.ts, 247, 7)) ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 243, 19)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 250, 7), Decl(conditionalTypes1.ts, 251, 7)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 247, 19)) var x: T2; ->x : Symbol(x, Decl(conditionalTypes1.ts, 246, 7), Decl(conditionalTypes1.ts, 247, 7)) ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 244, 50)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 250, 7), Decl(conditionalTypes1.ts, 251, 7)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 248, 50)) } function f32() { ->f32 : Symbol(f32, Decl(conditionalTypes1.ts, 248, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 250, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 250, 15)) +>f32 : Symbol(f32, Decl(conditionalTypes1.ts, 252, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 254, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 254, 15)) type T1 = T & U extends string ? boolean : number; ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 250, 22)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 250, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 250, 15)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 254, 22)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 254, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 254, 15)) type T2 = Foo; ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 251, 54)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 232, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 250, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 250, 15)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 255, 54)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 254, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 254, 15)) var z: T1; ->z : Symbol(z, Decl(conditionalTypes1.ts, 253, 7), Decl(conditionalTypes1.ts, 254, 7)) ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 250, 22)) +>z : Symbol(z, Decl(conditionalTypes1.ts, 257, 7), Decl(conditionalTypes1.ts, 258, 7)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 254, 22)) var z: T2; // Error, T2 is distributive, T1 isn't ->z : Symbol(z, Decl(conditionalTypes1.ts, 253, 7), Decl(conditionalTypes1.ts, 254, 7)) ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 251, 54)) +>z : Symbol(z, Decl(conditionalTypes1.ts, 257, 7), Decl(conditionalTypes1.ts, 258, 7)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 255, 54)) } function f33() { ->f33 : Symbol(f33, Decl(conditionalTypes1.ts, 255, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 257, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 257, 15)) +>f33 : Symbol(f33, Decl(conditionalTypes1.ts, 259, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 261, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 261, 15)) type T1 = Foo; ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 257, 22)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 232, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 257, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 257, 15)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 261, 22)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 261, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 261, 15)) type T2 = Bar; ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 258, 25)) ->Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 236, 50)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 257, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 257, 15)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 262, 25)) +>Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 240, 50)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 261, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 261, 15)) var z: T1; ->z : Symbol(z, Decl(conditionalTypes1.ts, 260, 7), Decl(conditionalTypes1.ts, 261, 7)) ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 257, 22)) +>z : Symbol(z, Decl(conditionalTypes1.ts, 264, 7), Decl(conditionalTypes1.ts, 265, 7)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 261, 22)) var z: T2; ->z : Symbol(z, Decl(conditionalTypes1.ts, 260, 7), Decl(conditionalTypes1.ts, 261, 7)) ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 258, 25)) +>z : Symbol(z, Decl(conditionalTypes1.ts, 264, 7), Decl(conditionalTypes1.ts, 265, 7)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 262, 25)) } // Repro from #21823 type T90 = T extends 0 ? 0 : () => 0; ->T90 : Symbol(T90, Decl(conditionalTypes1.ts, 262, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 266, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 266, 9)) +>T90 : Symbol(T90, Decl(conditionalTypes1.ts, 266, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 270, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 270, 9)) type T91 = T extends 0 ? 0 : () => 0; ->T91 : Symbol(T91, Decl(conditionalTypes1.ts, 266, 40)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 267, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 267, 9)) +>T91 : Symbol(T91, Decl(conditionalTypes1.ts, 270, 40)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 271, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 271, 9)) const f40 = (a: T90): T91 => a; ->f40 : Symbol(f40, Decl(conditionalTypes1.ts, 268, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 268, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 268, 16)) ->T90 : Symbol(T90, Decl(conditionalTypes1.ts, 262, 1)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 268, 13)) ->T91 : Symbol(T91, Decl(conditionalTypes1.ts, 266, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 268, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 268, 16)) +>f40 : Symbol(f40, Decl(conditionalTypes1.ts, 272, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 272, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 272, 16)) +>T90 : Symbol(T90, Decl(conditionalTypes1.ts, 266, 1)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 272, 13)) +>T91 : Symbol(T91, Decl(conditionalTypes1.ts, 270, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 272, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 272, 16)) const f41 = (a: T91): T90 => a; ->f41 : Symbol(f41, Decl(conditionalTypes1.ts, 269, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 269, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 269, 16)) ->T91 : Symbol(T91, Decl(conditionalTypes1.ts, 266, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 269, 13)) ->T90 : Symbol(T90, Decl(conditionalTypes1.ts, 262, 1)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 269, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 269, 16)) +>f41 : Symbol(f41, Decl(conditionalTypes1.ts, 273, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 273, 16)) +>T91 : Symbol(T91, Decl(conditionalTypes1.ts, 270, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) +>T90 : Symbol(T90, Decl(conditionalTypes1.ts, 266, 1)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 273, 16)) type T92 = T extends () => 0 ? () => 1 : () => 2; ->T92 : Symbol(T92, Decl(conditionalTypes1.ts, 269, 40)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 271, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 271, 9)) +>T92 : Symbol(T92, Decl(conditionalTypes1.ts, 273, 40)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 275, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 275, 9)) type T93 = T extends () => 0 ? () => 1 : () => 2; ->T93 : Symbol(T93, Decl(conditionalTypes1.ts, 271, 52)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 272, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 272, 9)) +>T93 : Symbol(T93, Decl(conditionalTypes1.ts, 275, 52)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 276, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 276, 9)) const f42 = (a: T92): T93 => a; ->f42 : Symbol(f42, Decl(conditionalTypes1.ts, 273, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 273, 16)) ->T92 : Symbol(T92, Decl(conditionalTypes1.ts, 269, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) ->T93 : Symbol(T93, Decl(conditionalTypes1.ts, 271, 52)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 273, 16)) +>f42 : Symbol(f42, Decl(conditionalTypes1.ts, 277, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 277, 16)) +>T92 : Symbol(T92, Decl(conditionalTypes1.ts, 273, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) +>T93 : Symbol(T93, Decl(conditionalTypes1.ts, 275, 52)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 277, 16)) const f43 = (a: T93): T92 => a; ->f43 : Symbol(f43, Decl(conditionalTypes1.ts, 274, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 274, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 274, 16)) ->T93 : Symbol(T93, Decl(conditionalTypes1.ts, 271, 52)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 274, 13)) ->T92 : Symbol(T92, Decl(conditionalTypes1.ts, 269, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 274, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 274, 16)) +>f43 : Symbol(f43, Decl(conditionalTypes1.ts, 278, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 278, 16)) +>T93 : Symbol(T93, Decl(conditionalTypes1.ts, 275, 52)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) +>T92 : Symbol(T92, Decl(conditionalTypes1.ts, 273, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 278, 16)) type T94 = T extends string ? true : 42; ->T94 : Symbol(T94, Decl(conditionalTypes1.ts, 274, 40)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 276, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 276, 9)) +>T94 : Symbol(T94, Decl(conditionalTypes1.ts, 278, 40)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 280, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 280, 9)) type T95 = T extends string ? boolean : number; ->T95 : Symbol(T95, Decl(conditionalTypes1.ts, 276, 43)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 277, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 277, 9)) +>T95 : Symbol(T95, Decl(conditionalTypes1.ts, 280, 43)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 281, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 281, 9)) const f44 = (value: T94): T95 => value; ->f44 : Symbol(f44, Decl(conditionalTypes1.ts, 278, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 278, 16)) ->T94 : Symbol(T94, Decl(conditionalTypes1.ts, 274, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) ->T95 : Symbol(T95, Decl(conditionalTypes1.ts, 276, 43)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 278, 16)) +>f44 : Symbol(f44, Decl(conditionalTypes1.ts, 282, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 282, 16)) +>T94 : Symbol(T94, Decl(conditionalTypes1.ts, 278, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) +>T95 : Symbol(T95, Decl(conditionalTypes1.ts, 280, 43)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 282, 16)) const f45 = (value: T95): T94 => value; // Error ->f45 : Symbol(f45, Decl(conditionalTypes1.ts, 279, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 279, 13)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 279, 16)) ->T95 : Symbol(T95, Decl(conditionalTypes1.ts, 276, 43)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 279, 13)) ->T94 : Symbol(T94, Decl(conditionalTypes1.ts, 274, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 279, 13)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 279, 16)) +>f45 : Symbol(f45, Decl(conditionalTypes1.ts, 283, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 283, 13)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 283, 16)) +>T95 : Symbol(T95, Decl(conditionalTypes1.ts, 280, 43)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 283, 13)) +>T94 : Symbol(T94, Decl(conditionalTypes1.ts, 278, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 283, 13)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 283, 16)) // Repro from #21863 function f50() { ->f50 : Symbol(f50, Decl(conditionalTypes1.ts, 279, 48)) +>f50 : Symbol(f50, Decl(conditionalTypes1.ts, 283, 48)) type Eq = T extends U ? U extends T ? true : false : false; ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 283, 16)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 284, 12)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 284, 14)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 284, 12)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 284, 14)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 284, 14)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 284, 12)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 287, 16)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 288, 12)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 288, 14)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 288, 12)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 288, 14)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 288, 14)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 288, 12)) type If = S extends false ? U : T; ->If : Symbol(If, Decl(conditionalTypes1.ts, 284, 69)) ->S : Symbol(S, Decl(conditionalTypes1.ts, 285, 12)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 285, 14)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 285, 17)) ->S : Symbol(S, Decl(conditionalTypes1.ts, 285, 12)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 285, 17)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 285, 14)) +>If : Symbol(If, Decl(conditionalTypes1.ts, 288, 69)) +>S : Symbol(S, Decl(conditionalTypes1.ts, 289, 12)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 289, 14)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 289, 17)) +>S : Symbol(S, Decl(conditionalTypes1.ts, 289, 12)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 289, 17)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 289, 14)) type Omit = { [P in keyof T]: If, never, P>; }[keyof T]; ->Omit : Symbol(Omit, Decl(conditionalTypes1.ts, 285, 47)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 286, 14)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 286, 37)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 286, 14)) ->If : Symbol(If, Decl(conditionalTypes1.ts, 284, 69)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 283, 16)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 286, 14)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 286, 37)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 286, 37)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 286, 14)) +>Omit : Symbol(Omit, Decl(conditionalTypes1.ts, 289, 47)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 290, 14)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 290, 37)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 290, 14)) +>If : Symbol(If, Decl(conditionalTypes1.ts, 288, 69)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 287, 16)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 290, 14)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 290, 37)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 290, 37)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 290, 14)) type Omit2 = { [P in keyof T]: If, never, P>; }[keyof T]; ->Omit2 : Symbol(Omit2, Decl(conditionalTypes1.ts, 286, 94)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 287, 15)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 287, 32)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 287, 49)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 287, 15)) ->If : Symbol(If, Decl(conditionalTypes1.ts, 284, 69)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 283, 16)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 287, 15)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 287, 49)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 287, 32)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 287, 49)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 287, 15)) +>Omit2 : Symbol(Omit2, Decl(conditionalTypes1.ts, 290, 94)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 291, 15)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 291, 32)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 291, 49)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 291, 15)) +>If : Symbol(If, Decl(conditionalTypes1.ts, 288, 69)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 287, 16)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 291, 15)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 291, 49)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 291, 32)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 291, 49)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 291, 15)) type A = Omit<{ a: void; b: never; }>; // 'a' ->A : Symbol(A, Decl(conditionalTypes1.ts, 287, 102)) ->Omit : Symbol(Omit, Decl(conditionalTypes1.ts, 285, 47)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 288, 19)) ->b : Symbol(b, Decl(conditionalTypes1.ts, 288, 28)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 291, 102)) +>Omit : Symbol(Omit, Decl(conditionalTypes1.ts, 289, 47)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 292, 19)) +>b : Symbol(b, Decl(conditionalTypes1.ts, 292, 28)) type B = Omit2<{ a: void; b: never; }>; // 'a' ->B : Symbol(B, Decl(conditionalTypes1.ts, 288, 42)) ->Omit2 : Symbol(Omit2, Decl(conditionalTypes1.ts, 286, 94)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 289, 20)) ->b : Symbol(b, Decl(conditionalTypes1.ts, 289, 29)) +>B : Symbol(B, Decl(conditionalTypes1.ts, 292, 42)) +>Omit2 : Symbol(Omit2, Decl(conditionalTypes1.ts, 290, 94)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 293, 20)) +>b : Symbol(b, Decl(conditionalTypes1.ts, 293, 29)) } // Repro from #21862 type OldDiff = ( ->OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 290, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 294, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 294, 30)) +>OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 294, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 298, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 298, 30)) & { [P in T]: P; } ->P : Symbol(P, Decl(conditionalTypes1.ts, 295, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 294, 13)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 295, 9)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 299, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 298, 13)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 299, 9)) & { [P in U]: never; } ->P : Symbol(P, Decl(conditionalTypes1.ts, 296, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 294, 30)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 300, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 298, 30)) & { [x: string]: never; } ->x : Symbol(x, Decl(conditionalTypes1.ts, 297, 9)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 301, 9)) )[T]; ->T : Symbol(T, Decl(conditionalTypes1.ts, 294, 13)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 298, 13)) type NewDiff = T extends U ? never : T; ->NewDiff : Symbol(NewDiff, Decl(conditionalTypes1.ts, 298, 5)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 299, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 299, 15)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 299, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 299, 15)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 299, 13)) +>NewDiff : Symbol(NewDiff, Decl(conditionalTypes1.ts, 302, 5)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 303, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 303, 15)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 303, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 303, 15)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 303, 13)) interface A { ->A : Symbol(A, Decl(conditionalTypes1.ts, 299, 45)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) a: 'a'; ->a : Symbol(A.a, Decl(conditionalTypes1.ts, 300, 13)) +>a : Symbol(A.a, Decl(conditionalTypes1.ts, 304, 13)) } interface B1 extends A { ->B1 : Symbol(B1, Decl(conditionalTypes1.ts, 302, 1)) ->A : Symbol(A, Decl(conditionalTypes1.ts, 299, 45)) +>B1 : Symbol(B1, Decl(conditionalTypes1.ts, 306, 1)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) b: 'b'; ->b : Symbol(B1.b, Decl(conditionalTypes1.ts, 303, 24)) +>b : Symbol(B1.b, Decl(conditionalTypes1.ts, 307, 24)) c: OldDiff; ->c : Symbol(B1.c, Decl(conditionalTypes1.ts, 304, 11)) ->OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 290, 1)) ->A : Symbol(A, Decl(conditionalTypes1.ts, 299, 45)) +>c : Symbol(B1.c, Decl(conditionalTypes1.ts, 308, 11)) +>OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 294, 1)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) } interface B2 extends A { ->B2 : Symbol(B2, Decl(conditionalTypes1.ts, 306, 1)) ->A : Symbol(A, Decl(conditionalTypes1.ts, 299, 45)) +>B2 : Symbol(B2, Decl(conditionalTypes1.ts, 310, 1)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) b: 'b'; ->b : Symbol(B2.b, Decl(conditionalTypes1.ts, 307, 24)) +>b : Symbol(B2.b, Decl(conditionalTypes1.ts, 311, 24)) c: NewDiff; ->c : Symbol(B2.c, Decl(conditionalTypes1.ts, 308, 11)) ->NewDiff : Symbol(NewDiff, Decl(conditionalTypes1.ts, 298, 5)) ->A : Symbol(A, Decl(conditionalTypes1.ts, 299, 45)) +>c : Symbol(B2.c, Decl(conditionalTypes1.ts, 312, 11)) +>NewDiff : Symbol(NewDiff, Decl(conditionalTypes1.ts, 302, 5)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) } type c1 = B1['c']; // 'c' | 'b' ->c1 : Symbol(c1, Decl(conditionalTypes1.ts, 310, 1)) ->B1 : Symbol(B1, Decl(conditionalTypes1.ts, 302, 1)) +>c1 : Symbol(c1, Decl(conditionalTypes1.ts, 314, 1)) +>B1 : Symbol(B1, Decl(conditionalTypes1.ts, 306, 1)) type c2 = B2['c']; // 'c' | 'b' ->c2 : Symbol(c2, Decl(conditionalTypes1.ts, 311, 18)) ->B2 : Symbol(B2, Decl(conditionalTypes1.ts, 306, 1)) +>c2 : Symbol(c2, Decl(conditionalTypes1.ts, 315, 18)) +>B2 : Symbol(B2, Decl(conditionalTypes1.ts, 310, 1)) // Repro from #21929 type NonFooKeys1 = OldDiff; ->NonFooKeys1 : Symbol(NonFooKeys1, Decl(conditionalTypes1.ts, 312, 18)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 316, 17)) ->OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 290, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 316, 17)) +>NonFooKeys1 : Symbol(NonFooKeys1, Decl(conditionalTypes1.ts, 316, 18)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 320, 17)) +>OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 294, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 320, 17)) type NonFooKeys2 = Exclude; ->NonFooKeys2 : Symbol(NonFooKeys2, Decl(conditionalTypes1.ts, 316, 61)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 317, 17)) +>NonFooKeys2 : Symbol(NonFooKeys2, Decl(conditionalTypes1.ts, 320, 61)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 321, 17)) >Exclude : Symbol(Exclude, Decl(lib.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 317, 17)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 321, 17)) type Test1 = NonFooKeys1<{foo: 1, bar: 2, baz: 3}>; // "bar" | "baz" ->Test1 : Symbol(Test1, Decl(conditionalTypes1.ts, 317, 61)) ->NonFooKeys1 : Symbol(NonFooKeys1, Decl(conditionalTypes1.ts, 312, 18)) ->foo : Symbol(foo, Decl(conditionalTypes1.ts, 319, 26)) ->bar : Symbol(bar, Decl(conditionalTypes1.ts, 319, 33)) ->baz : Symbol(baz, Decl(conditionalTypes1.ts, 319, 41)) +>Test1 : Symbol(Test1, Decl(conditionalTypes1.ts, 321, 61)) +>NonFooKeys1 : Symbol(NonFooKeys1, Decl(conditionalTypes1.ts, 316, 18)) +>foo : Symbol(foo, Decl(conditionalTypes1.ts, 323, 26)) +>bar : Symbol(bar, Decl(conditionalTypes1.ts, 323, 33)) +>baz : Symbol(baz, Decl(conditionalTypes1.ts, 323, 41)) type Test2 = NonFooKeys2<{foo: 1, bar: 2, baz: 3}>; // "bar" | "baz" ->Test2 : Symbol(Test2, Decl(conditionalTypes1.ts, 319, 51)) ->NonFooKeys2 : Symbol(NonFooKeys2, Decl(conditionalTypes1.ts, 316, 61)) ->foo : Symbol(foo, Decl(conditionalTypes1.ts, 320, 26)) ->bar : Symbol(bar, Decl(conditionalTypes1.ts, 320, 33)) ->baz : Symbol(baz, Decl(conditionalTypes1.ts, 320, 41)) +>Test2 : Symbol(Test2, Decl(conditionalTypes1.ts, 323, 51)) +>NonFooKeys2 : Symbol(NonFooKeys2, Decl(conditionalTypes1.ts, 320, 61)) +>foo : Symbol(foo, Decl(conditionalTypes1.ts, 324, 26)) +>bar : Symbol(bar, Decl(conditionalTypes1.ts, 324, 33)) +>baz : Symbol(baz, Decl(conditionalTypes1.ts, 324, 41)) // Repro from #21729 interface Foo2 { foo: string; } ->Foo2 : Symbol(Foo2, Decl(conditionalTypes1.ts, 320, 51)) ->foo : Symbol(Foo2.foo, Decl(conditionalTypes1.ts, 324, 16)) +>Foo2 : Symbol(Foo2, Decl(conditionalTypes1.ts, 324, 51)) +>foo : Symbol(Foo2.foo, Decl(conditionalTypes1.ts, 328, 16)) interface Bar2 { bar: string; } ->Bar2 : Symbol(Bar2, Decl(conditionalTypes1.ts, 324, 31)) ->bar : Symbol(Bar2.bar, Decl(conditionalTypes1.ts, 325, 16)) +>Bar2 : Symbol(Bar2, Decl(conditionalTypes1.ts, 328, 31)) +>bar : Symbol(Bar2.bar, Decl(conditionalTypes1.ts, 329, 16)) type FooBar = Foo2 | Bar2; ->FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 325, 31)) ->Foo2 : Symbol(Foo2, Decl(conditionalTypes1.ts, 320, 51)) ->Bar2 : Symbol(Bar2, Decl(conditionalTypes1.ts, 324, 31)) +>FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 329, 31)) +>Foo2 : Symbol(Foo2, Decl(conditionalTypes1.ts, 324, 51)) +>Bar2 : Symbol(Bar2, Decl(conditionalTypes1.ts, 328, 31)) declare interface ExtractFooBar { } ->ExtractFooBar : Symbol(ExtractFooBar, Decl(conditionalTypes1.ts, 326, 26)) ->FB : Symbol(FB, Decl(conditionalTypes1.ts, 327, 32)) ->FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 325, 31)) +>ExtractFooBar : Symbol(ExtractFooBar, Decl(conditionalTypes1.ts, 330, 26)) +>FB : Symbol(FB, Decl(conditionalTypes1.ts, 331, 32)) +>FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 329, 31)) type Extracted = { ->Extracted : Symbol(Extracted, Decl(conditionalTypes1.ts, 327, 54)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 329, 15)) +>Extracted : Symbol(Extracted, Decl(conditionalTypes1.ts, 331, 54)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) [K in keyof Struct]: Struct[K] extends FooBar ? ExtractFooBar : Struct[K]; ->K : Symbol(K, Decl(conditionalTypes1.ts, 330, 5)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 329, 15)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 329, 15)) ->K : Symbol(K, Decl(conditionalTypes1.ts, 330, 5)) ->FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 325, 31)) ->ExtractFooBar : Symbol(ExtractFooBar, Decl(conditionalTypes1.ts, 326, 26)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 329, 15)) ->K : Symbol(K, Decl(conditionalTypes1.ts, 330, 5)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 329, 15)) ->K : Symbol(K, Decl(conditionalTypes1.ts, 330, 5)) +>K : Symbol(K, Decl(conditionalTypes1.ts, 334, 5)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) +>K : Symbol(K, Decl(conditionalTypes1.ts, 334, 5)) +>FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 329, 31)) +>ExtractFooBar : Symbol(ExtractFooBar, Decl(conditionalTypes1.ts, 330, 26)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) +>K : Symbol(K, Decl(conditionalTypes1.ts, 334, 5)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) +>K : Symbol(K, Decl(conditionalTypes1.ts, 334, 5)) } diff --git a/tests/baselines/reference/conditionalTypes1.types b/tests/baselines/reference/conditionalTypes1.types index 01fef85dfcb..0d7624b07c8 100644 --- a/tests/baselines/reference/conditionalTypes1.types +++ b/tests/baselines/reference/conditionalTypes1.types @@ -926,6 +926,21 @@ type T52 = IsNever; // false >T52 : false >IsNever : IsNever +function f22(x: T extends (infer U)[] ? U[] : never) { +>f22 : (x: T extends infer U[] ? U[] : never) => void +>T : T +>x : T extends infer U[] ? U[] : never +>T : T +>U : U +>U : U + + let e = x[0]; // {} +>e : {} +>x[0] : {} +>x : T extends infer U[] ? U[] : never +>0 : 0 +} + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; From 272aba1c7ddd6f1203c9c6fd8105e22f5ca3d26b Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 28 Mar 2018 13:26:10 -0700 Subject: [PATCH 38/75] Port generated lib files --- src/lib/dom.generated.d.ts | 48 +++++++++++-------- src/lib/webworker.generated.d.ts | 2 +- .../mappedTypeRecursiveInference.types | 20 ++++---- 3 files changed, 38 insertions(+), 32 deletions(-) diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 63c8f199e7b..32ceabdb29b 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -3285,6 +3285,7 @@ interface DOMTokenList { contains(token: string): boolean; item(index: number): string | null; remove(...tokens: string[]): void; + replace(oldToken: string, newToken: string): void; toString(): string; toggle(token: string, force?: boolean): boolean; [index: number]: string; @@ -3532,10 +3533,10 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; - "touchcancel": Event; - "touchend": Event; - "touchmove": Event; - "touchstart": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "volumechange": Event; "waiting": Event; "webkitfullscreenchange": Event; @@ -3949,10 +3950,10 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * @param ev The event. */ ontimeupdate: ((this: Document, ev: Event) => any) | null; - ontouchcancel: ((this: Document, ev: Event) => any) | null; - ontouchend: ((this: Document, ev: Event) => any) | null; - ontouchmove: ((this: Document, ev: Event) => any) | null; - ontouchstart: ((this: Document, ev: Event) => any) | null; + ontouchcancel: ((this: Document, ev: TouchEvent) => any) | null; + ontouchend: ((this: Document, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Document, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Document, ev: TouchEvent) => any) | null; onvisibilitychange: (this: Document, ev: Event) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. @@ -4138,6 +4139,7 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; + elementsFromPoint(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. @@ -4312,6 +4314,7 @@ interface DocumentEvent { 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; @@ -4431,10 +4434,10 @@ interface ElementEventMap extends GlobalEventHandlersEventMap { "MSPointerOut": Event; "MSPointerOver": Event; "MSPointerUp": Event; - "touchcancel": Event; - "touchend": Event; - "touchmove": Event; - "touchstart": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "webkitfullscreenchange": Event; "webkitfullscreenerror": Event; } @@ -4473,10 +4476,10 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNod onmspointerout: ((this: Element, ev: Event) => any) | null; onmspointerover: ((this: Element, ev: Event) => any) | null; onmspointerup: ((this: Element, ev: Event) => any) | null; - ontouchcancel: ((this: Element, ev: Event) => any) | null; - ontouchend: ((this: Element, ev: Event) => any) | null; - ontouchmove: ((this: Element, ev: Event) => any) | null; - ontouchstart: ((this: Element, ev: Event) => any) | null; + ontouchcancel: ((this: Element, ev: TouchEvent) => any) | null; + ontouchend: ((this: Element, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Element, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Element, ev: TouchEvent) => any) | null; onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; outerHTML: string; @@ -6131,6 +6134,7 @@ interface HTMLImageElement extends HTMLElement { readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; /** * Sets or retrieves the height of the object. */ @@ -14742,7 +14746,7 @@ interface WebSocket extends EventTarget { readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: string | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; @@ -14868,10 +14872,10 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "submit": Event; "suspend": Event; "timeupdate": Event; - "touchcancel": Event; - "touchend": Event; - "touchmove": Event; - "touchstart": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; "unload": Event; "volumechange": Event; "vrdisplayactivate": Event; @@ -15059,6 +15063,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; @@ -15868,6 +15873,7 @@ 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; diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 8c3dac36d23..c60ccb44f90 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -1443,7 +1443,7 @@ interface WebSocket extends EventTarget { readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: string | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; diff --git a/tests/baselines/reference/mappedTypeRecursiveInference.types b/tests/baselines/reference/mappedTypeRecursiveInference.types index e0b35459343..e58ed5e310d 100644 --- a/tests/baselines/reference/mappedTypeRecursiveInference.types +++ b/tests/baselines/reference/mappedTypeRecursiveInference.types @@ -108,24 +108,24 @@ let xhr: XMLHttpRequest; >XMLHttpRequest : XMLHttpRequest const out2 = foo(xhr); ->out2 : { msCaching: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onreadystatechange: {}; readonly readyState: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly response: {}; readonly responseText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; responseType: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseURL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseXML: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly status: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly statusText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; timeout: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly upload: { addEventListener: any; removeEventListener: any; dispatchEvent: any; onabort: any; onerror: any; onload: any; onloadend: any; onloadstart: any; onprogress: any; ontimeout: any; }; withCredentials: { valueOf: any; }; abort: {}; getAllResponseHeaders: {}; getResponseHeader: {}; msCachingEnabled: {}; open: {}; overrideMimeType: {}; send: {}; setRequestHeader: {}; readonly DONE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly HEADERS_RECEIVED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly LOADING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly OPENED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly UNSENT: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; addEventListener: {}; removeEventListener: {}; dispatchEvent: {}; onabort: {}; onerror: {}; onload: {}; onloadend: {}; onloadstart: {}; onprogress: {}; ontimeout: {}; } ->foo(xhr) : { msCaching: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onreadystatechange: {}; readonly readyState: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly response: {}; readonly responseText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; responseType: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseURL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseXML: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly status: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly statusText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; timeout: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly upload: { addEventListener: any; removeEventListener: any; dispatchEvent: any; onabort: any; onerror: any; onload: any; onloadend: any; onloadstart: any; onprogress: any; ontimeout: any; }; withCredentials: { valueOf: any; }; abort: {}; getAllResponseHeaders: {}; getResponseHeader: {}; msCachingEnabled: {}; open: {}; overrideMimeType: {}; send: {}; setRequestHeader: {}; readonly DONE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly HEADERS_RECEIVED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly LOADING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly OPENED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly UNSENT: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; addEventListener: {}; removeEventListener: {}; dispatchEvent: {}; onabort: {}; onerror: {}; onload: {}; onloadend: {}; onloadstart: {}; onprogress: {}; ontimeout: {}; } +>out2 : { msCaching: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onreadystatechange: {}; readonly readyState: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly response: {}; readonly responseText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; responseType: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseURL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseXML: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly status: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly statusText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; timeout: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly upload: { addEventListener: any; removeEventListener: any; dispatchEvent: any; onabort: any; onerror: any; onload: any; onloadend: any; onloadstart: any; onprogress: any; ontimeout: any; }; withCredentials: { valueOf: any; }; abort: {}; getAllResponseHeaders: {}; getResponseHeader: {}; msCachingEnabled: {}; open: {}; overrideMimeType: {}; send: {}; setRequestHeader: {}; readonly DONE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly HEADERS_RECEIVED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly LOADING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly OPENED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly UNSENT: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; addEventListener: {}; removeEventListener: {}; dispatchEvent: {}; onabort: {}; onerror: {}; onload: {}; onloadend: {}; onloadstart: {}; onprogress: {}; ontimeout: {}; } +>foo(xhr) : { msCaching: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onreadystatechange: {}; readonly readyState: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly response: {}; readonly responseText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; responseType: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseURL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseXML: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly status: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly statusText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; timeout: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly upload: { addEventListener: any; removeEventListener: any; dispatchEvent: any; onabort: any; onerror: any; onload: any; onloadend: any; onloadstart: any; onprogress: any; ontimeout: any; }; withCredentials: { valueOf: any; }; abort: {}; getAllResponseHeaders: {}; getResponseHeader: {}; msCachingEnabled: {}; open: {}; overrideMimeType: {}; send: {}; setRequestHeader: {}; readonly DONE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly HEADERS_RECEIVED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly LOADING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly OPENED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly UNSENT: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; addEventListener: {}; removeEventListener: {}; dispatchEvent: {}; onabort: {}; onerror: {}; onload: {}; onloadend: {}; onloadstart: {}; onprogress: {}; ontimeout: {}; } >foo : (deep: Deep) => T >xhr : XMLHttpRequest out2.responseXML ->out2.responseXML : { readonly URL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly URLUnencoded: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly activeElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; alinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly all: { readonly length: any; item: any; namedItem: any; }; readonly anchors: { item: any; namedItem: any; readonly length: any; }; readonly applets: { item: any; namedItem: any; readonly length: any; }; bgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; body: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly characterSet: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; charset: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly compatMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; cookie: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly currentScript: { async: any; charset: any; crossOrigin: any; defer: any; event: any; htmlFor: any; integrity: any; noModule: any; src: any; text: any; type: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; } | { type: any; addEventListener: any; removeEventListener: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly href: any; }; readonly defaultView: { Blob: any; URL: any; URLSearchParams: any; readonly applicationCache: any; readonly caches: any; readonly clientInformation: any; readonly closed: any; readonly crypto: any; customElements: any; defaultStatus: any; readonly devicePixelRatio: any; readonly doNotTrack: any; readonly document: any; event: any; readonly external: any; readonly frameElement: any; readonly frames: any; readonly history: any; readonly innerHeight: any; readonly innerWidth: any; readonly isSecureContext: any; readonly length: any; location: any; readonly locationbar: any; readonly menubar: any; readonly msContentScript: any; readonly msCredentials: any; name: any; readonly navigator: any; offscreenBuffering: any; onabort: any; onbeforeunload: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncompassneedscalibration: any; oncontextmenu: any; ondblclick: any; ondevicelight: any; ondevicemotion: any; ondeviceorientation: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onhashchange: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmessage: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onoffline: any; ononline: any; onorientationchange: any; onpagehide: any; onpageshow: any; onpause: any; onplay: any; onplaying: any; onpopstate: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onresize: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onstalled: any; onstorage: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: any; onvolumechange: any; onvrdisplayactivate: any; onvrdisplayblur: any; onvrdisplayconnect: any; onvrdisplaydeactivate: any; onvrdisplaydisconnect: any; onvrdisplayfocus: any; onvrdisplaypointerrestricted: any; onvrdisplaypointerunrestricted: any; onvrdisplaypresentchange: any; onwaiting: any; readonly opener: any; readonly orientation: any; readonly outerHeight: any; readonly outerWidth: any; readonly pageXOffset: any; readonly pageYOffset: any; readonly parent: any; readonly performance: any; readonly personalbar: any; readonly screen: any; readonly screenLeft: any; readonly screenTop: any; readonly screenX: any; readonly screenY: any; readonly scrollX: any; readonly scrollY: any; readonly scrollbars: any; readonly self: any; readonly speechSynthesis: any; status: any; readonly statusbar: any; readonly styleMedia: any; readonly toolbar: any; readonly top: any; readonly window: any; alert: any; blur: any; cancelAnimationFrame: any; captureEvents: any; close: any; confirm: any; createImageBitmap: any; departFocus: any; focus: any; getComputedStyle: any; getMatchedCSSRules: any; getSelection: any; matchMedia: any; moveBy: any; moveTo: any; msWriteProfilerMark: any; open: any; postMessage: any; prompt: any; releaseEvents: any; requestAnimationFrame: any; resizeBy: any; resizeTo: any; scroll: any; scrollBy: any; scrollTo: any; stop: any; webkitCancelAnimationFrame: any; webkitConvertPointFromNodeToPage: any; webkitConvertPointFromPageToNode: any; webkitRequestAnimationFrame: any; addEventListener: any; removeEventListener: any; dispatchEvent: any; clearInterval: any; clearTimeout: any; setInterval: any; setTimeout: any; clearImmediate: any; setImmediate: any; readonly sessionStorage: any; readonly localStorage: any; readonly console: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly indexedDB: any; atob: any; btoa: any; fetch: any; }; designMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; dir: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly doctype: { readonly entities: any; readonly internalSubset: any; readonly name: any; readonly notations: any; readonly publicId: any; readonly systemId: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; remove: any; }; readonly documentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; domain: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly embeds: { item: any; namedItem: any; readonly length: any; }; fgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly forms: { item: any; namedItem: any; readonly length: any; }; readonly fullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly fullscreenEnabled: { valueOf: any; }; readonly head: { profile: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly hidden: { valueOf: any; }; readonly images: { item: any; namedItem: any; readonly length: any; }; readonly implementation: { createDocument: any; createDocumentType: any; createHTMLDocument: any; hasFeature: any; }; readonly inputEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly lastModified: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; linkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly links: { item: any; namedItem: any; readonly length: any; }; location: { hash: any; host: any; hostname: any; href: any; readonly origin: any; pathname: any; port: any; protocol: any; search: any; assign: any; reload: any; replace: any; toString: any; }; msCSSOMElementFloatMetrics: { valueOf: any; }; msCapsLockWarningOff: { valueOf: any; }; onabort: {}; onactivate: {}; onbeforeactivate: {}; onbeforedeactivate: {}; onblur: {}; oncanplay: {}; oncanplaythrough: {}; onchange: {}; onclick: {}; oncontextmenu: {}; ondblclick: {}; ondeactivate: {}; ondrag: {}; ondragend: {}; ondragenter: {}; ondragleave: {}; ondragover: {}; ondragstart: {}; ondrop: {}; ondurationchange: {}; onemptied: {}; onended: {}; onerror: {}; onfocus: {}; onfullscreenchange: {}; onfullscreenerror: {}; oninput: {}; oninvalid: {}; onkeydown: {}; onkeypress: {}; onkeyup: {}; onload: {}; onloadeddata: {}; onloadedmetadata: {}; onloadstart: {}; onmousedown: {}; onmousemove: {}; onmouseout: {}; onmouseover: {}; onmouseup: {}; onmousewheel: {}; onmscontentzoom: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsinertiastart: {}; onmsmanipulationstatechanged: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; onmssitemodejumplistitemremoved: {}; onmsthumbnailclick: {}; onpause: {}; onplay: {}; onplaying: {}; onpointerlockchange: {}; onpointerlockerror: {}; onprogress: {}; onratechange: {}; onreadystatechange: {}; onreset: {}; onscroll: {}; onseeked: {}; onseeking: {}; onselect: {}; onselectionchange: {}; onselectstart: {}; onstalled: {}; onstop: {}; onsubmit: {}; onsuspend: {}; ontimeupdate: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onvisibilitychange: {}; onvolumechange: {}; onwaiting: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; readonly plugins: { item: any; namedItem: any; readonly length: any; }; readonly pointerLockElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly readyState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly referrer: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly rootElement: { contentScriptType: any; contentStyleType: any; currentScale: any; readonly currentTranslate: any; readonly height: any; onabort: any; onerror: any; onresize: any; onscroll: any; onunload: any; onzoom: any; readonly pixelUnitToMillimeterX: any; readonly pixelUnitToMillimeterY: any; readonly screenPixelToMillimeterX: any; readonly screenPixelToMillimeterY: any; readonly viewport: any; readonly width: any; readonly x: any; readonly y: any; checkEnclosure: any; checkIntersection: any; createSVGAngle: any; createSVGLength: any; createSVGMatrix: any; createSVGNumber: any; createSVGPoint: any; createSVGRect: any; createSVGTransform: any; createSVGTransformFromMatrix: any; deselectAll: any; forceRedraw: any; getComputedStyle: any; getCurrentTime: any; getElementById: any; getEnclosureList: any; getIntersectionList: any; pauseAnimations: any; setCurrentTime: any; suspendRedraw: any; unpauseAnimations: any; unsuspendRedraw: any; unsuspendRedrawAll: any; addEventListener: any; removeEventListener: any; readonly farthestViewportElement: any; readonly nearestViewportElement: any; readonly transform: any; getBBox: any; getCTM: any; getScreenCTM: any; getTransformToElement: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly requiredExtensions: any; readonly requiredFeatures: any; readonly systemLanguage: any; hasExtension: any; createEvent: any; readonly preserveAspectRatio: any; readonly viewBox: any; readonly zoomAndPan: any; }; readonly scripts: { item: any; namedItem: any; readonly length: any; }; readonly scrollingElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly styleSheets: { readonly length: any; item: any; }; title: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly visibilityState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; vlinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly webkitCurrentFullScreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenEnabled: { valueOf: any; }; readonly webkitIsFullScreen: { valueOf: any; }; readonly xmlEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; xmlStandalone: { valueOf: any; }; xmlVersion: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; adoptNode: {}; captureEvents: {}; caretRangeFromPoint: {}; clear: {}; close: {}; createAttribute: {}; createAttributeNS: {}; createCDATASection: {}; createComment: {}; createDocumentFragment: {}; createElement: {}; createElementNS: {}; createExpression: {}; createNSResolver: {}; createNodeIterator: {}; createProcessingInstruction: {}; createRange: {}; createTextNode: {}; createTouch: {}; createTouchList: {}; createTreeWalker: {}; elementFromPoint: {}; evaluate: {}; execCommand: {}; execCommandShowHelp: {}; exitFullscreen: {}; exitPointerLock: {}; focus: {}; getElementById: {}; getElementsByClassName: {}; getElementsByName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; getSelection: {}; hasFocus: {}; importNode: {}; msElementsFromPoint: {}; msElementsFromRect: {}; open: {}; queryCommandEnabled: {}; queryCommandIndeterm: {}; queryCommandState: {}; queryCommandSupported: {}; queryCommandText: {}; queryCommandValue: {}; releaseEvents: {}; webkitCancelFullScreen: {}; webkitExitFullscreen: {}; write: {}; writeln: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; createEvent: {}; } ->out2 : { msCaching: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onreadystatechange: {}; readonly readyState: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly response: {}; readonly responseText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; responseType: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseURL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseXML: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly status: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly statusText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; timeout: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly upload: { addEventListener: any; removeEventListener: any; dispatchEvent: any; onabort: any; onerror: any; onload: any; onloadend: any; onloadstart: any; onprogress: any; ontimeout: any; }; withCredentials: { valueOf: any; }; abort: {}; getAllResponseHeaders: {}; getResponseHeader: {}; msCachingEnabled: {}; open: {}; overrideMimeType: {}; send: {}; setRequestHeader: {}; readonly DONE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly HEADERS_RECEIVED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly LOADING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly OPENED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly UNSENT: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; addEventListener: {}; removeEventListener: {}; dispatchEvent: {}; onabort: {}; onerror: {}; onload: {}; onloadend: {}; onloadstart: {}; onprogress: {}; ontimeout: {}; } ->responseXML : { readonly URL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly URLUnencoded: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly activeElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; alinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly all: { readonly length: any; item: any; namedItem: any; }; readonly anchors: { item: any; namedItem: any; readonly length: any; }; readonly applets: { item: any; namedItem: any; readonly length: any; }; bgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; body: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly characterSet: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; charset: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly compatMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; cookie: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly currentScript: { async: any; charset: any; crossOrigin: any; defer: any; event: any; htmlFor: any; integrity: any; noModule: any; src: any; text: any; type: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; } | { type: any; addEventListener: any; removeEventListener: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly href: any; }; readonly defaultView: { Blob: any; URL: any; URLSearchParams: any; readonly applicationCache: any; readonly caches: any; readonly clientInformation: any; readonly closed: any; readonly crypto: any; customElements: any; defaultStatus: any; readonly devicePixelRatio: any; readonly doNotTrack: any; readonly document: any; event: any; readonly external: any; readonly frameElement: any; readonly frames: any; readonly history: any; readonly innerHeight: any; readonly innerWidth: any; readonly isSecureContext: any; readonly length: any; location: any; readonly locationbar: any; readonly menubar: any; readonly msContentScript: any; readonly msCredentials: any; name: any; readonly navigator: any; offscreenBuffering: any; onabort: any; onbeforeunload: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncompassneedscalibration: any; oncontextmenu: any; ondblclick: any; ondevicelight: any; ondevicemotion: any; ondeviceorientation: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onhashchange: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmessage: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onoffline: any; ononline: any; onorientationchange: any; onpagehide: any; onpageshow: any; onpause: any; onplay: any; onplaying: any; onpopstate: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onresize: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onstalled: any; onstorage: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: any; onvolumechange: any; onvrdisplayactivate: any; onvrdisplayblur: any; onvrdisplayconnect: any; onvrdisplaydeactivate: any; onvrdisplaydisconnect: any; onvrdisplayfocus: any; onvrdisplaypointerrestricted: any; onvrdisplaypointerunrestricted: any; onvrdisplaypresentchange: any; onwaiting: any; readonly opener: any; readonly orientation: any; readonly outerHeight: any; readonly outerWidth: any; readonly pageXOffset: any; readonly pageYOffset: any; readonly parent: any; readonly performance: any; readonly personalbar: any; readonly screen: any; readonly screenLeft: any; readonly screenTop: any; readonly screenX: any; readonly screenY: any; readonly scrollX: any; readonly scrollY: any; readonly scrollbars: any; readonly self: any; readonly speechSynthesis: any; status: any; readonly statusbar: any; readonly styleMedia: any; readonly toolbar: any; readonly top: any; readonly window: any; alert: any; blur: any; cancelAnimationFrame: any; captureEvents: any; close: any; confirm: any; createImageBitmap: any; departFocus: any; focus: any; getComputedStyle: any; getMatchedCSSRules: any; getSelection: any; matchMedia: any; moveBy: any; moveTo: any; msWriteProfilerMark: any; open: any; postMessage: any; prompt: any; releaseEvents: any; requestAnimationFrame: any; resizeBy: any; resizeTo: any; scroll: any; scrollBy: any; scrollTo: any; stop: any; webkitCancelAnimationFrame: any; webkitConvertPointFromNodeToPage: any; webkitConvertPointFromPageToNode: any; webkitRequestAnimationFrame: any; addEventListener: any; removeEventListener: any; dispatchEvent: any; clearInterval: any; clearTimeout: any; setInterval: any; setTimeout: any; clearImmediate: any; setImmediate: any; readonly sessionStorage: any; readonly localStorage: any; readonly console: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly indexedDB: any; atob: any; btoa: any; fetch: any; }; designMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; dir: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly doctype: { readonly entities: any; readonly internalSubset: any; readonly name: any; readonly notations: any; readonly publicId: any; readonly systemId: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; remove: any; }; readonly documentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; domain: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly embeds: { item: any; namedItem: any; readonly length: any; }; fgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly forms: { item: any; namedItem: any; readonly length: any; }; readonly fullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly fullscreenEnabled: { valueOf: any; }; readonly head: { profile: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly hidden: { valueOf: any; }; readonly images: { item: any; namedItem: any; readonly length: any; }; readonly implementation: { createDocument: any; createDocumentType: any; createHTMLDocument: any; hasFeature: any; }; readonly inputEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly lastModified: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; linkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly links: { item: any; namedItem: any; readonly length: any; }; location: { hash: any; host: any; hostname: any; href: any; readonly origin: any; pathname: any; port: any; protocol: any; search: any; assign: any; reload: any; replace: any; toString: any; }; msCSSOMElementFloatMetrics: { valueOf: any; }; msCapsLockWarningOff: { valueOf: any; }; onabort: {}; onactivate: {}; onbeforeactivate: {}; onbeforedeactivate: {}; onblur: {}; oncanplay: {}; oncanplaythrough: {}; onchange: {}; onclick: {}; oncontextmenu: {}; ondblclick: {}; ondeactivate: {}; ondrag: {}; ondragend: {}; ondragenter: {}; ondragleave: {}; ondragover: {}; ondragstart: {}; ondrop: {}; ondurationchange: {}; onemptied: {}; onended: {}; onerror: {}; onfocus: {}; onfullscreenchange: {}; onfullscreenerror: {}; oninput: {}; oninvalid: {}; onkeydown: {}; onkeypress: {}; onkeyup: {}; onload: {}; onloadeddata: {}; onloadedmetadata: {}; onloadstart: {}; onmousedown: {}; onmousemove: {}; onmouseout: {}; onmouseover: {}; onmouseup: {}; onmousewheel: {}; onmscontentzoom: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsinertiastart: {}; onmsmanipulationstatechanged: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; onmssitemodejumplistitemremoved: {}; onmsthumbnailclick: {}; onpause: {}; onplay: {}; onplaying: {}; onpointerlockchange: {}; onpointerlockerror: {}; onprogress: {}; onratechange: {}; onreadystatechange: {}; onreset: {}; onscroll: {}; onseeked: {}; onseeking: {}; onselect: {}; onselectionchange: {}; onselectstart: {}; onstalled: {}; onstop: {}; onsubmit: {}; onsuspend: {}; ontimeupdate: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onvisibilitychange: {}; onvolumechange: {}; onwaiting: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; readonly plugins: { item: any; namedItem: any; readonly length: any; }; readonly pointerLockElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly readyState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly referrer: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly rootElement: { contentScriptType: any; contentStyleType: any; currentScale: any; readonly currentTranslate: any; readonly height: any; onabort: any; onerror: any; onresize: any; onscroll: any; onunload: any; onzoom: any; readonly pixelUnitToMillimeterX: any; readonly pixelUnitToMillimeterY: any; readonly screenPixelToMillimeterX: any; readonly screenPixelToMillimeterY: any; readonly viewport: any; readonly width: any; readonly x: any; readonly y: any; checkEnclosure: any; checkIntersection: any; createSVGAngle: any; createSVGLength: any; createSVGMatrix: any; createSVGNumber: any; createSVGPoint: any; createSVGRect: any; createSVGTransform: any; createSVGTransformFromMatrix: any; deselectAll: any; forceRedraw: any; getComputedStyle: any; getCurrentTime: any; getElementById: any; getEnclosureList: any; getIntersectionList: any; pauseAnimations: any; setCurrentTime: any; suspendRedraw: any; unpauseAnimations: any; unsuspendRedraw: any; unsuspendRedrawAll: any; addEventListener: any; removeEventListener: any; readonly farthestViewportElement: any; readonly nearestViewportElement: any; readonly transform: any; getBBox: any; getCTM: any; getScreenCTM: any; getTransformToElement: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly requiredExtensions: any; readonly requiredFeatures: any; readonly systemLanguage: any; hasExtension: any; createEvent: any; readonly preserveAspectRatio: any; readonly viewBox: any; readonly zoomAndPan: any; }; readonly scripts: { item: any; namedItem: any; readonly length: any; }; readonly scrollingElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly styleSheets: { readonly length: any; item: any; }; title: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly visibilityState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; vlinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly webkitCurrentFullScreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenEnabled: { valueOf: any; }; readonly webkitIsFullScreen: { valueOf: any; }; readonly xmlEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; xmlStandalone: { valueOf: any; }; xmlVersion: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; adoptNode: {}; captureEvents: {}; caretRangeFromPoint: {}; clear: {}; close: {}; createAttribute: {}; createAttributeNS: {}; createCDATASection: {}; createComment: {}; createDocumentFragment: {}; createElement: {}; createElementNS: {}; createExpression: {}; createNSResolver: {}; createNodeIterator: {}; createProcessingInstruction: {}; createRange: {}; createTextNode: {}; createTouch: {}; createTouchList: {}; createTreeWalker: {}; elementFromPoint: {}; evaluate: {}; execCommand: {}; execCommandShowHelp: {}; exitFullscreen: {}; exitPointerLock: {}; focus: {}; getElementById: {}; getElementsByClassName: {}; getElementsByName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; getSelection: {}; hasFocus: {}; importNode: {}; msElementsFromPoint: {}; msElementsFromRect: {}; open: {}; queryCommandEnabled: {}; queryCommandIndeterm: {}; queryCommandState: {}; queryCommandSupported: {}; queryCommandText: {}; queryCommandValue: {}; releaseEvents: {}; webkitCancelFullScreen: {}; webkitExitFullscreen: {}; write: {}; writeln: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; createEvent: {}; } +>out2.responseXML : { readonly URL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly URLUnencoded: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly activeElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; alinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly all: { readonly length: any; item: any; namedItem: any; }; readonly anchors: { item: any; namedItem: any; readonly length: any; }; readonly applets: { item: any; namedItem: any; readonly length: any; }; bgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; body: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly characterSet: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; charset: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly compatMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; cookie: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly currentScript: { async: any; charset: any; crossOrigin: any; defer: any; event: any; htmlFor: any; integrity: any; noModule: any; src: any; text: any; type: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; } | { type: any; addEventListener: any; removeEventListener: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly href: any; }; readonly defaultView: { Blob: any; URL: any; URLSearchParams: any; readonly applicationCache: any; readonly caches: any; readonly clientInformation: any; readonly closed: any; readonly crypto: any; customElements: any; defaultStatus: any; readonly devicePixelRatio: any; readonly doNotTrack: any; readonly document: any; event: any; readonly external: any; readonly frameElement: any; readonly frames: any; readonly history: any; readonly innerHeight: any; readonly innerWidth: any; readonly isSecureContext: any; readonly length: any; location: any; readonly locationbar: any; readonly menubar: any; readonly msContentScript: any; readonly msCredentials: any; name: any; readonly navigator: any; offscreenBuffering: any; onabort: any; onbeforeunload: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncompassneedscalibration: any; oncontextmenu: any; ondblclick: any; ondevicelight: any; ondevicemotion: any; ondeviceorientation: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onhashchange: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmessage: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onoffline: any; ononline: any; onorientationchange: any; onpagehide: any; onpageshow: any; onpause: any; onplay: any; onplaying: any; onpopstate: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onresize: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onstalled: any; onstorage: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: any; onvolumechange: any; onvrdisplayactivate: any; onvrdisplayblur: any; onvrdisplayconnect: any; onvrdisplaydeactivate: any; onvrdisplaydisconnect: any; onvrdisplayfocus: any; onvrdisplaypointerrestricted: any; onvrdisplaypointerunrestricted: any; onvrdisplaypresentchange: any; onwaiting: any; readonly opener: any; readonly orientation: any; readonly outerHeight: any; readonly outerWidth: any; readonly pageXOffset: any; readonly pageYOffset: any; readonly parent: any; readonly performance: any; readonly personalbar: any; readonly screen: any; readonly screenLeft: any; readonly screenTop: any; readonly screenX: any; readonly screenY: any; readonly scrollX: any; readonly scrollY: any; readonly scrollbars: any; readonly self: any; readonly speechSynthesis: any; status: any; readonly statusbar: any; readonly styleMedia: any; readonly toolbar: any; readonly top: any; readonly window: any; alert: any; blur: any; cancelAnimationFrame: any; captureEvents: any; close: any; confirm: any; createImageBitmap: any; departFocus: any; focus: any; getComputedStyle: any; getMatchedCSSRules: any; getSelection: any; matchMedia: any; moveBy: any; moveTo: any; msWriteProfilerMark: any; open: any; postMessage: any; print: any; prompt: any; releaseEvents: any; requestAnimationFrame: any; resizeBy: any; resizeTo: any; scroll: any; scrollBy: any; scrollTo: any; stop: any; webkitCancelAnimationFrame: any; webkitConvertPointFromNodeToPage: any; webkitConvertPointFromPageToNode: any; webkitRequestAnimationFrame: any; addEventListener: any; removeEventListener: any; dispatchEvent: any; clearInterval: any; clearTimeout: any; setInterval: any; setTimeout: any; clearImmediate: any; setImmediate: any; readonly sessionStorage: any; readonly localStorage: any; readonly console: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly indexedDB: any; atob: any; btoa: any; fetch: any; }; designMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; dir: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly doctype: { readonly entities: any; readonly internalSubset: any; readonly name: any; readonly notations: any; readonly publicId: any; readonly systemId: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; remove: any; }; readonly documentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; domain: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly embeds: { item: any; namedItem: any; readonly length: any; }; fgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly forms: { item: any; namedItem: any; readonly length: any; }; readonly fullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly fullscreenEnabled: { valueOf: any; }; readonly head: { profile: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly hidden: { valueOf: any; }; readonly images: { item: any; namedItem: any; readonly length: any; }; readonly implementation: { createDocument: any; createDocumentType: any; createHTMLDocument: any; hasFeature: any; }; readonly inputEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly lastModified: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; linkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly links: { item: any; namedItem: any; readonly length: any; }; location: { hash: any; host: any; hostname: any; href: any; readonly origin: any; pathname: any; port: any; protocol: any; search: any; assign: any; reload: any; replace: any; toString: any; }; msCSSOMElementFloatMetrics: { valueOf: any; }; msCapsLockWarningOff: { valueOf: any; }; onabort: {}; onactivate: {}; onbeforeactivate: {}; onbeforedeactivate: {}; onblur: {}; oncanplay: {}; oncanplaythrough: {}; onchange: {}; onclick: {}; oncontextmenu: {}; ondblclick: {}; ondeactivate: {}; ondrag: {}; ondragend: {}; ondragenter: {}; ondragleave: {}; ondragover: {}; ondragstart: {}; ondrop: {}; ondurationchange: {}; onemptied: {}; onended: {}; onerror: {}; onfocus: {}; onfullscreenchange: {}; onfullscreenerror: {}; oninput: {}; oninvalid: {}; onkeydown: {}; onkeypress: {}; onkeyup: {}; onload: {}; onloadeddata: {}; onloadedmetadata: {}; onloadstart: {}; onmousedown: {}; onmousemove: {}; onmouseout: {}; onmouseover: {}; onmouseup: {}; onmousewheel: {}; onmscontentzoom: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsinertiastart: {}; onmsmanipulationstatechanged: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; onmssitemodejumplistitemremoved: {}; onmsthumbnailclick: {}; onpause: {}; onplay: {}; onplaying: {}; onpointerlockchange: {}; onpointerlockerror: {}; onprogress: {}; onratechange: {}; onreadystatechange: {}; onreset: {}; onscroll: {}; onseeked: {}; onseeking: {}; onselect: {}; onselectionchange: {}; onselectstart: {}; onstalled: {}; onstop: {}; onsubmit: {}; onsuspend: {}; ontimeupdate: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onvisibilitychange: {}; onvolumechange: {}; onwaiting: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; readonly plugins: { item: any; namedItem: any; readonly length: any; }; readonly pointerLockElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly readyState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly referrer: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly rootElement: { contentScriptType: any; contentStyleType: any; currentScale: any; readonly currentTranslate: any; readonly height: any; onabort: any; onerror: any; onresize: any; onscroll: any; onunload: any; onzoom: any; readonly pixelUnitToMillimeterX: any; readonly pixelUnitToMillimeterY: any; readonly screenPixelToMillimeterX: any; readonly screenPixelToMillimeterY: any; readonly viewport: any; readonly width: any; readonly x: any; readonly y: any; checkEnclosure: any; checkIntersection: any; createSVGAngle: any; createSVGLength: any; createSVGMatrix: any; createSVGNumber: any; createSVGPoint: any; createSVGRect: any; createSVGTransform: any; createSVGTransformFromMatrix: any; deselectAll: any; forceRedraw: any; getComputedStyle: any; getCurrentTime: any; getElementById: any; getEnclosureList: any; getIntersectionList: any; pauseAnimations: any; setCurrentTime: any; suspendRedraw: any; unpauseAnimations: any; unsuspendRedraw: any; unsuspendRedrawAll: any; addEventListener: any; removeEventListener: any; readonly farthestViewportElement: any; readonly nearestViewportElement: any; readonly transform: any; getBBox: any; getCTM: any; getScreenCTM: any; getTransformToElement: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly requiredExtensions: any; readonly requiredFeatures: any; readonly systemLanguage: any; hasExtension: any; createEvent: any; readonly preserveAspectRatio: any; readonly viewBox: any; readonly zoomAndPan: any; }; readonly scripts: { item: any; namedItem: any; readonly length: any; }; readonly scrollingElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly styleSheets: { readonly length: any; item: any; }; title: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly visibilityState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; vlinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly webkitCurrentFullScreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenEnabled: { valueOf: any; }; readonly webkitIsFullScreen: { valueOf: any; }; readonly xmlEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; xmlStandalone: { valueOf: any; }; xmlVersion: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; adoptNode: {}; captureEvents: {}; caretRangeFromPoint: {}; clear: {}; close: {}; createAttribute: {}; createAttributeNS: {}; createCDATASection: {}; createComment: {}; createDocumentFragment: {}; createElement: {}; createElementNS: {}; createExpression: {}; createNSResolver: {}; createNodeIterator: {}; createProcessingInstruction: {}; createRange: {}; createTextNode: {}; createTouch: {}; createTouchList: {}; createTreeWalker: {}; elementFromPoint: {}; elementsFromPoint: {}; evaluate: {}; execCommand: {}; execCommandShowHelp: {}; exitFullscreen: {}; exitPointerLock: {}; focus: {}; getElementById: {}; getElementsByClassName: {}; getElementsByName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; getSelection: {}; hasFocus: {}; importNode: {}; msElementsFromPoint: {}; msElementsFromRect: {}; open: {}; queryCommandEnabled: {}; queryCommandIndeterm: {}; queryCommandState: {}; queryCommandSupported: {}; queryCommandText: {}; queryCommandValue: {}; releaseEvents: {}; webkitCancelFullScreen: {}; webkitExitFullscreen: {}; write: {}; writeln: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; createEvent: {}; } +>out2 : { msCaching: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onreadystatechange: {}; readonly readyState: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly response: {}; readonly responseText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; responseType: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseURL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseXML: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly status: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly statusText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; timeout: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly upload: { addEventListener: any; removeEventListener: any; dispatchEvent: any; onabort: any; onerror: any; onload: any; onloadend: any; onloadstart: any; onprogress: any; ontimeout: any; }; withCredentials: { valueOf: any; }; abort: {}; getAllResponseHeaders: {}; getResponseHeader: {}; msCachingEnabled: {}; open: {}; overrideMimeType: {}; send: {}; setRequestHeader: {}; readonly DONE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly HEADERS_RECEIVED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly LOADING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly OPENED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly UNSENT: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; addEventListener: {}; removeEventListener: {}; dispatchEvent: {}; onabort: {}; onerror: {}; onload: {}; onloadend: {}; onloadstart: {}; onprogress: {}; ontimeout: {}; } +>responseXML : { readonly URL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly URLUnencoded: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly activeElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; alinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly all: { readonly length: any; item: any; namedItem: any; }; readonly anchors: { item: any; namedItem: any; readonly length: any; }; readonly applets: { item: any; namedItem: any; readonly length: any; }; bgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; body: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly characterSet: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; charset: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly compatMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; cookie: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly currentScript: { async: any; charset: any; crossOrigin: any; defer: any; event: any; htmlFor: any; integrity: any; noModule: any; src: any; text: any; type: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; } | { type: any; addEventListener: any; removeEventListener: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly href: any; }; readonly defaultView: { Blob: any; URL: any; URLSearchParams: any; readonly applicationCache: any; readonly caches: any; readonly clientInformation: any; readonly closed: any; readonly crypto: any; customElements: any; defaultStatus: any; readonly devicePixelRatio: any; readonly doNotTrack: any; readonly document: any; event: any; readonly external: any; readonly frameElement: any; readonly frames: any; readonly history: any; readonly innerHeight: any; readonly innerWidth: any; readonly isSecureContext: any; readonly length: any; location: any; readonly locationbar: any; readonly menubar: any; readonly msContentScript: any; readonly msCredentials: any; name: any; readonly navigator: any; offscreenBuffering: any; onabort: any; onbeforeunload: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncompassneedscalibration: any; oncontextmenu: any; ondblclick: any; ondevicelight: any; ondevicemotion: any; ondeviceorientation: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onhashchange: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmessage: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onoffline: any; ononline: any; onorientationchange: any; onpagehide: any; onpageshow: any; onpause: any; onplay: any; onplaying: any; onpopstate: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onresize: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onstalled: any; onstorage: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: any; onvolumechange: any; onvrdisplayactivate: any; onvrdisplayblur: any; onvrdisplayconnect: any; onvrdisplaydeactivate: any; onvrdisplaydisconnect: any; onvrdisplayfocus: any; onvrdisplaypointerrestricted: any; onvrdisplaypointerunrestricted: any; onvrdisplaypresentchange: any; onwaiting: any; readonly opener: any; readonly orientation: any; readonly outerHeight: any; readonly outerWidth: any; readonly pageXOffset: any; readonly pageYOffset: any; readonly parent: any; readonly performance: any; readonly personalbar: any; readonly screen: any; readonly screenLeft: any; readonly screenTop: any; readonly screenX: any; readonly screenY: any; readonly scrollX: any; readonly scrollY: any; readonly scrollbars: any; readonly self: any; readonly speechSynthesis: any; status: any; readonly statusbar: any; readonly styleMedia: any; readonly toolbar: any; readonly top: any; readonly window: any; alert: any; blur: any; cancelAnimationFrame: any; captureEvents: any; close: any; confirm: any; createImageBitmap: any; departFocus: any; focus: any; getComputedStyle: any; getMatchedCSSRules: any; getSelection: any; matchMedia: any; moveBy: any; moveTo: any; msWriteProfilerMark: any; open: any; postMessage: any; print: any; prompt: any; releaseEvents: any; requestAnimationFrame: any; resizeBy: any; resizeTo: any; scroll: any; scrollBy: any; scrollTo: any; stop: any; webkitCancelAnimationFrame: any; webkitConvertPointFromNodeToPage: any; webkitConvertPointFromPageToNode: any; webkitRequestAnimationFrame: any; addEventListener: any; removeEventListener: any; dispatchEvent: any; clearInterval: any; clearTimeout: any; setInterval: any; setTimeout: any; clearImmediate: any; setImmediate: any; readonly sessionStorage: any; readonly localStorage: any; readonly console: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly indexedDB: any; atob: any; btoa: any; fetch: any; }; designMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; dir: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly doctype: { readonly entities: any; readonly internalSubset: any; readonly name: any; readonly notations: any; readonly publicId: any; readonly systemId: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; remove: any; }; readonly documentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; domain: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly embeds: { item: any; namedItem: any; readonly length: any; }; fgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly forms: { item: any; namedItem: any; readonly length: any; }; readonly fullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly fullscreenEnabled: { valueOf: any; }; readonly head: { profile: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly hidden: { valueOf: any; }; readonly images: { item: any; namedItem: any; readonly length: any; }; readonly implementation: { createDocument: any; createDocumentType: any; createHTMLDocument: any; hasFeature: any; }; readonly inputEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly lastModified: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; linkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly links: { item: any; namedItem: any; readonly length: any; }; location: { hash: any; host: any; hostname: any; href: any; readonly origin: any; pathname: any; port: any; protocol: any; search: any; assign: any; reload: any; replace: any; toString: any; }; msCSSOMElementFloatMetrics: { valueOf: any; }; msCapsLockWarningOff: { valueOf: any; }; onabort: {}; onactivate: {}; onbeforeactivate: {}; onbeforedeactivate: {}; onblur: {}; oncanplay: {}; oncanplaythrough: {}; onchange: {}; onclick: {}; oncontextmenu: {}; ondblclick: {}; ondeactivate: {}; ondrag: {}; ondragend: {}; ondragenter: {}; ondragleave: {}; ondragover: {}; ondragstart: {}; ondrop: {}; ondurationchange: {}; onemptied: {}; onended: {}; onerror: {}; onfocus: {}; onfullscreenchange: {}; onfullscreenerror: {}; oninput: {}; oninvalid: {}; onkeydown: {}; onkeypress: {}; onkeyup: {}; onload: {}; onloadeddata: {}; onloadedmetadata: {}; onloadstart: {}; onmousedown: {}; onmousemove: {}; onmouseout: {}; onmouseover: {}; onmouseup: {}; onmousewheel: {}; onmscontentzoom: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsinertiastart: {}; onmsmanipulationstatechanged: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; onmssitemodejumplistitemremoved: {}; onmsthumbnailclick: {}; onpause: {}; onplay: {}; onplaying: {}; onpointerlockchange: {}; onpointerlockerror: {}; onprogress: {}; onratechange: {}; onreadystatechange: {}; onreset: {}; onscroll: {}; onseeked: {}; onseeking: {}; onselect: {}; onselectionchange: {}; onselectstart: {}; onstalled: {}; onstop: {}; onsubmit: {}; onsuspend: {}; ontimeupdate: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onvisibilitychange: {}; onvolumechange: {}; onwaiting: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; readonly plugins: { item: any; namedItem: any; readonly length: any; }; readonly pointerLockElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly readyState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly referrer: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly rootElement: { contentScriptType: any; contentStyleType: any; currentScale: any; readonly currentTranslate: any; readonly height: any; onabort: any; onerror: any; onresize: any; onscroll: any; onunload: any; onzoom: any; readonly pixelUnitToMillimeterX: any; readonly pixelUnitToMillimeterY: any; readonly screenPixelToMillimeterX: any; readonly screenPixelToMillimeterY: any; readonly viewport: any; readonly width: any; readonly x: any; readonly y: any; checkEnclosure: any; checkIntersection: any; createSVGAngle: any; createSVGLength: any; createSVGMatrix: any; createSVGNumber: any; createSVGPoint: any; createSVGRect: any; createSVGTransform: any; createSVGTransformFromMatrix: any; deselectAll: any; forceRedraw: any; getComputedStyle: any; getCurrentTime: any; getElementById: any; getEnclosureList: any; getIntersectionList: any; pauseAnimations: any; setCurrentTime: any; suspendRedraw: any; unpauseAnimations: any; unsuspendRedraw: any; unsuspendRedrawAll: any; addEventListener: any; removeEventListener: any; readonly farthestViewportElement: any; readonly nearestViewportElement: any; readonly transform: any; getBBox: any; getCTM: any; getScreenCTM: any; getTransformToElement: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly requiredExtensions: any; readonly requiredFeatures: any; readonly systemLanguage: any; hasExtension: any; createEvent: any; readonly preserveAspectRatio: any; readonly viewBox: any; readonly zoomAndPan: any; }; readonly scripts: { item: any; namedItem: any; readonly length: any; }; readonly scrollingElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly styleSheets: { readonly length: any; item: any; }; title: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly visibilityState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; vlinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly webkitCurrentFullScreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenEnabled: { valueOf: any; }; readonly webkitIsFullScreen: { valueOf: any; }; readonly xmlEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; xmlStandalone: { valueOf: any; }; xmlVersion: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; adoptNode: {}; captureEvents: {}; caretRangeFromPoint: {}; clear: {}; close: {}; createAttribute: {}; createAttributeNS: {}; createCDATASection: {}; createComment: {}; createDocumentFragment: {}; createElement: {}; createElementNS: {}; createExpression: {}; createNSResolver: {}; createNodeIterator: {}; createProcessingInstruction: {}; createRange: {}; createTextNode: {}; createTouch: {}; createTouchList: {}; createTreeWalker: {}; elementFromPoint: {}; elementsFromPoint: {}; evaluate: {}; execCommand: {}; execCommandShowHelp: {}; exitFullscreen: {}; exitPointerLock: {}; focus: {}; getElementById: {}; getElementsByClassName: {}; getElementsByName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; getSelection: {}; hasFocus: {}; importNode: {}; msElementsFromPoint: {}; msElementsFromRect: {}; open: {}; queryCommandEnabled: {}; queryCommandIndeterm: {}; queryCommandState: {}; queryCommandSupported: {}; queryCommandText: {}; queryCommandValue: {}; releaseEvents: {}; webkitCancelFullScreen: {}; webkitExitFullscreen: {}; write: {}; writeln: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; createEvent: {}; } out2.responseXML.activeElement.className.length >out2.responseXML.activeElement.className.length : { toString: {}; toFixed: {}; toExponential: {}; toPrecision: {}; valueOf: {}; toLocaleString: {}; } >out2.responseXML.activeElement.className : { toString: {}; charAt: {}; charCodeAt: {}; concat: {}; indexOf: {}; lastIndexOf: {}; localeCompare: {}; match: {}; replace: {}; search: {}; slice: {}; split: {}; substring: {}; toLowerCase: {}; toLocaleLowerCase: {}; toUpperCase: {}; toLocaleUpperCase: {}; trim: {}; readonly length: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; substr: {}; valueOf: {}; [Symbol.iterator]: {}; codePointAt: {}; includes: {}; endsWith: {}; normalize: {}; repeat: {}; startsWith: {}; anchor: {}; big: {}; blink: {}; bold: {}; fixed: {}; fontcolor: {}; fontsize: {}; italics: {}; link: {}; small: {}; strike: {}; sub: {}; sup: {}; } ->out2.responseXML.activeElement : { readonly assignedSlot: { name: any; assignedNodes: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly attributes: { readonly length: any; getNamedItem: any; getNamedItemNS: any; item: any; removeNamedItem: any; removeNamedItemNS: any; setNamedItem: any; setNamedItemNS: any; }; readonly classList: { readonly length: any; add: any; contains: any; item: any; remove: any; toString: any; toggle: any; }; className: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly clientHeight: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientLeft: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientTop: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientWidth: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; id: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; innerHTML: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; msContentZoomFactor: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly msRegionOverflow: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onariarequest: {}; oncommand: {}; ongotpointercapture: {}; onlostpointercapture: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsgotpointercapture: {}; onmsinertiastart: {}; onmslostpointercapture: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; outerHTML: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly prefix: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly scrollHeight: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; scrollLeft: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; scrollTop: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly scrollWidth: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly shadowRoot: { readonly host: any; innerHTML: any; readonly activeElement: any; readonly styleSheets: any; elementFromPoint: any; elementsFromPoint: any; getSelection: any; getElementById: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; }; slot: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly tagName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; attachShadow: {}; closest: {}; getAttribute: {}; getAttributeNS: {}; getAttributeNode: {}; getAttributeNodeNS: {}; getBoundingClientRect: {}; getClientRects: {}; getElementsByClassName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; hasAttribute: {}; hasAttributeNS: {}; hasAttributes: {}; insertAdjacentElement: {}; insertAdjacentHTML: {}; insertAdjacentText: {}; matches: {}; msGetRegionContent: {}; msGetUntransformedBounds: {}; msMatchesSelector: {}; msReleasePointerCapture: {}; msSetPointerCapture: {}; msZoomTo: {}; releasePointerCapture: {}; removeAttribute: {}; removeAttributeNS: {}; removeAttributeNode: {}; requestFullscreen: {}; requestPointerLock: {}; scroll: {}; scrollBy: {}; scrollIntoView: {}; scrollTo: {}; setAttribute: {}; setAttributeNS: {}; setAttributeNode: {}; setAttributeNodeNS: {}; setPointerCapture: {}; webkitMatchesSelector: {}; webkitRequestFullScreen: {}; webkitRequestFullscreen: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly nextElementSibling: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly previousElementSibling: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; remove: {}; } ->out2.responseXML : { readonly URL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly URLUnencoded: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly activeElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; alinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly all: { readonly length: any; item: any; namedItem: any; }; readonly anchors: { item: any; namedItem: any; readonly length: any; }; readonly applets: { item: any; namedItem: any; readonly length: any; }; bgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; body: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly characterSet: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; charset: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly compatMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; cookie: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly currentScript: { async: any; charset: any; crossOrigin: any; defer: any; event: any; htmlFor: any; integrity: any; noModule: any; src: any; text: any; type: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; } | { type: any; addEventListener: any; removeEventListener: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly href: any; }; readonly defaultView: { Blob: any; URL: any; URLSearchParams: any; readonly applicationCache: any; readonly caches: any; readonly clientInformation: any; readonly closed: any; readonly crypto: any; customElements: any; defaultStatus: any; readonly devicePixelRatio: any; readonly doNotTrack: any; readonly document: any; event: any; readonly external: any; readonly frameElement: any; readonly frames: any; readonly history: any; readonly innerHeight: any; readonly innerWidth: any; readonly isSecureContext: any; readonly length: any; location: any; readonly locationbar: any; readonly menubar: any; readonly msContentScript: any; readonly msCredentials: any; name: any; readonly navigator: any; offscreenBuffering: any; onabort: any; onbeforeunload: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncompassneedscalibration: any; oncontextmenu: any; ondblclick: any; ondevicelight: any; ondevicemotion: any; ondeviceorientation: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onhashchange: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmessage: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onoffline: any; ononline: any; onorientationchange: any; onpagehide: any; onpageshow: any; onpause: any; onplay: any; onplaying: any; onpopstate: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onresize: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onstalled: any; onstorage: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: any; onvolumechange: any; onvrdisplayactivate: any; onvrdisplayblur: any; onvrdisplayconnect: any; onvrdisplaydeactivate: any; onvrdisplaydisconnect: any; onvrdisplayfocus: any; onvrdisplaypointerrestricted: any; onvrdisplaypointerunrestricted: any; onvrdisplaypresentchange: any; onwaiting: any; readonly opener: any; readonly orientation: any; readonly outerHeight: any; readonly outerWidth: any; readonly pageXOffset: any; readonly pageYOffset: any; readonly parent: any; readonly performance: any; readonly personalbar: any; readonly screen: any; readonly screenLeft: any; readonly screenTop: any; readonly screenX: any; readonly screenY: any; readonly scrollX: any; readonly scrollY: any; readonly scrollbars: any; readonly self: any; readonly speechSynthesis: any; status: any; readonly statusbar: any; readonly styleMedia: any; readonly toolbar: any; readonly top: any; readonly window: any; alert: any; blur: any; cancelAnimationFrame: any; captureEvents: any; close: any; confirm: any; createImageBitmap: any; departFocus: any; focus: any; getComputedStyle: any; getMatchedCSSRules: any; getSelection: any; matchMedia: any; moveBy: any; moveTo: any; msWriteProfilerMark: any; open: any; postMessage: any; prompt: any; releaseEvents: any; requestAnimationFrame: any; resizeBy: any; resizeTo: any; scroll: any; scrollBy: any; scrollTo: any; stop: any; webkitCancelAnimationFrame: any; webkitConvertPointFromNodeToPage: any; webkitConvertPointFromPageToNode: any; webkitRequestAnimationFrame: any; addEventListener: any; removeEventListener: any; dispatchEvent: any; clearInterval: any; clearTimeout: any; setInterval: any; setTimeout: any; clearImmediate: any; setImmediate: any; readonly sessionStorage: any; readonly localStorage: any; readonly console: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly indexedDB: any; atob: any; btoa: any; fetch: any; }; designMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; dir: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly doctype: { readonly entities: any; readonly internalSubset: any; readonly name: any; readonly notations: any; readonly publicId: any; readonly systemId: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; remove: any; }; readonly documentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; domain: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly embeds: { item: any; namedItem: any; readonly length: any; }; fgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly forms: { item: any; namedItem: any; readonly length: any; }; readonly fullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly fullscreenEnabled: { valueOf: any; }; readonly head: { profile: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly hidden: { valueOf: any; }; readonly images: { item: any; namedItem: any; readonly length: any; }; readonly implementation: { createDocument: any; createDocumentType: any; createHTMLDocument: any; hasFeature: any; }; readonly inputEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly lastModified: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; linkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly links: { item: any; namedItem: any; readonly length: any; }; location: { hash: any; host: any; hostname: any; href: any; readonly origin: any; pathname: any; port: any; protocol: any; search: any; assign: any; reload: any; replace: any; toString: any; }; msCSSOMElementFloatMetrics: { valueOf: any; }; msCapsLockWarningOff: { valueOf: any; }; onabort: {}; onactivate: {}; onbeforeactivate: {}; onbeforedeactivate: {}; onblur: {}; oncanplay: {}; oncanplaythrough: {}; onchange: {}; onclick: {}; oncontextmenu: {}; ondblclick: {}; ondeactivate: {}; ondrag: {}; ondragend: {}; ondragenter: {}; ondragleave: {}; ondragover: {}; ondragstart: {}; ondrop: {}; ondurationchange: {}; onemptied: {}; onended: {}; onerror: {}; onfocus: {}; onfullscreenchange: {}; onfullscreenerror: {}; oninput: {}; oninvalid: {}; onkeydown: {}; onkeypress: {}; onkeyup: {}; onload: {}; onloadeddata: {}; onloadedmetadata: {}; onloadstart: {}; onmousedown: {}; onmousemove: {}; onmouseout: {}; onmouseover: {}; onmouseup: {}; onmousewheel: {}; onmscontentzoom: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsinertiastart: {}; onmsmanipulationstatechanged: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; onmssitemodejumplistitemremoved: {}; onmsthumbnailclick: {}; onpause: {}; onplay: {}; onplaying: {}; onpointerlockchange: {}; onpointerlockerror: {}; onprogress: {}; onratechange: {}; onreadystatechange: {}; onreset: {}; onscroll: {}; onseeked: {}; onseeking: {}; onselect: {}; onselectionchange: {}; onselectstart: {}; onstalled: {}; onstop: {}; onsubmit: {}; onsuspend: {}; ontimeupdate: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onvisibilitychange: {}; onvolumechange: {}; onwaiting: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; readonly plugins: { item: any; namedItem: any; readonly length: any; }; readonly pointerLockElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly readyState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly referrer: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly rootElement: { contentScriptType: any; contentStyleType: any; currentScale: any; readonly currentTranslate: any; readonly height: any; onabort: any; onerror: any; onresize: any; onscroll: any; onunload: any; onzoom: any; readonly pixelUnitToMillimeterX: any; readonly pixelUnitToMillimeterY: any; readonly screenPixelToMillimeterX: any; readonly screenPixelToMillimeterY: any; readonly viewport: any; readonly width: any; readonly x: any; readonly y: any; checkEnclosure: any; checkIntersection: any; createSVGAngle: any; createSVGLength: any; createSVGMatrix: any; createSVGNumber: any; createSVGPoint: any; createSVGRect: any; createSVGTransform: any; createSVGTransformFromMatrix: any; deselectAll: any; forceRedraw: any; getComputedStyle: any; getCurrentTime: any; getElementById: any; getEnclosureList: any; getIntersectionList: any; pauseAnimations: any; setCurrentTime: any; suspendRedraw: any; unpauseAnimations: any; unsuspendRedraw: any; unsuspendRedrawAll: any; addEventListener: any; removeEventListener: any; readonly farthestViewportElement: any; readonly nearestViewportElement: any; readonly transform: any; getBBox: any; getCTM: any; getScreenCTM: any; getTransformToElement: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly requiredExtensions: any; readonly requiredFeatures: any; readonly systemLanguage: any; hasExtension: any; createEvent: any; readonly preserveAspectRatio: any; readonly viewBox: any; readonly zoomAndPan: any; }; readonly scripts: { item: any; namedItem: any; readonly length: any; }; readonly scrollingElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly styleSheets: { readonly length: any; item: any; }; title: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly visibilityState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; vlinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly webkitCurrentFullScreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenEnabled: { valueOf: any; }; readonly webkitIsFullScreen: { valueOf: any; }; readonly xmlEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; xmlStandalone: { valueOf: any; }; xmlVersion: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; adoptNode: {}; captureEvents: {}; caretRangeFromPoint: {}; clear: {}; close: {}; createAttribute: {}; createAttributeNS: {}; createCDATASection: {}; createComment: {}; createDocumentFragment: {}; createElement: {}; createElementNS: {}; createExpression: {}; createNSResolver: {}; createNodeIterator: {}; createProcessingInstruction: {}; createRange: {}; createTextNode: {}; createTouch: {}; createTouchList: {}; createTreeWalker: {}; elementFromPoint: {}; evaluate: {}; execCommand: {}; execCommandShowHelp: {}; exitFullscreen: {}; exitPointerLock: {}; focus: {}; getElementById: {}; getElementsByClassName: {}; getElementsByName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; getSelection: {}; hasFocus: {}; importNode: {}; msElementsFromPoint: {}; msElementsFromRect: {}; open: {}; queryCommandEnabled: {}; queryCommandIndeterm: {}; queryCommandState: {}; queryCommandSupported: {}; queryCommandText: {}; queryCommandValue: {}; releaseEvents: {}; webkitCancelFullScreen: {}; webkitExitFullscreen: {}; write: {}; writeln: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; createEvent: {}; } ->out2 : { msCaching: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onreadystatechange: {}; readonly readyState: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly response: {}; readonly responseText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; responseType: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseURL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseXML: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly status: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly statusText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; timeout: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly upload: { addEventListener: any; removeEventListener: any; dispatchEvent: any; onabort: any; onerror: any; onload: any; onloadend: any; onloadstart: any; onprogress: any; ontimeout: any; }; withCredentials: { valueOf: any; }; abort: {}; getAllResponseHeaders: {}; getResponseHeader: {}; msCachingEnabled: {}; open: {}; overrideMimeType: {}; send: {}; setRequestHeader: {}; readonly DONE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly HEADERS_RECEIVED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly LOADING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly OPENED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly UNSENT: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; addEventListener: {}; removeEventListener: {}; dispatchEvent: {}; onabort: {}; onerror: {}; onload: {}; onloadend: {}; onloadstart: {}; onprogress: {}; ontimeout: {}; } ->responseXML : { readonly URL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly URLUnencoded: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly activeElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; alinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly all: { readonly length: any; item: any; namedItem: any; }; readonly anchors: { item: any; namedItem: any; readonly length: any; }; readonly applets: { item: any; namedItem: any; readonly length: any; }; bgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; body: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly characterSet: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; charset: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly compatMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; cookie: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly currentScript: { async: any; charset: any; crossOrigin: any; defer: any; event: any; htmlFor: any; integrity: any; noModule: any; src: any; text: any; type: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; } | { type: any; addEventListener: any; removeEventListener: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly href: any; }; readonly defaultView: { Blob: any; URL: any; URLSearchParams: any; readonly applicationCache: any; readonly caches: any; readonly clientInformation: any; readonly closed: any; readonly crypto: any; customElements: any; defaultStatus: any; readonly devicePixelRatio: any; readonly doNotTrack: any; readonly document: any; event: any; readonly external: any; readonly frameElement: any; readonly frames: any; readonly history: any; readonly innerHeight: any; readonly innerWidth: any; readonly isSecureContext: any; readonly length: any; location: any; readonly locationbar: any; readonly menubar: any; readonly msContentScript: any; readonly msCredentials: any; name: any; readonly navigator: any; offscreenBuffering: any; onabort: any; onbeforeunload: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncompassneedscalibration: any; oncontextmenu: any; ondblclick: any; ondevicelight: any; ondevicemotion: any; ondeviceorientation: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onhashchange: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmessage: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onoffline: any; ononline: any; onorientationchange: any; onpagehide: any; onpageshow: any; onpause: any; onplay: any; onplaying: any; onpopstate: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onresize: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onstalled: any; onstorage: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: any; onvolumechange: any; onvrdisplayactivate: any; onvrdisplayblur: any; onvrdisplayconnect: any; onvrdisplaydeactivate: any; onvrdisplaydisconnect: any; onvrdisplayfocus: any; onvrdisplaypointerrestricted: any; onvrdisplaypointerunrestricted: any; onvrdisplaypresentchange: any; onwaiting: any; readonly opener: any; readonly orientation: any; readonly outerHeight: any; readonly outerWidth: any; readonly pageXOffset: any; readonly pageYOffset: any; readonly parent: any; readonly performance: any; readonly personalbar: any; readonly screen: any; readonly screenLeft: any; readonly screenTop: any; readonly screenX: any; readonly screenY: any; readonly scrollX: any; readonly scrollY: any; readonly scrollbars: any; readonly self: any; readonly speechSynthesis: any; status: any; readonly statusbar: any; readonly styleMedia: any; readonly toolbar: any; readonly top: any; readonly window: any; alert: any; blur: any; cancelAnimationFrame: any; captureEvents: any; close: any; confirm: any; createImageBitmap: any; departFocus: any; focus: any; getComputedStyle: any; getMatchedCSSRules: any; getSelection: any; matchMedia: any; moveBy: any; moveTo: any; msWriteProfilerMark: any; open: any; postMessage: any; prompt: any; releaseEvents: any; requestAnimationFrame: any; resizeBy: any; resizeTo: any; scroll: any; scrollBy: any; scrollTo: any; stop: any; webkitCancelAnimationFrame: any; webkitConvertPointFromNodeToPage: any; webkitConvertPointFromPageToNode: any; webkitRequestAnimationFrame: any; addEventListener: any; removeEventListener: any; dispatchEvent: any; clearInterval: any; clearTimeout: any; setInterval: any; setTimeout: any; clearImmediate: any; setImmediate: any; readonly sessionStorage: any; readonly localStorage: any; readonly console: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly indexedDB: any; atob: any; btoa: any; fetch: any; }; designMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; dir: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly doctype: { readonly entities: any; readonly internalSubset: any; readonly name: any; readonly notations: any; readonly publicId: any; readonly systemId: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; remove: any; }; readonly documentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; domain: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly embeds: { item: any; namedItem: any; readonly length: any; }; fgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly forms: { item: any; namedItem: any; readonly length: any; }; readonly fullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly fullscreenEnabled: { valueOf: any; }; readonly head: { profile: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly hidden: { valueOf: any; }; readonly images: { item: any; namedItem: any; readonly length: any; }; readonly implementation: { createDocument: any; createDocumentType: any; createHTMLDocument: any; hasFeature: any; }; readonly inputEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly lastModified: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; linkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly links: { item: any; namedItem: any; readonly length: any; }; location: { hash: any; host: any; hostname: any; href: any; readonly origin: any; pathname: any; port: any; protocol: any; search: any; assign: any; reload: any; replace: any; toString: any; }; msCSSOMElementFloatMetrics: { valueOf: any; }; msCapsLockWarningOff: { valueOf: any; }; onabort: {}; onactivate: {}; onbeforeactivate: {}; onbeforedeactivate: {}; onblur: {}; oncanplay: {}; oncanplaythrough: {}; onchange: {}; onclick: {}; oncontextmenu: {}; ondblclick: {}; ondeactivate: {}; ondrag: {}; ondragend: {}; ondragenter: {}; ondragleave: {}; ondragover: {}; ondragstart: {}; ondrop: {}; ondurationchange: {}; onemptied: {}; onended: {}; onerror: {}; onfocus: {}; onfullscreenchange: {}; onfullscreenerror: {}; oninput: {}; oninvalid: {}; onkeydown: {}; onkeypress: {}; onkeyup: {}; onload: {}; onloadeddata: {}; onloadedmetadata: {}; onloadstart: {}; onmousedown: {}; onmousemove: {}; onmouseout: {}; onmouseover: {}; onmouseup: {}; onmousewheel: {}; onmscontentzoom: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsinertiastart: {}; onmsmanipulationstatechanged: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; onmssitemodejumplistitemremoved: {}; onmsthumbnailclick: {}; onpause: {}; onplay: {}; onplaying: {}; onpointerlockchange: {}; onpointerlockerror: {}; onprogress: {}; onratechange: {}; onreadystatechange: {}; onreset: {}; onscroll: {}; onseeked: {}; onseeking: {}; onselect: {}; onselectionchange: {}; onselectstart: {}; onstalled: {}; onstop: {}; onsubmit: {}; onsuspend: {}; ontimeupdate: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onvisibilitychange: {}; onvolumechange: {}; onwaiting: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; readonly plugins: { item: any; namedItem: any; readonly length: any; }; readonly pointerLockElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly readyState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly referrer: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly rootElement: { contentScriptType: any; contentStyleType: any; currentScale: any; readonly currentTranslate: any; readonly height: any; onabort: any; onerror: any; onresize: any; onscroll: any; onunload: any; onzoom: any; readonly pixelUnitToMillimeterX: any; readonly pixelUnitToMillimeterY: any; readonly screenPixelToMillimeterX: any; readonly screenPixelToMillimeterY: any; readonly viewport: any; readonly width: any; readonly x: any; readonly y: any; checkEnclosure: any; checkIntersection: any; createSVGAngle: any; createSVGLength: any; createSVGMatrix: any; createSVGNumber: any; createSVGPoint: any; createSVGRect: any; createSVGTransform: any; createSVGTransformFromMatrix: any; deselectAll: any; forceRedraw: any; getComputedStyle: any; getCurrentTime: any; getElementById: any; getEnclosureList: any; getIntersectionList: any; pauseAnimations: any; setCurrentTime: any; suspendRedraw: any; unpauseAnimations: any; unsuspendRedraw: any; unsuspendRedrawAll: any; addEventListener: any; removeEventListener: any; readonly farthestViewportElement: any; readonly nearestViewportElement: any; readonly transform: any; getBBox: any; getCTM: any; getScreenCTM: any; getTransformToElement: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly requiredExtensions: any; readonly requiredFeatures: any; readonly systemLanguage: any; hasExtension: any; createEvent: any; readonly preserveAspectRatio: any; readonly viewBox: any; readonly zoomAndPan: any; }; readonly scripts: { item: any; namedItem: any; readonly length: any; }; readonly scrollingElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly styleSheets: { readonly length: any; item: any; }; title: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly visibilityState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; vlinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly webkitCurrentFullScreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenEnabled: { valueOf: any; }; readonly webkitIsFullScreen: { valueOf: any; }; readonly xmlEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; xmlStandalone: { valueOf: any; }; xmlVersion: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; adoptNode: {}; captureEvents: {}; caretRangeFromPoint: {}; clear: {}; close: {}; createAttribute: {}; createAttributeNS: {}; createCDATASection: {}; createComment: {}; createDocumentFragment: {}; createElement: {}; createElementNS: {}; createExpression: {}; createNSResolver: {}; createNodeIterator: {}; createProcessingInstruction: {}; createRange: {}; createTextNode: {}; createTouch: {}; createTouchList: {}; createTreeWalker: {}; elementFromPoint: {}; evaluate: {}; execCommand: {}; execCommandShowHelp: {}; exitFullscreen: {}; exitPointerLock: {}; focus: {}; getElementById: {}; getElementsByClassName: {}; getElementsByName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; getSelection: {}; hasFocus: {}; importNode: {}; msElementsFromPoint: {}; msElementsFromRect: {}; open: {}; queryCommandEnabled: {}; queryCommandIndeterm: {}; queryCommandState: {}; queryCommandSupported: {}; queryCommandText: {}; queryCommandValue: {}; releaseEvents: {}; webkitCancelFullScreen: {}; webkitExitFullscreen: {}; write: {}; writeln: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; createEvent: {}; } ->activeElement : { readonly assignedSlot: { name: any; assignedNodes: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly attributes: { readonly length: any; getNamedItem: any; getNamedItemNS: any; item: any; removeNamedItem: any; removeNamedItemNS: any; setNamedItem: any; setNamedItemNS: any; }; readonly classList: { readonly length: any; add: any; contains: any; item: any; remove: any; toString: any; toggle: any; }; className: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly clientHeight: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientLeft: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientTop: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientWidth: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; id: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; innerHTML: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; msContentZoomFactor: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly msRegionOverflow: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onariarequest: {}; oncommand: {}; ongotpointercapture: {}; onlostpointercapture: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsgotpointercapture: {}; onmsinertiastart: {}; onmslostpointercapture: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; outerHTML: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly prefix: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly scrollHeight: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; scrollLeft: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; scrollTop: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly scrollWidth: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly shadowRoot: { readonly host: any; innerHTML: any; readonly activeElement: any; readonly styleSheets: any; elementFromPoint: any; elementsFromPoint: any; getSelection: any; getElementById: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; }; slot: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly tagName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; attachShadow: {}; closest: {}; getAttribute: {}; getAttributeNS: {}; getAttributeNode: {}; getAttributeNodeNS: {}; getBoundingClientRect: {}; getClientRects: {}; getElementsByClassName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; hasAttribute: {}; hasAttributeNS: {}; hasAttributes: {}; insertAdjacentElement: {}; insertAdjacentHTML: {}; insertAdjacentText: {}; matches: {}; msGetRegionContent: {}; msGetUntransformedBounds: {}; msMatchesSelector: {}; msReleasePointerCapture: {}; msSetPointerCapture: {}; msZoomTo: {}; releasePointerCapture: {}; removeAttribute: {}; removeAttributeNS: {}; removeAttributeNode: {}; requestFullscreen: {}; requestPointerLock: {}; scroll: {}; scrollBy: {}; scrollIntoView: {}; scrollTo: {}; setAttribute: {}; setAttributeNS: {}; setAttributeNode: {}; setAttributeNodeNS: {}; setPointerCapture: {}; webkitMatchesSelector: {}; webkitRequestFullScreen: {}; webkitRequestFullscreen: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly nextElementSibling: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly previousElementSibling: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; remove: {}; } +>out2.responseXML.activeElement : { readonly assignedSlot: { name: any; assignedNodes: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly attributes: { readonly length: any; getNamedItem: any; getNamedItemNS: any; item: any; removeNamedItem: any; removeNamedItemNS: any; setNamedItem: any; setNamedItemNS: any; }; readonly classList: { readonly length: any; add: any; contains: any; item: any; remove: any; replace: any; toString: any; toggle: any; }; className: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly clientHeight: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientLeft: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientTop: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientWidth: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; id: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; innerHTML: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; msContentZoomFactor: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly msRegionOverflow: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onariarequest: {}; oncommand: {}; ongotpointercapture: {}; onlostpointercapture: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsgotpointercapture: {}; onmsinertiastart: {}; onmslostpointercapture: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; outerHTML: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly prefix: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly scrollHeight: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; scrollLeft: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; scrollTop: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly scrollWidth: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly shadowRoot: { readonly host: any; innerHTML: any; readonly activeElement: any; readonly styleSheets: any; elementFromPoint: any; elementsFromPoint: any; getSelection: any; getElementById: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; }; slot: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly tagName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; attachShadow: {}; closest: {}; getAttribute: {}; getAttributeNS: {}; getAttributeNode: {}; getAttributeNodeNS: {}; getBoundingClientRect: {}; getClientRects: {}; getElementsByClassName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; hasAttribute: {}; hasAttributeNS: {}; hasAttributes: {}; insertAdjacentElement: {}; insertAdjacentHTML: {}; insertAdjacentText: {}; matches: {}; msGetRegionContent: {}; msGetUntransformedBounds: {}; msMatchesSelector: {}; msReleasePointerCapture: {}; msSetPointerCapture: {}; msZoomTo: {}; releasePointerCapture: {}; removeAttribute: {}; removeAttributeNS: {}; removeAttributeNode: {}; requestFullscreen: {}; requestPointerLock: {}; scroll: {}; scrollBy: {}; scrollIntoView: {}; scrollTo: {}; setAttribute: {}; setAttributeNS: {}; setAttributeNode: {}; setAttributeNodeNS: {}; setPointerCapture: {}; webkitMatchesSelector: {}; webkitRequestFullScreen: {}; webkitRequestFullscreen: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly nextElementSibling: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly previousElementSibling: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; remove: {}; } +>out2.responseXML : { readonly URL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly URLUnencoded: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly activeElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; alinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly all: { readonly length: any; item: any; namedItem: any; }; readonly anchors: { item: any; namedItem: any; readonly length: any; }; readonly applets: { item: any; namedItem: any; readonly length: any; }; bgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; body: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly characterSet: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; charset: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly compatMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; cookie: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly currentScript: { async: any; charset: any; crossOrigin: any; defer: any; event: any; htmlFor: any; integrity: any; noModule: any; src: any; text: any; type: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; } | { type: any; addEventListener: any; removeEventListener: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly href: any; }; readonly defaultView: { Blob: any; URL: any; URLSearchParams: any; readonly applicationCache: any; readonly caches: any; readonly clientInformation: any; readonly closed: any; readonly crypto: any; customElements: any; defaultStatus: any; readonly devicePixelRatio: any; readonly doNotTrack: any; readonly document: any; event: any; readonly external: any; readonly frameElement: any; readonly frames: any; readonly history: any; readonly innerHeight: any; readonly innerWidth: any; readonly isSecureContext: any; readonly length: any; location: any; readonly locationbar: any; readonly menubar: any; readonly msContentScript: any; readonly msCredentials: any; name: any; readonly navigator: any; offscreenBuffering: any; onabort: any; onbeforeunload: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncompassneedscalibration: any; oncontextmenu: any; ondblclick: any; ondevicelight: any; ondevicemotion: any; ondeviceorientation: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onhashchange: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmessage: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onoffline: any; ononline: any; onorientationchange: any; onpagehide: any; onpageshow: any; onpause: any; onplay: any; onplaying: any; onpopstate: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onresize: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onstalled: any; onstorage: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: any; onvolumechange: any; onvrdisplayactivate: any; onvrdisplayblur: any; onvrdisplayconnect: any; onvrdisplaydeactivate: any; onvrdisplaydisconnect: any; onvrdisplayfocus: any; onvrdisplaypointerrestricted: any; onvrdisplaypointerunrestricted: any; onvrdisplaypresentchange: any; onwaiting: any; readonly opener: any; readonly orientation: any; readonly outerHeight: any; readonly outerWidth: any; readonly pageXOffset: any; readonly pageYOffset: any; readonly parent: any; readonly performance: any; readonly personalbar: any; readonly screen: any; readonly screenLeft: any; readonly screenTop: any; readonly screenX: any; readonly screenY: any; readonly scrollX: any; readonly scrollY: any; readonly scrollbars: any; readonly self: any; readonly speechSynthesis: any; status: any; readonly statusbar: any; readonly styleMedia: any; readonly toolbar: any; readonly top: any; readonly window: any; alert: any; blur: any; cancelAnimationFrame: any; captureEvents: any; close: any; confirm: any; createImageBitmap: any; departFocus: any; focus: any; getComputedStyle: any; getMatchedCSSRules: any; getSelection: any; matchMedia: any; moveBy: any; moveTo: any; msWriteProfilerMark: any; open: any; postMessage: any; print: any; prompt: any; releaseEvents: any; requestAnimationFrame: any; resizeBy: any; resizeTo: any; scroll: any; scrollBy: any; scrollTo: any; stop: any; webkitCancelAnimationFrame: any; webkitConvertPointFromNodeToPage: any; webkitConvertPointFromPageToNode: any; webkitRequestAnimationFrame: any; addEventListener: any; removeEventListener: any; dispatchEvent: any; clearInterval: any; clearTimeout: any; setInterval: any; setTimeout: any; clearImmediate: any; setImmediate: any; readonly sessionStorage: any; readonly localStorage: any; readonly console: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly indexedDB: any; atob: any; btoa: any; fetch: any; }; designMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; dir: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly doctype: { readonly entities: any; readonly internalSubset: any; readonly name: any; readonly notations: any; readonly publicId: any; readonly systemId: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; remove: any; }; readonly documentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; domain: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly embeds: { item: any; namedItem: any; readonly length: any; }; fgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly forms: { item: any; namedItem: any; readonly length: any; }; readonly fullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly fullscreenEnabled: { valueOf: any; }; readonly head: { profile: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly hidden: { valueOf: any; }; readonly images: { item: any; namedItem: any; readonly length: any; }; readonly implementation: { createDocument: any; createDocumentType: any; createHTMLDocument: any; hasFeature: any; }; readonly inputEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly lastModified: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; linkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly links: { item: any; namedItem: any; readonly length: any; }; location: { hash: any; host: any; hostname: any; href: any; readonly origin: any; pathname: any; port: any; protocol: any; search: any; assign: any; reload: any; replace: any; toString: any; }; msCSSOMElementFloatMetrics: { valueOf: any; }; msCapsLockWarningOff: { valueOf: any; }; onabort: {}; onactivate: {}; onbeforeactivate: {}; onbeforedeactivate: {}; onblur: {}; oncanplay: {}; oncanplaythrough: {}; onchange: {}; onclick: {}; oncontextmenu: {}; ondblclick: {}; ondeactivate: {}; ondrag: {}; ondragend: {}; ondragenter: {}; ondragleave: {}; ondragover: {}; ondragstart: {}; ondrop: {}; ondurationchange: {}; onemptied: {}; onended: {}; onerror: {}; onfocus: {}; onfullscreenchange: {}; onfullscreenerror: {}; oninput: {}; oninvalid: {}; onkeydown: {}; onkeypress: {}; onkeyup: {}; onload: {}; onloadeddata: {}; onloadedmetadata: {}; onloadstart: {}; onmousedown: {}; onmousemove: {}; onmouseout: {}; onmouseover: {}; onmouseup: {}; onmousewheel: {}; onmscontentzoom: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsinertiastart: {}; onmsmanipulationstatechanged: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; onmssitemodejumplistitemremoved: {}; onmsthumbnailclick: {}; onpause: {}; onplay: {}; onplaying: {}; onpointerlockchange: {}; onpointerlockerror: {}; onprogress: {}; onratechange: {}; onreadystatechange: {}; onreset: {}; onscroll: {}; onseeked: {}; onseeking: {}; onselect: {}; onselectionchange: {}; onselectstart: {}; onstalled: {}; onstop: {}; onsubmit: {}; onsuspend: {}; ontimeupdate: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onvisibilitychange: {}; onvolumechange: {}; onwaiting: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; readonly plugins: { item: any; namedItem: any; readonly length: any; }; readonly pointerLockElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly readyState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly referrer: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly rootElement: { contentScriptType: any; contentStyleType: any; currentScale: any; readonly currentTranslate: any; readonly height: any; onabort: any; onerror: any; onresize: any; onscroll: any; onunload: any; onzoom: any; readonly pixelUnitToMillimeterX: any; readonly pixelUnitToMillimeterY: any; readonly screenPixelToMillimeterX: any; readonly screenPixelToMillimeterY: any; readonly viewport: any; readonly width: any; readonly x: any; readonly y: any; checkEnclosure: any; checkIntersection: any; createSVGAngle: any; createSVGLength: any; createSVGMatrix: any; createSVGNumber: any; createSVGPoint: any; createSVGRect: any; createSVGTransform: any; createSVGTransformFromMatrix: any; deselectAll: any; forceRedraw: any; getComputedStyle: any; getCurrentTime: any; getElementById: any; getEnclosureList: any; getIntersectionList: any; pauseAnimations: any; setCurrentTime: any; suspendRedraw: any; unpauseAnimations: any; unsuspendRedraw: any; unsuspendRedrawAll: any; addEventListener: any; removeEventListener: any; readonly farthestViewportElement: any; readonly nearestViewportElement: any; readonly transform: any; getBBox: any; getCTM: any; getScreenCTM: any; getTransformToElement: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly requiredExtensions: any; readonly requiredFeatures: any; readonly systemLanguage: any; hasExtension: any; createEvent: any; readonly preserveAspectRatio: any; readonly viewBox: any; readonly zoomAndPan: any; }; readonly scripts: { item: any; namedItem: any; readonly length: any; }; readonly scrollingElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly styleSheets: { readonly length: any; item: any; }; title: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly visibilityState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; vlinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly webkitCurrentFullScreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenEnabled: { valueOf: any; }; readonly webkitIsFullScreen: { valueOf: any; }; readonly xmlEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; xmlStandalone: { valueOf: any; }; xmlVersion: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; adoptNode: {}; captureEvents: {}; caretRangeFromPoint: {}; clear: {}; close: {}; createAttribute: {}; createAttributeNS: {}; createCDATASection: {}; createComment: {}; createDocumentFragment: {}; createElement: {}; createElementNS: {}; createExpression: {}; createNSResolver: {}; createNodeIterator: {}; createProcessingInstruction: {}; createRange: {}; createTextNode: {}; createTouch: {}; createTouchList: {}; createTreeWalker: {}; elementFromPoint: {}; elementsFromPoint: {}; evaluate: {}; execCommand: {}; execCommandShowHelp: {}; exitFullscreen: {}; exitPointerLock: {}; focus: {}; getElementById: {}; getElementsByClassName: {}; getElementsByName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; getSelection: {}; hasFocus: {}; importNode: {}; msElementsFromPoint: {}; msElementsFromRect: {}; open: {}; queryCommandEnabled: {}; queryCommandIndeterm: {}; queryCommandState: {}; queryCommandSupported: {}; queryCommandText: {}; queryCommandValue: {}; releaseEvents: {}; webkitCancelFullScreen: {}; webkitExitFullscreen: {}; write: {}; writeln: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; createEvent: {}; } +>out2 : { msCaching: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onreadystatechange: {}; readonly readyState: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly response: {}; readonly responseText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; responseType: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseURL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly responseXML: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly status: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly statusText: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; timeout: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly upload: { addEventListener: any; removeEventListener: any; dispatchEvent: any; onabort: any; onerror: any; onload: any; onloadend: any; onloadstart: any; onprogress: any; ontimeout: any; }; withCredentials: { valueOf: any; }; abort: {}; getAllResponseHeaders: {}; getResponseHeader: {}; msCachingEnabled: {}; open: {}; overrideMimeType: {}; send: {}; setRequestHeader: {}; readonly DONE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly HEADERS_RECEIVED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly LOADING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly OPENED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly UNSENT: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; addEventListener: {}; removeEventListener: {}; dispatchEvent: {}; onabort: {}; onerror: {}; onload: {}; onloadend: {}; onloadstart: {}; onprogress: {}; ontimeout: {}; } +>responseXML : { readonly URL: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly URLUnencoded: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly activeElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; alinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly all: { readonly length: any; item: any; namedItem: any; }; readonly anchors: { item: any; namedItem: any; readonly length: any; }; readonly applets: { item: any; namedItem: any; readonly length: any; }; bgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; body: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly characterSet: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; charset: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly compatMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; cookie: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly currentScript: { async: any; charset: any; crossOrigin: any; defer: any; event: any; htmlFor: any; integrity: any; noModule: any; src: any; text: any; type: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; } | { type: any; addEventListener: any; removeEventListener: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly href: any; }; readonly defaultView: { Blob: any; URL: any; URLSearchParams: any; readonly applicationCache: any; readonly caches: any; readonly clientInformation: any; readonly closed: any; readonly crypto: any; customElements: any; defaultStatus: any; readonly devicePixelRatio: any; readonly doNotTrack: any; readonly document: any; event: any; readonly external: any; readonly frameElement: any; readonly frames: any; readonly history: any; readonly innerHeight: any; readonly innerWidth: any; readonly isSecureContext: any; readonly length: any; location: any; readonly locationbar: any; readonly menubar: any; readonly msContentScript: any; readonly msCredentials: any; name: any; readonly navigator: any; offscreenBuffering: any; onabort: any; onbeforeunload: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncompassneedscalibration: any; oncontextmenu: any; ondblclick: any; ondevicelight: any; ondevicemotion: any; ondeviceorientation: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onhashchange: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmessage: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onoffline: any; ononline: any; onorientationchange: any; onpagehide: any; onpageshow: any; onpause: any; onplay: any; onplaying: any; onpopstate: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onresize: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onstalled: any; onstorage: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: any; onvolumechange: any; onvrdisplayactivate: any; onvrdisplayblur: any; onvrdisplayconnect: any; onvrdisplaydeactivate: any; onvrdisplaydisconnect: any; onvrdisplayfocus: any; onvrdisplaypointerrestricted: any; onvrdisplaypointerunrestricted: any; onvrdisplaypresentchange: any; onwaiting: any; readonly opener: any; readonly orientation: any; readonly outerHeight: any; readonly outerWidth: any; readonly pageXOffset: any; readonly pageYOffset: any; readonly parent: any; readonly performance: any; readonly personalbar: any; readonly screen: any; readonly screenLeft: any; readonly screenTop: any; readonly screenX: any; readonly screenY: any; readonly scrollX: any; readonly scrollY: any; readonly scrollbars: any; readonly self: any; readonly speechSynthesis: any; status: any; readonly statusbar: any; readonly styleMedia: any; readonly toolbar: any; readonly top: any; readonly window: any; alert: any; blur: any; cancelAnimationFrame: any; captureEvents: any; close: any; confirm: any; createImageBitmap: any; departFocus: any; focus: any; getComputedStyle: any; getMatchedCSSRules: any; getSelection: any; matchMedia: any; moveBy: any; moveTo: any; msWriteProfilerMark: any; open: any; postMessage: any; print: any; prompt: any; releaseEvents: any; requestAnimationFrame: any; resizeBy: any; resizeTo: any; scroll: any; scrollBy: any; scrollTo: any; stop: any; webkitCancelAnimationFrame: any; webkitConvertPointFromNodeToPage: any; webkitConvertPointFromPageToNode: any; webkitRequestAnimationFrame: any; addEventListener: any; removeEventListener: any; dispatchEvent: any; clearInterval: any; clearTimeout: any; setInterval: any; setTimeout: any; clearImmediate: any; setImmediate: any; readonly sessionStorage: any; readonly localStorage: any; readonly console: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly indexedDB: any; atob: any; btoa: any; fetch: any; }; designMode: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; dir: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly doctype: { readonly entities: any; readonly internalSubset: any; readonly name: any; readonly notations: any; readonly publicId: any; readonly systemId: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; remove: any; }; readonly documentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; domain: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly embeds: { item: any; namedItem: any; readonly length: any; }; fgColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly forms: { item: any; namedItem: any; readonly length: any; }; readonly fullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly fullscreenEnabled: { valueOf: any; }; readonly head: { profile: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly hidden: { valueOf: any; }; readonly images: { item: any; namedItem: any; readonly length: any; }; readonly implementation: { createDocument: any; createDocumentType: any; createHTMLDocument: any; hasFeature: any; }; readonly inputEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly lastModified: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; linkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly links: { item: any; namedItem: any; readonly length: any; }; location: { hash: any; host: any; hostname: any; href: any; readonly origin: any; pathname: any; port: any; protocol: any; search: any; assign: any; reload: any; replace: any; toString: any; }; msCSSOMElementFloatMetrics: { valueOf: any; }; msCapsLockWarningOff: { valueOf: any; }; onabort: {}; onactivate: {}; onbeforeactivate: {}; onbeforedeactivate: {}; onblur: {}; oncanplay: {}; oncanplaythrough: {}; onchange: {}; onclick: {}; oncontextmenu: {}; ondblclick: {}; ondeactivate: {}; ondrag: {}; ondragend: {}; ondragenter: {}; ondragleave: {}; ondragover: {}; ondragstart: {}; ondrop: {}; ondurationchange: {}; onemptied: {}; onended: {}; onerror: {}; onfocus: {}; onfullscreenchange: {}; onfullscreenerror: {}; oninput: {}; oninvalid: {}; onkeydown: {}; onkeypress: {}; onkeyup: {}; onload: {}; onloadeddata: {}; onloadedmetadata: {}; onloadstart: {}; onmousedown: {}; onmousemove: {}; onmouseout: {}; onmouseover: {}; onmouseup: {}; onmousewheel: {}; onmscontentzoom: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsinertiastart: {}; onmsmanipulationstatechanged: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; onmssitemodejumplistitemremoved: {}; onmsthumbnailclick: {}; onpause: {}; onplay: {}; onplaying: {}; onpointerlockchange: {}; onpointerlockerror: {}; onprogress: {}; onratechange: {}; onreadystatechange: {}; onreset: {}; onscroll: {}; onseeked: {}; onseeking: {}; onselect: {}; onselectionchange: {}; onselectstart: {}; onstalled: {}; onstop: {}; onsubmit: {}; onsuspend: {}; ontimeupdate: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onvisibilitychange: {}; onvolumechange: {}; onwaiting: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; readonly plugins: { item: any; namedItem: any; readonly length: any; }; readonly pointerLockElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly readyState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly referrer: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly rootElement: { contentScriptType: any; contentStyleType: any; currentScale: any; readonly currentTranslate: any; readonly height: any; onabort: any; onerror: any; onresize: any; onscroll: any; onunload: any; onzoom: any; readonly pixelUnitToMillimeterX: any; readonly pixelUnitToMillimeterY: any; readonly screenPixelToMillimeterX: any; readonly screenPixelToMillimeterY: any; readonly viewport: any; readonly width: any; readonly x: any; readonly y: any; checkEnclosure: any; checkIntersection: any; createSVGAngle: any; createSVGLength: any; createSVGMatrix: any; createSVGNumber: any; createSVGPoint: any; createSVGRect: any; createSVGTransform: any; createSVGTransformFromMatrix: any; deselectAll: any; forceRedraw: any; getComputedStyle: any; getCurrentTime: any; getElementById: any; getEnclosureList: any; getIntersectionList: any; pauseAnimations: any; setCurrentTime: any; suspendRedraw: any; unpauseAnimations: any; unsuspendRedraw: any; unsuspendRedrawAll: any; addEventListener: any; removeEventListener: any; readonly farthestViewportElement: any; readonly nearestViewportElement: any; readonly transform: any; getBBox: any; getCTM: any; getScreenCTM: any; getTransformToElement: any; readonly className: any; onclick: any; ondblclick: any; onfocusin: any; onfocusout: any; onload: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; readonly ownerSVGElement: any; readonly viewportElement: any; xmlbase: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; readonly requiredExtensions: any; readonly requiredFeatures: any; readonly systemLanguage: any; hasExtension: any; createEvent: any; readonly preserveAspectRatio: any; readonly viewBox: any; readonly zoomAndPan: any; }; readonly scripts: { item: any; namedItem: any; readonly length: any; }; readonly scrollingElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly styleSheets: { readonly length: any; item: any; }; title: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly visibilityState: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; vlinkColor: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly webkitCurrentFullScreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenElement: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly webkitFullscreenEnabled: { valueOf: any; }; readonly webkitIsFullScreen: { valueOf: any; }; readonly xmlEncoding: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; xmlStandalone: { valueOf: any; }; xmlVersion: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; adoptNode: {}; captureEvents: {}; caretRangeFromPoint: {}; clear: {}; close: {}; createAttribute: {}; createAttributeNS: {}; createCDATASection: {}; createComment: {}; createDocumentFragment: {}; createElement: {}; createElementNS: {}; createExpression: {}; createNSResolver: {}; createNodeIterator: {}; createProcessingInstruction: {}; createRange: {}; createTextNode: {}; createTouch: {}; createTouchList: {}; createTreeWalker: {}; elementFromPoint: {}; elementsFromPoint: {}; evaluate: {}; execCommand: {}; execCommandShowHelp: {}; exitFullscreen: {}; exitPointerLock: {}; focus: {}; getElementById: {}; getElementsByClassName: {}; getElementsByName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; getSelection: {}; hasFocus: {}; importNode: {}; msElementsFromPoint: {}; msElementsFromRect: {}; open: {}; queryCommandEnabled: {}; queryCommandIndeterm: {}; queryCommandState: {}; queryCommandSupported: {}; queryCommandText: {}; queryCommandValue: {}; releaseEvents: {}; webkitCancelFullScreen: {}; webkitExitFullscreen: {}; write: {}; writeln: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; createEvent: {}; } +>activeElement : { readonly assignedSlot: { name: any; assignedNodes: any; addEventListener: any; removeEventListener: any; accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly attributes: { readonly length: any; getNamedItem: any; getNamedItemNS: any; item: any; removeNamedItem: any; removeNamedItemNS: any; setNamedItem: any; setNamedItemNS: any; }; readonly classList: { readonly length: any; add: any; contains: any; item: any; remove: any; replace: any; toString: any; toggle: any; }; className: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly clientHeight: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientLeft: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientTop: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly clientWidth: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; id: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; innerHTML: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; msContentZoomFactor: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly msRegionOverflow: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; onariarequest: {}; oncommand: {}; ongotpointercapture: {}; onlostpointercapture: {}; onmsgesturechange: {}; onmsgesturedoubletap: {}; onmsgestureend: {}; onmsgesturehold: {}; onmsgesturestart: {}; onmsgesturetap: {}; onmsgotpointercapture: {}; onmsinertiastart: {}; onmslostpointercapture: {}; onmspointercancel: {}; onmspointerdown: {}; onmspointerenter: {}; onmspointerleave: {}; onmspointermove: {}; onmspointerout: {}; onmspointerover: {}; onmspointerup: {}; ontouchcancel: {}; ontouchend: {}; ontouchmove: {}; ontouchstart: {}; onwebkitfullscreenchange: {}; onwebkitfullscreenerror: {}; outerHTML: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly prefix: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly scrollHeight: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; scrollLeft: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; scrollTop: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly scrollWidth: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly shadowRoot: { readonly host: any; innerHTML: any; readonly activeElement: any; readonly styleSheets: any; elementFromPoint: any; elementsFromPoint: any; getSelection: any; getElementById: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; }; slot: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly tagName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; attachShadow: {}; closest: {}; getAttribute: {}; getAttributeNS: {}; getAttributeNode: {}; getAttributeNodeNS: {}; getBoundingClientRect: {}; getClientRects: {}; getElementsByClassName: {}; getElementsByTagName: {}; getElementsByTagNameNS: {}; hasAttribute: {}; hasAttributeNS: {}; hasAttributes: {}; insertAdjacentElement: {}; insertAdjacentHTML: {}; insertAdjacentText: {}; matches: {}; msGetRegionContent: {}; msGetUntransformedBounds: {}; msMatchesSelector: {}; msReleasePointerCapture: {}; msSetPointerCapture: {}; msZoomTo: {}; releasePointerCapture: {}; removeAttribute: {}; removeAttributeNS: {}; removeAttributeNode: {}; requestFullscreen: {}; requestPointerLock: {}; scroll: {}; scrollBy: {}; scrollIntoView: {}; scrollTo: {}; setAttribute: {}; setAttributeNS: {}; setAttributeNode: {}; setAttributeNodeNS: {}; setPointerCapture: {}; webkitMatchesSelector: {}; webkitRequestFullScreen: {}; webkitRequestFullscreen: {}; addEventListener: {}; removeEventListener: {}; readonly baseURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly childNodes: { length: any; item: any; }; readonly firstChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly lastChild: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly localName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly namespaceURI: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nextSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly nodeName: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly nodeType: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; nodeValue: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; readonly ownerDocument: { readonly URL: any; readonly URLUnencoded: any; readonly activeElement: any; alinkColor: any; readonly all: any; readonly anchors: any; readonly applets: any; bgColor: any; body: any; readonly characterSet: any; charset: any; readonly compatMode: any; cookie: any; readonly currentScript: any; readonly defaultView: any; designMode: any; dir: any; readonly doctype: any; readonly documentElement: any; domain: any; readonly embeds: any; fgColor: any; readonly forms: any; readonly fullscreenElement: any; readonly fullscreenEnabled: any; readonly head: any; readonly hidden: any; readonly images: any; readonly implementation: any; readonly inputEncoding: any; readonly lastModified: any; linkColor: any; readonly links: any; location: any; msCSSOMElementFloatMetrics: any; msCapsLockWarningOff: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforedeactivate: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; onfullscreenchange: any; onfullscreenerror: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsinertiastart: any; onmsmanipulationstatechanged: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; onmssitemodejumplistitemremoved: any; onmsthumbnailclick: any; onpause: any; onplay: any; onplaying: any; onpointerlockchange: any; onpointerlockerror: any; onprogress: any; onratechange: any; onreadystatechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectionchange: any; onselectstart: any; onstalled: any; onstop: any; onsubmit: any; onsuspend: any; ontimeupdate: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onvisibilitychange: any; onvolumechange: any; onwaiting: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; readonly plugins: any; readonly pointerLockElement: any; readonly readyState: any; readonly referrer: any; readonly rootElement: any; readonly scripts: any; readonly scrollingElement: any; readonly styleSheets: any; title: any; readonly visibilityState: any; vlinkColor: any; readonly webkitCurrentFullScreenElement: any; readonly webkitFullscreenElement: any; readonly webkitFullscreenEnabled: any; readonly webkitIsFullScreen: any; readonly xmlEncoding: any; xmlStandalone: any; xmlVersion: any; adoptNode: any; captureEvents: any; caretRangeFromPoint: any; clear: any; close: any; createAttribute: any; createAttributeNS: any; createCDATASection: any; createComment: any; createDocumentFragment: any; createElement: any; createElementNS: any; createExpression: any; createNSResolver: any; createNodeIterator: any; createProcessingInstruction: any; createRange: any; createTextNode: any; createTouch: any; createTouchList: any; createTreeWalker: any; elementFromPoint: any; elementsFromPoint: any; evaluate: any; execCommand: any; execCommandShowHelp: any; exitFullscreen: any; exitPointerLock: any; focus: any; getElementById: any; getElementsByClassName: any; getElementsByName: any; getElementsByTagName: any; getElementsByTagNameNS: any; getSelection: any; hasFocus: any; importNode: any; msElementsFromPoint: any; msElementsFromRect: any; open: any; queryCommandEnabled: any; queryCommandIndeterm: any; queryCommandState: any; queryCommandSupported: any; queryCommandText: any; queryCommandValue: any; releaseEvents: any; webkitCancelFullScreen: any; webkitExitFullscreen: any; write: any; writeln: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly children: any; querySelector: any; querySelectorAll: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; createEvent: any; }; readonly parentElement: { accessKey: any; contentEditable: any; readonly dataset: any; dir: any; draggable: any; hidden: any; hideFocus: any; innerText: any; readonly isContentEditable: any; lang: any; readonly offsetHeight: any; readonly offsetLeft: any; readonly offsetParent: any; readonly offsetTop: any; readonly offsetWidth: any; onabort: any; onactivate: any; onbeforeactivate: any; onbeforecopy: any; onbeforecut: any; onbeforedeactivate: any; onbeforepaste: any; onblur: any; oncanplay: any; oncanplaythrough: any; onchange: any; onclick: any; oncontextmenu: any; oncopy: any; oncuechange: any; oncut: any; ondblclick: any; ondeactivate: any; ondrag: any; ondragend: any; ondragenter: any; ondragleave: any; ondragover: any; ondragstart: any; ondrop: any; ondurationchange: any; onemptied: any; onended: any; onerror: any; onfocus: any; oninput: any; oninvalid: any; onkeydown: any; onkeypress: any; onkeyup: any; onload: any; onloadeddata: any; onloadedmetadata: any; onloadstart: any; onmousedown: any; onmouseenter: any; onmouseleave: any; onmousemove: any; onmouseout: any; onmouseover: any; onmouseup: any; onmousewheel: any; onmscontentzoom: any; onmsmanipulationstatechanged: any; onpaste: any; onpause: any; onplay: any; onplaying: any; onprogress: any; onratechange: any; onreset: any; onscroll: any; onseeked: any; onseeking: any; onselect: any; onselectstart: any; onstalled: any; onsubmit: any; onsuspend: any; ontimeupdate: any; onvolumechange: any; onwaiting: any; outerText: any; spellcheck: any; tabIndex: any; title: any; animate: any; blur: any; click: any; dragDrop: any; focus: any; msGetInputContext: any; addEventListener: any; removeEventListener: any; readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; readonly style: any; }; readonly parentNode: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; readonly previousSibling: { readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; addEventListener: any; dispatchEvent: any; removeEventListener: any; }; textContent: { toString: any; charAt: any; charCodeAt: any; concat: any; indexOf: any; lastIndexOf: any; localeCompare: any; match: any; replace: any; search: any; slice: any; split: any; substring: any; toLowerCase: any; toLocaleLowerCase: any; toUpperCase: any; toLocaleUpperCase: any; trim: any; readonly length: any; substr: any; valueOf: any; [Symbol.iterator]: any; codePointAt: any; includes: any; endsWith: any; normalize: any; repeat: any; startsWith: any; anchor: any; big: any; blink: any; bold: any; fixed: any; fontcolor: any; fontsize: any; italics: any; link: any; small: any; strike: any; sub: any; sup: any; }; appendChild: {}; cloneNode: {}; compareDocumentPosition: {}; contains: {}; hasChildNodes: {}; insertBefore: {}; isDefaultNamespace: {}; isEqualNode: {}; isSameNode: {}; lookupNamespaceURI: {}; lookupPrefix: {}; normalize: {}; removeChild: {}; replaceChild: {}; readonly ATTRIBUTE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly CDATA_SECTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly COMMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_FRAGMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINED_BY: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_CONTAINS: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_DISCONNECTED: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_FOLLOWING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_POSITION_PRECEDING: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly DOCUMENT_TYPE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ELEMENT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly ENTITY_REFERENCE_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly NOTATION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly PROCESSING_INSTRUCTION_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly TEXT_NODE: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; dispatchEvent: {}; onpointercancel: {}; onpointerdown: {}; onpointerenter: {}; onpointerleave: {}; onpointermove: {}; onpointerout: {}; onpointerover: {}; onpointerup: {}; onwheel: {}; readonly childElementCount: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; readonly firstElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly lastElementChild: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly nextElementSibling: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly previousElementSibling: { readonly assignedSlot: any; readonly attributes: any; readonly classList: any; className: any; readonly clientHeight: any; readonly clientLeft: any; readonly clientTop: any; readonly clientWidth: any; id: any; innerHTML: any; msContentZoomFactor: any; readonly msRegionOverflow: any; onariarequest: any; oncommand: any; ongotpointercapture: any; onlostpointercapture: any; onmsgesturechange: any; onmsgesturedoubletap: any; onmsgestureend: any; onmsgesturehold: any; onmsgesturestart: any; onmsgesturetap: any; onmsgotpointercapture: any; onmsinertiastart: any; onmslostpointercapture: any; onmspointercancel: any; onmspointerdown: any; onmspointerenter: any; onmspointerleave: any; onmspointermove: any; onmspointerout: any; onmspointerover: any; onmspointerup: any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onwebkitfullscreenchange: any; onwebkitfullscreenerror: any; outerHTML: any; readonly prefix: any; readonly scrollHeight: any; scrollLeft: any; scrollTop: any; readonly scrollWidth: any; readonly shadowRoot: any; slot: any; readonly tagName: any; attachShadow: any; closest: any; getAttribute: any; getAttributeNS: any; getAttributeNode: any; getAttributeNodeNS: any; getBoundingClientRect: any; getClientRects: any; getElementsByClassName: any; getElementsByTagName: any; getElementsByTagNameNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; insertAdjacentElement: any; insertAdjacentHTML: any; insertAdjacentText: any; matches: any; msGetRegionContent: any; msGetUntransformedBounds: any; msMatchesSelector: any; msReleasePointerCapture: any; msSetPointerCapture: any; msZoomTo: any; releasePointerCapture: any; removeAttribute: any; removeAttributeNS: any; removeAttributeNode: any; requestFullscreen: any; requestPointerLock: any; scroll: any; scrollBy: any; scrollIntoView: any; scrollTo: any; setAttribute: any; setAttributeNS: any; setAttributeNode: any; setAttributeNodeNS: any; setPointerCapture: any; webkitMatchesSelector: any; webkitRequestFullScreen: any; webkitRequestFullscreen: any; addEventListener: any; removeEventListener: any; readonly baseURI: any; readonly childNodes: any; readonly firstChild: any; readonly lastChild: any; readonly localName: any; readonly namespaceURI: any; readonly nextSibling: any; readonly nodeName: any; readonly nodeType: any; nodeValue: any; readonly ownerDocument: any; readonly parentElement: any; readonly parentNode: any; readonly previousSibling: any; textContent: any; appendChild: any; cloneNode: any; compareDocumentPosition: any; contains: any; hasChildNodes: any; insertBefore: any; isDefaultNamespace: any; isEqualNode: any; isSameNode: any; lookupNamespaceURI: any; lookupPrefix: any; normalize: any; removeChild: any; replaceChild: any; readonly ATTRIBUTE_NODE: any; readonly CDATA_SECTION_NODE: any; readonly COMMENT_NODE: any; readonly DOCUMENT_FRAGMENT_NODE: any; readonly DOCUMENT_NODE: any; readonly DOCUMENT_POSITION_CONTAINED_BY: any; readonly DOCUMENT_POSITION_CONTAINS: any; readonly DOCUMENT_POSITION_DISCONNECTED: any; readonly DOCUMENT_POSITION_FOLLOWING: any; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: any; readonly DOCUMENT_POSITION_PRECEDING: any; readonly DOCUMENT_TYPE_NODE: any; readonly ELEMENT_NODE: any; readonly ENTITY_NODE: any; readonly ENTITY_REFERENCE_NODE: any; readonly NOTATION_NODE: any; readonly PROCESSING_INSTRUCTION_NODE: any; readonly TEXT_NODE: any; dispatchEvent: any; onpointercancel: any; onpointerdown: any; onpointerenter: any; onpointerleave: any; onpointermove: any; onpointerout: any; onpointerover: any; onpointerup: any; onwheel: any; readonly childElementCount: any; readonly firstElementChild: any; readonly lastElementChild: any; readonly nextElementSibling: any; readonly previousElementSibling: any; readonly children: any; querySelector: any; querySelectorAll: any; remove: any; }; readonly children: { namedItem: any; readonly length: any; item: any; }; querySelector: {}; querySelectorAll: {}; remove: {}; } >className : { toString: {}; charAt: {}; charCodeAt: {}; concat: {}; indexOf: {}; lastIndexOf: {}; localeCompare: {}; match: {}; replace: {}; search: {}; slice: {}; split: {}; substring: {}; toLowerCase: {}; toLocaleLowerCase: {}; toUpperCase: {}; toLocaleUpperCase: {}; trim: {}; readonly length: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocaleString: any; }; substr: {}; valueOf: {}; [Symbol.iterator]: {}; codePointAt: {}; includes: {}; endsWith: {}; normalize: {}; repeat: {}; startsWith: {}; anchor: {}; big: {}; blink: {}; bold: {}; fixed: {}; fontcolor: {}; fontsize: {}; italics: {}; link: {}; small: {}; strike: {}; sub: {}; sup: {}; } >length : { toString: {}; toFixed: {}; toExponential: {}; toPrecision: {}; valueOf: {}; toLocaleString: {}; } From 6ec13bb9455e91466eb29cc7355b287f860de53a Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 28 Mar 2018 13:33:20 -0700 Subject: [PATCH 39/75] Use getAllSuperTypeNodes in more places (#22718) --- src/compiler/utilities.ts | 7 ++ src/services/completions.ts | 82 +++++----------- src/services/findAllReferences.ts | 95 +++++-------------- src/services/services.ts | 17 +--- .../completionEntryForClassMembers2.ts | 9 +- 5 files changed, 62 insertions(+), 148 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 1022e6c11eb..1cc3add43e3 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2111,6 +2111,13 @@ namespace ts { return heritageClause ? heritageClause.types : undefined; } + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + export function getAllSuperTypeNodes(node: Node): ReadonlyArray { + return isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || emptyArray + : isClassLike(node) ? concatenate(singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || emptyArray + : emptyArray; + } + export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration) { const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause ? heritageClause.types : undefined; diff --git a/src/services/completions.ts b/src/services/completions.ts index e7bbb47513f..4284de589bc 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1563,43 +1563,34 @@ namespace ts.Completions { completionKind = CompletionKind.MemberLike; // Declaring new property/method/accessor isNewIdentifierLocation = true; - // Has keywords for class elements keywordFilters = isClassLike(decl) ? KeywordCompletionFilters.ClassElementKeywords : KeywordCompletionFilters.InterfaceElementKeywords; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!isClassLike(decl)) return GlobalsSearch.Success; - const baseTypeNode = getClassExtendsHeritageClauseElement(decl); - const implementsTypeNodes = getClassImplementsHeritageClauseElements(decl); - if (!baseTypeNode && !implementsTypeNodes) return GlobalsSearch.Success; - const classElement = contextToken.parent; - const classElementModifierFlags = (isClassElement(classElement) ? getModifierFlags(classElement) : ModifierFlags.None) - // If this context token is not something we are editing now, consider if this would lead to be modifier - | (!isCurrentlyEditingNode(contextToken) ? modifierToFlag(keywordForNode(contextToken)) : ModifierFlags.None); - - // No member list for private methods - if (classElementModifierFlags & ModifierFlags.Private) return GlobalsSearch.Success; - - let baseClassTypeToGetPropertiesFrom: Type | undefined; - if (baseTypeNode) { - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); - if (classElementModifierFlags & ModifierFlags.Static) { - // Use static class to get property symbols from - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, decl); + let classElementModifierFlags = isClassElement(classElement) && getModifierFlags(classElement); + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === SyntaxKind.Identifier && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | ModifierFlags.Private; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | ModifierFlags.Static; + break; } } - const implementedInterfaceTypePropertySymbols = !implementsTypeNodes || (classElementModifierFlags & ModifierFlags.Static) - ? emptyArray - : flatMap(implementsTypeNodes, typeNode => 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) : emptyArray, - implementedInterfaceTypePropertySymbols, - decl.members, - classElementModifierFlags); + // No member list for private methods + if (!(classElementModifierFlags & ModifierFlags.Private)) { + // List of property symbols of base type that are not private and already implemented + const baseSymbols = flatMap(getAllSuperTypeNodes(decl), baseTypeNode => { + const type = typeChecker.getTypeAtLocation(baseTypeNode); + return typeChecker.getPropertiesOfType(classElementModifierFlags & ModifierFlags.Static ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } return GlobalsSearch.Success; } @@ -1967,12 +1958,8 @@ namespace ts.Completions { * * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags */ - function filterClassMembersList( - baseSymbols: ReadonlyArray, - implementingTypeSymbols: ReadonlyArray, - existingMembers: ReadonlyArray, - currentClassElementModifierFlags: ModifierFlags): Symbol[] { - const existingMemberNames = createUnderscoreEscapedMap(); + function filterClassMembersList(baseSymbols: ReadonlyArray, existingMembers: ReadonlyArray, currentClassElementModifierFlags: ModifierFlags): Symbol[] { + const existingMemberNames = createUnderscoreEscapedMap(); for (const m of existingMembers) { // Ignore omitted expressions for missing members if (m.kind !== SyntaxKind.PropertyDeclaration && @@ -1993,10 +1980,7 @@ namespace ts.Completions { } // do not filter it out if the static presence doesnt match - const mIsStatic = hasModifier(m, ModifierFlags.Static); - const currentElementIsStatic = !!(currentClassElementModifierFlags & ModifierFlags.Static); - if ((mIsStatic && !currentElementIsStatic) || - (!mIsStatic && currentElementIsStatic)) { + if (hasModifier(m, ModifierFlags.Static) !== !!(currentClassElementModifierFlags & ModifierFlags.Static)) { continue; } @@ -2006,24 +1990,10 @@ namespace ts.Completions { } } - const result: Symbol[] = []; - addPropertySymbols(baseSymbols, ModifierFlags.Private); - addPropertySymbols(implementingTypeSymbols, ModifierFlags.NonPublicAccessibilityModifier); - return result; - - function addPropertySymbols(properties: ReadonlyArray, inValidModifierFlags: ModifierFlags) { - for (const property of properties) { - if (isValidProperty(property, inValidModifierFlags)) { - result.push(property); - } - } - } - - function isValidProperty(propertySymbol: Symbol, inValidModifierFlags: ModifierFlags) { - return !existingMemberNames.get(propertySymbol.escapedName) && - propertySymbol.getDeclarations() && - !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); - } + return baseSymbols.filter(propertySymbol => + !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & ModifierFlags.Private)); } /** diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index e742a7f1030..a151d776403 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1200,63 +1200,31 @@ namespace ts.FindAllReferences.Core { * distinction between structurally compatible implementations and explicit implementations, so we * must use the AST. * - * @param child A class or interface Symbol + * @param symbol 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: Symbol, parent: Symbol, cachedResults: Map, checker: TypeChecker): boolean { - const parentIsInterface = parent.getFlags() & SymbolFlags.Interface; - return searchHierarchy(child); - - function searchHierarchy(symbol: Symbol): boolean { - if (symbol === parent) { - return true; - } - - const key = getSymbolId(symbol) + "," + getSymbolId(parent); - const cached = cachedResults.get(key); - if (cached !== undefined) { - return cached; - } - - // Set the key so that we don't infinitely recurse - cachedResults.set(key, false); - - const inherits = forEach(symbol.getDeclarations(), declaration => { - if (isClassLike(declaration)) { - if (parentIsInterface) { - const interfaceReferences = getClassImplementsHeritageClauseElements(declaration); - if (interfaceReferences) { - for (const typeReference of interfaceReferences) { - if (searchTypeReference(typeReference)) { - return true; - } - } - } - } - return searchTypeReference(getClassExtendsHeritageClauseElement(declaration)); - } - else if (declaration.kind === SyntaxKind.InterfaceDeclaration) { - if (parentIsInterface) { - return forEach(getInterfaceBaseTypeNodes(declaration), searchTypeReference); - } - } - return false; - }); - - cachedResults.set(key, inherits); - return inherits; + function explicitlyInheritsFrom(symbol: Symbol, parent: Symbol, cachedResults: Map, checker: TypeChecker): boolean { + if (symbol === parent) { + return true; } - function searchTypeReference(typeReference: ExpressionWithTypeArguments): boolean { - if (typeReference) { + const key = getSymbolId(symbol) + "," + getSymbolId(parent); + const cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + + const inherits = symbol.declarations.some(declaration => + getAllSuperTypeNodes(declaration).some(typeReference => { const type = checker.getTypeAtLocation(typeReference); - if (type && type.symbol) { - return searchHierarchy(type.symbol); - } - } - return false; - } + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + })); + cachedResults.set(key, inherits); + return inherits; } function getReferencesForSuperKeyword(superKeyword: Node): SymbolAndEntries[] { @@ -1491,10 +1459,6 @@ namespace ts.FindAllReferences.Core { * The value of previousIterationSymbol is undefined when the function is first called. */ function getPropertySymbolsFromBaseTypes(symbol: Symbol, propertyName: string, result: Push, previousIterationSymbolsCache: SymbolTable, checker: TypeChecker): void { - 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: @@ -1506,27 +1470,16 @@ namespace ts.FindAllReferences.Core { // 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)) { + if (!symbol || previousIterationSymbolsCache.has(symbol.escapedName)) { return; } if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { - forEach(symbol.getDeclarations(), declaration => { - if (isClassLike(declaration)) { - getPropertySymbolFromTypeReference(getClassExtendsHeritageClauseElement(declaration)); - forEach(getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); - } - else if (declaration.kind === SyntaxKind.InterfaceDeclaration) { - forEach(getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; + for (const declaration of symbol.declarations) { + for (const typeReference of getAllSuperTypeNodes(declaration)) { + const type = checker.getTypeAtLocation(typeReference); + if (!type) continue; - function getPropertySymbolFromTypeReference(typeReference: ExpressionWithTypeArguments): void { - if (typeReference) { - const type = checker.getTypeAtLocation(typeReference); - if (type) { const propertySymbol = checker.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push(...checker.getRootSymbols(propertySymbol)); diff --git a/src/services/services.ts b/src/services/services.ts index cd35e0375a3..590c65c4eae 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -576,7 +576,7 @@ namespace ts { */ function findInheritedJSDocComments(declaration: Declaration, propertyName: string, typeChecker: TypeChecker): SymbolDisplayPart[] { let foundDocs = false; - return flatMap(getAllSuperTypeNodes(declaration), superTypeNode => { + return flatMap(declaration.parent ? getAllSuperTypeNodes(declaration.parent) : emptyArray, superTypeNode => { if (foundDocs) { return emptyArray; } @@ -594,21 +594,6 @@ namespace ts { }); } - /** - * 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: Declaration): ReadonlyArray { - const container = declaration.parent; - if (!container || (!isClassDeclaration(container) && !isInterfaceDeclaration(container))) { - return emptyArray; - } - const extended = getClassExtendsHeritageClauseElement(container); - const types = extended ? [extended] : emptyArray; - return isClassLike(container) ? concatenate(types, getClassImplementsHeritageClauseElements(container)) : types; - } - class SourceFileObject extends NodeObject implements SourceFile { public kind: SyntaxKind.SourceFile; public _declarationBrand: any; diff --git a/tests/cases/fourslash/completionEntryForClassMembers2.ts b/tests/cases/fourslash/completionEntryForClassMembers2.ts index 539702196a3..9d2d158cd55 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers2.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers2.ts @@ -350,7 +350,7 @@ verifyClassElementLocations( value => value[0] !== "getValue"), ["extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember"]); -const invalidMembersOfB0AtInstanceSide = privateMembersOfBaseClassB0.concat(validStaticMembersOfBaseClassB0); +const invalidMembersOfB0AtInstanceSide = privateMembersOfBaseClassB0.concat(validStaticMembersOfBaseClassB0); const invalidMembersOfB0AtStaticSide = privateMembersOfBaseClassB0.concat(validInstanceMembersOfBaseClassB0); // members of B0 and members of I4 verifyClassElementLocations({ @@ -403,11 +403,10 @@ verifyClassElementLocations({ validMembers: membersOfI7, invalidMembers: noMembe "implementsIAndAlsoImplementsI7whichExtendsI" ]); -const invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 = invalidMembersOfB0AtInstanceSide - .concat(protectedPropertiesOfBaseClassB0); +const invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 = invalidMembersOfB0AtInstanceSide; // members of I5 extends B0 verifyClassElementLocations({ - validMembers: membersOfI5, + validMembers: membersOfI5.concat(protectedPropertiesOfBaseClassB0), invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 }, [ "implementsI5ThatExtendsB0", @@ -415,7 +414,7 @@ verifyClassElementLocations({ // members of I6 extends B0 verifyClassElementLocations({ - validMembers: membersOfI6, + validMembers: membersOfI6.concat(protectedPropertiesOfBaseClassB0), invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 }, [ "implementsI6ThatExtendsB0AndHasStaticMethodOfB0", From 7d39b457f88d667c6eab8530d447cede4507846c Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 28 Mar 2018 13:57:43 -0700 Subject: [PATCH 40/75] Simplify createChildren (#22270) * Simplify createChildren * Move 'getSourceFile()' call after early returns --- src/services/services.ts | 165 +++++++++++++++++---------------------- 1 file changed, 72 insertions(+), 93 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index 590c65c4eae..64e64ea1bad 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -54,7 +54,7 @@ namespace ts { public jsDoc: JSDoc[]; public original: Node; public transformFlags: TransformFlags; - private _children: Node[]; + private _children: Node[] | undefined; constructor(kind: SyntaxKind, pos: number, end: number) { this.pos = pos; @@ -117,106 +117,17 @@ namespace ts { return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); } - private addSyntheticNodes(nodes: Push, pos: number, end: number): number { - scanner.setTextPos(pos); - while (pos < end) { - const token = scanner.scan(); - const textPos = scanner.getTextPos(); - if (textPos <= end) { - if (token === SyntaxKind.Identifier) { - Debug.fail(`Did not expect ${Debug.showSyntaxKind(this)} to have an Identifier in its trivia`); - } - nodes.push(createNode(token, pos, textPos, this)); - } - pos = textPos; - if (token === SyntaxKind.EndOfFileToken) { - break; - } - } - return pos; - } - - private createSyntaxList(nodes: NodeArray): Node { - const list = createNode(SyntaxKind.SyntaxList, nodes.pos, nodes.end, this); - list._children = []; - let pos = nodes.pos; - - for (const node of nodes) { - if (pos < node.pos) { - pos = this.addSyntheticNodes(list._children, pos, node.pos); - } - list._children.push(node); - pos = node.end; - } - if (pos < nodes.end) { - this.addSyntheticNodes(list._children, pos, nodes.end); - } - return list; - } - - private createChildren(sourceFile?: SourceFileLike) { - if (!isNodeKind(this.kind)) { - this._children = emptyArray; - return; - } - - if (isJSDocCommentContainingNode(this)) { - /** Don't add trivia for "tokens" since this is in a comment. */ - const children: Node[] = []; - this.forEachChild(child => { children.push(child); }); - this._children = children; - return; - } - - const children: Node[] = []; - scanner.setText((sourceFile || this.getSourceFile()).text); - let pos = this.pos; - const processNode = (node: Node) => { - pos = this.addSyntheticNodes(children, pos, node.pos); - children.push(node); - pos = node.end; - }; - const processNodes = (nodes: NodeArray) => { - if (pos < nodes.pos) { - pos = this.addSyntheticNodes(children, pos, nodes.pos); - } - children.push(this.createSyntaxList(nodes)); - pos = nodes.end; - }; - // jsDocComments need to be the first children - if (this.jsDoc) { - for (const jsDocComment of this.jsDoc) { - 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; - forEachChild(this, processNode, processNodes); - if (pos < this.end) { - this.addSyntheticNodes(children, pos, this.end); - } - scanner.setText(undefined); - this._children = children; - } - public getChildCount(sourceFile?: SourceFile): number { - this.assertHasRealPosition(); - if (!this._children) this.createChildren(sourceFile); - return this._children.length; + return this.getChildren(sourceFile).length; } public getChildAt(index: number, sourceFile?: SourceFile): Node { - this.assertHasRealPosition(); - if (!this._children) this.createChildren(sourceFile); - return this._children[index]; + return this.getChildren(sourceFile)[index]; } public getChildren(sourceFile?: SourceFileLike): Node[] { 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; + return this._children || (this._children = createChildren(this, sourceFile)); } public getFirstToken(sourceFile?: SourceFile): Node { @@ -249,6 +160,74 @@ namespace ts { } } + function createChildren(node: Node, sourceFile: SourceFileLike | undefined): Node[] { + if (!isNodeKind(node.kind)) { + return emptyArray; + } + + const children: Node[] = []; + + if (isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(child => { children.push(child); }); + return children; + } + + scanner.setText((sourceFile || node.getSourceFile()).text); + let pos = node.pos; + const processNode = (child: Node) => { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + const processNodes = (nodes: NodeArray) => { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + forEach((node as JSDocContainer).jsDoc, processNode); + // For syntactic classifications, all trivia are classified 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 = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + scanner.setText(undefined); + return children; + } + + function addSyntheticNodes(nodes: Push, pos: number, end: number, parent: Node): void { + scanner.setTextPos(pos); + while (pos < end) { + const token = scanner.scan(); + const textPos = scanner.getTextPos(); + if (textPos <= end) { + if (token === SyntaxKind.Identifier) { + Debug.fail(`Did not expect ${Debug.showSyntaxKind(parent)} to have an Identifier in its trivia`); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === SyntaxKind.EndOfFileToken) { + break; + } + } + } + + function createSyntaxList(nodes: NodeArray, parent: Node): Node { + const list = createNode(SyntaxKind.SyntaxList, nodes.pos, nodes.end, parent) as any as SyntaxList; + list._children = []; + let pos = nodes.pos; + for (const node of nodes) { + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } + class TokenOrIdentifierObject implements Node { public kind: SyntaxKind; public pos: number; From 33e9ef60c4343be8cbae59e4b917d920181b1321 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 28 Mar 2018 13:12:06 -0700 Subject: [PATCH 41/75] Correct the incremental parsing when there is jsDoc node Fixes #22924 --- src/compiler/parser.ts | 18 ++++++++++++++---- .../fourslash/incrementalParsingWithJsDoc.ts | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 tests/cases/fourslash/incrementalParsingWithJsDoc.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index e72ce3ad5ac..182995a3881 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -6965,7 +6965,7 @@ namespace ts { forEachChild(node, visitNode, visitArray); if (hasJSDocNodes(node)) { for (const jsDocComment of node.jsDoc) { - forEachChild(jsDocComment, visitNode, visitArray); + visitNode(jsDocComment); } } checkNodePositions(node, aggressiveChecks); @@ -7071,10 +7071,16 @@ namespace ts { function checkNodePositions(node: Node, aggressiveChecks: boolean) { if (aggressiveChecks) { let pos = node.pos; - forEachChild(node, child => { + const visitNode = (child: Node) => { Debug.assert(child.pos >= pos); pos = child.end; - }); + }; + if (hasJSDocNodes(node)) { + for (const jsDocComment of node.jsDoc) { + visitNode(jsDocComment); + } + } + forEachChild(node, visitNode); Debug.assert(pos <= node.end); } } @@ -7112,7 +7118,11 @@ namespace ts { // Adjust the pos or end (or both) of the intersecting element accordingly. adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); - + if (hasJSDocNodes(child)) { + for (const jsDocComment of child.jsDoc) { + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } diff --git a/tests/cases/fourslash/incrementalParsingWithJsDoc.ts b/tests/cases/fourslash/incrementalParsingWithJsDoc.ts new file mode 100644 index 00000000000..cd709530f9c --- /dev/null +++ b/tests/cases/fourslash/incrementalParsingWithJsDoc.ts @@ -0,0 +1,15 @@ +/// + +////import a from 'a/aaaaaaa/aaaaaaa/aaaaaa/aaaaaaa'; +/////**/import b from 'b'; +////import c from 'c'; +//// +////[|/** @internal */|] +////export class LanguageIdentifier[| { }|] + +// Force a syntax tree ot be created. +verify.outliningSpansInCurrentFile(test.ranges()); +goTo.marker(""); +edit.backspace(test.marker("").position); +verify.outliningSpansInCurrentFile(test.ranges()); + From 83276ce163c82abb46ec5d75b7a84d5c20b3e9d0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 28 Mar 2018 15:21:29 -0700 Subject: [PATCH 42/75] Add another test --- .../cases/conformance/types/conditional/conditionalTypes1.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/cases/conformance/types/conditional/conditionalTypes1.ts b/tests/cases/conformance/types/conditional/conditionalTypes1.ts index 4005e896ce1..8aa524ba818 100644 --- a/tests/cases/conformance/types/conditional/conditionalTypes1.ts +++ b/tests/cases/conformance/types/conditional/conditionalTypes1.ts @@ -219,6 +219,10 @@ function f22(x: T extends (infer U)[] ? U[] : never) { let e = x[0]; // {} } +function f23(x: T extends (infer U)[] ? U[] : never) { + let e = x[0]; // string +} + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; From 6fedf4dc7eb91a31edf5dc1b728d6cf09a3b7117 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 28 Mar 2018 15:21:36 -0700 Subject: [PATCH 43/75] Accept new baselines --- .../reference/conditionalTypes1.errors.txt | 8 +- .../baselines/reference/conditionalTypes1.js | 8 + .../reference/conditionalTypes1.symbols | 597 +++++++++--------- .../reference/conditionalTypes1.types | 15 + 4 files changed, 334 insertions(+), 294 deletions(-) diff --git a/tests/baselines/reference/conditionalTypes1.errors.txt b/tests/baselines/reference/conditionalTypes1.errors.txt index b96ecf6254c..de06eeb832b 100644 --- a/tests/baselines/reference/conditionalTypes1.errors.txt +++ b/tests/baselines/reference/conditionalTypes1.errors.txt @@ -64,8 +64,8 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(159,5): error TS2 tests/cases/conformance/types/conditional/conditionalTypes1.ts(160,5): error TS2322: Type 'T' is not assignable to type 'ZeroOf'. Type 'string | number' is not assignable to type 'ZeroOf'. Type 'string' is not assignable to type 'ZeroOf'. -tests/cases/conformance/types/conditional/conditionalTypes1.ts(259,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'z' must be of type 'T1', but here has type 'Foo'. -tests/cases/conformance/types/conditional/conditionalTypes1.ts(284,43): error TS2322: Type 'T95' is not assignable to type 'T94'. +tests/cases/conformance/types/conditional/conditionalTypes1.ts(263,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'z' must be of type 'T1', but here has type 'Foo'. +tests/cases/conformance/types/conditional/conditionalTypes1.ts(288,43): error TS2322: Type 'T95' is not assignable to type 'T94'. Type 'boolean' is not assignable to type 'true'. @@ -374,6 +374,10 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(284,43): error TS let e = x[0]; // {} } + function f23(x: T extends (infer U)[] ? U[] : never) { + let e = x[0]; // string + } + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; diff --git a/tests/baselines/reference/conditionalTypes1.js b/tests/baselines/reference/conditionalTypes1.js index f0acf03c967..4ac1efa1868 100644 --- a/tests/baselines/reference/conditionalTypes1.js +++ b/tests/baselines/reference/conditionalTypes1.js @@ -217,6 +217,10 @@ function f22(x: T extends (infer U)[] ? U[] : never) { let e = x[0]; // {} } +function f23(x: T extends (infer U)[] ? U[] : never) { + let e = x[0]; // string +} + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; @@ -405,6 +409,9 @@ function f21(x, y) { function f22(x) { var e = x[0]; // {} } +function f23(x) { + var e = x[0]; // string +} var convert = function (value) { return value; }; var convert2 = function (value) { return value; }; function f31() { @@ -598,6 +605,7 @@ declare type T50 = IsNever; declare type T51 = IsNever; declare type T52 = IsNever; declare function f22(x: T extends (infer U)[] ? U[] : never): void; +declare function f23(x: T extends (infer U)[] ? U[] : never): void; declare type Eq = T extends U ? U extends T ? true : false : false; declare type T60 = Eq; declare type T61 = Eq; diff --git a/tests/baselines/reference/conditionalTypes1.symbols b/tests/baselines/reference/conditionalTypes1.symbols index 6a59d7da9db..ae13ff75913 100644 --- a/tests/baselines/reference/conditionalTypes1.symbols +++ b/tests/baselines/reference/conditionalTypes1.symbols @@ -832,475 +832,488 @@ function f22(x: T extends (infer U)[] ? U[] : never) { >x : Symbol(x, Decl(conditionalTypes1.ts, 214, 16)) } +function f23(x: T extends (infer U)[] ? U[] : never) { +>f23 : Symbol(f23, Decl(conditionalTypes1.ts, 216, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 218, 13)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 218, 33)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 218, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 218, 52)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 218, 52)) + + let e = x[0]; // string +>e : Symbol(e, Decl(conditionalTypes1.ts, 219, 7)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 218, 33)) +} + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 220, 8)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 220, 10)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 220, 8)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 220, 10)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 220, 10)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 220, 8)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 220, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 224, 8)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 224, 10)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 224, 8)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 224, 10)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 224, 10)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 224, 8)) type T60 = Eq; // true ->T60 : Symbol(T60, Decl(conditionalTypes1.ts, 220, 65)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) +>T60 : Symbol(T60, Decl(conditionalTypes1.ts, 224, 65)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 220, 1)) type T61 = Eq; // false ->T61 : Symbol(T61, Decl(conditionalTypes1.ts, 221, 26)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) +>T61 : Symbol(T61, Decl(conditionalTypes1.ts, 225, 26)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 220, 1)) type T62 = Eq; // false ->T62 : Symbol(T62, Decl(conditionalTypes1.ts, 222, 27)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) +>T62 : Symbol(T62, Decl(conditionalTypes1.ts, 226, 27)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 220, 1)) type T63 = Eq; // true ->T63 : Symbol(T63, Decl(conditionalTypes1.ts, 223, 27)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) +>T63 : Symbol(T63, Decl(conditionalTypes1.ts, 227, 27)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 220, 1)) type Eq1 = Eq extends false ? false : true; ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 226, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 226, 11)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 226, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 226, 11)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 228, 28)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 230, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 230, 11)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 220, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 230, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 230, 11)) type T70 = Eq1; // true ->T70 : Symbol(T70, Decl(conditionalTypes1.ts, 226, 55)) ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) +>T70 : Symbol(T70, Decl(conditionalTypes1.ts, 230, 55)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 228, 28)) type T71 = Eq1; // false ->T71 : Symbol(T71, Decl(conditionalTypes1.ts, 227, 27)) ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) +>T71 : Symbol(T71, Decl(conditionalTypes1.ts, 231, 27)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 228, 28)) type T72 = Eq1; // false ->T72 : Symbol(T72, Decl(conditionalTypes1.ts, 228, 28)) ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) +>T72 : Symbol(T72, Decl(conditionalTypes1.ts, 232, 28)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 228, 28)) type T73 = Eq1; // true ->T73 : Symbol(T73, Decl(conditionalTypes1.ts, 229, 28)) ->Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 224, 28)) +>T73 : Symbol(T73, Decl(conditionalTypes1.ts, 233, 28)) +>Eq1 : Symbol(Eq1, Decl(conditionalTypes1.ts, 228, 28)) type Eq2 = Eq extends true ? true : false; ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 232, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 232, 11)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 216, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 232, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 232, 11)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 234, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 236, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 236, 11)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 220, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 236, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 236, 11)) type T80 = Eq2; // true ->T80 : Symbol(T80, Decl(conditionalTypes1.ts, 232, 54)) ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) +>T80 : Symbol(T80, Decl(conditionalTypes1.ts, 236, 54)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 234, 29)) type T81 = Eq2; // false ->T81 : Symbol(T81, Decl(conditionalTypes1.ts, 233, 27)) ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) +>T81 : Symbol(T81, Decl(conditionalTypes1.ts, 237, 27)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 234, 29)) type T82 = Eq2; // false ->T82 : Symbol(T82, Decl(conditionalTypes1.ts, 234, 28)) ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) +>T82 : Symbol(T82, Decl(conditionalTypes1.ts, 238, 28)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 234, 29)) type T83 = Eq2; // true ->T83 : Symbol(T83, Decl(conditionalTypes1.ts, 235, 28)) ->Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 230, 29)) +>T83 : Symbol(T83, Decl(conditionalTypes1.ts, 239, 28)) +>Eq2 : Symbol(Eq2, Decl(conditionalTypes1.ts, 234, 29)) // Repro from #21756 type Foo = T extends string ? boolean : number; ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 240, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 240, 9)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 240, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 244, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 244, 9)) type Bar = T extends string ? boolean : number; ->Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 240, 50)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 241, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 241, 9)) +>Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 244, 50)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 245, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 245, 9)) const convert = (value: Foo): Bar => value; ->convert : Symbol(convert, Decl(conditionalTypes1.ts, 242, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 242, 17)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 242, 20)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 242, 17)) ->Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 240, 50)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 242, 17)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 242, 20)) +>convert : Symbol(convert, Decl(conditionalTypes1.ts, 246, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 246, 17)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 246, 20)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 240, 29)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 246, 17)) +>Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 244, 50)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 246, 17)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 246, 20)) type Baz = Foo; ->Baz : Symbol(Baz, Decl(conditionalTypes1.ts, 242, 52)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 244, 9)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 244, 9)) +>Baz : Symbol(Baz, Decl(conditionalTypes1.ts, 246, 52)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 248, 9)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 240, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 248, 9)) const convert2 = (value: Foo): Baz => value; ->convert2 : Symbol(convert2, Decl(conditionalTypes1.ts, 245, 5)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 245, 18)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 245, 21)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 245, 18)) ->Baz : Symbol(Baz, Decl(conditionalTypes1.ts, 242, 52)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 245, 18)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 245, 21)) +>convert2 : Symbol(convert2, Decl(conditionalTypes1.ts, 249, 5)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 249, 18)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 249, 21)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 240, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 249, 18)) +>Baz : Symbol(Baz, Decl(conditionalTypes1.ts, 246, 52)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 249, 18)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 249, 21)) function f31() { ->f31 : Symbol(f31, Decl(conditionalTypes1.ts, 245, 53)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 247, 13)) +>f31 : Symbol(f31, Decl(conditionalTypes1.ts, 249, 53)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 251, 13)) type T1 = T extends string ? boolean : number; ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 247, 19)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 247, 13)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 251, 19)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 251, 13)) type T2 = T extends string ? boolean : number; ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 248, 50)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 247, 13)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 252, 50)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 251, 13)) var x: T1; ->x : Symbol(x, Decl(conditionalTypes1.ts, 250, 7), Decl(conditionalTypes1.ts, 251, 7)) ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 247, 19)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 254, 7), Decl(conditionalTypes1.ts, 255, 7)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 251, 19)) var x: T2; ->x : Symbol(x, Decl(conditionalTypes1.ts, 250, 7), Decl(conditionalTypes1.ts, 251, 7)) ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 248, 50)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 254, 7), Decl(conditionalTypes1.ts, 255, 7)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 252, 50)) } function f32() { ->f32 : Symbol(f32, Decl(conditionalTypes1.ts, 252, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 254, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 254, 15)) +>f32 : Symbol(f32, Decl(conditionalTypes1.ts, 256, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 258, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 258, 15)) type T1 = T & U extends string ? boolean : number; ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 254, 22)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 254, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 254, 15)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 258, 22)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 258, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 258, 15)) type T2 = Foo; ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 255, 54)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 254, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 254, 15)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 259, 54)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 240, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 258, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 258, 15)) var z: T1; ->z : Symbol(z, Decl(conditionalTypes1.ts, 257, 7), Decl(conditionalTypes1.ts, 258, 7)) ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 254, 22)) +>z : Symbol(z, Decl(conditionalTypes1.ts, 261, 7), Decl(conditionalTypes1.ts, 262, 7)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 258, 22)) var z: T2; // Error, T2 is distributive, T1 isn't ->z : Symbol(z, Decl(conditionalTypes1.ts, 257, 7), Decl(conditionalTypes1.ts, 258, 7)) ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 255, 54)) +>z : Symbol(z, Decl(conditionalTypes1.ts, 261, 7), Decl(conditionalTypes1.ts, 262, 7)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 259, 54)) } function f33() { ->f33 : Symbol(f33, Decl(conditionalTypes1.ts, 259, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 261, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 261, 15)) +>f33 : Symbol(f33, Decl(conditionalTypes1.ts, 263, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 265, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 265, 15)) type T1 = Foo; ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 261, 22)) ->Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 236, 29)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 261, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 261, 15)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 265, 22)) +>Foo : Symbol(Foo, Decl(conditionalTypes1.ts, 240, 29)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 265, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 265, 15)) type T2 = Bar; ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 262, 25)) ->Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 240, 50)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 261, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 261, 15)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 266, 25)) +>Bar : Symbol(Bar, Decl(conditionalTypes1.ts, 244, 50)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 265, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 265, 15)) var z: T1; ->z : Symbol(z, Decl(conditionalTypes1.ts, 264, 7), Decl(conditionalTypes1.ts, 265, 7)) ->T1 : Symbol(T1, Decl(conditionalTypes1.ts, 261, 22)) +>z : Symbol(z, Decl(conditionalTypes1.ts, 268, 7), Decl(conditionalTypes1.ts, 269, 7)) +>T1 : Symbol(T1, Decl(conditionalTypes1.ts, 265, 22)) var z: T2; ->z : Symbol(z, Decl(conditionalTypes1.ts, 264, 7), Decl(conditionalTypes1.ts, 265, 7)) ->T2 : Symbol(T2, Decl(conditionalTypes1.ts, 262, 25)) +>z : Symbol(z, Decl(conditionalTypes1.ts, 268, 7), Decl(conditionalTypes1.ts, 269, 7)) +>T2 : Symbol(T2, Decl(conditionalTypes1.ts, 266, 25)) } // Repro from #21823 type T90 = T extends 0 ? 0 : () => 0; ->T90 : Symbol(T90, Decl(conditionalTypes1.ts, 266, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 270, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 270, 9)) +>T90 : Symbol(T90, Decl(conditionalTypes1.ts, 270, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 274, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 274, 9)) type T91 = T extends 0 ? 0 : () => 0; ->T91 : Symbol(T91, Decl(conditionalTypes1.ts, 270, 40)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 271, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 271, 9)) +>T91 : Symbol(T91, Decl(conditionalTypes1.ts, 274, 40)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 275, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 275, 9)) const f40 = (a: T90): T91 => a; ->f40 : Symbol(f40, Decl(conditionalTypes1.ts, 272, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 272, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 272, 16)) ->T90 : Symbol(T90, Decl(conditionalTypes1.ts, 266, 1)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 272, 13)) ->T91 : Symbol(T91, Decl(conditionalTypes1.ts, 270, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 272, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 272, 16)) +>f40 : Symbol(f40, Decl(conditionalTypes1.ts, 276, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 276, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 276, 16)) +>T90 : Symbol(T90, Decl(conditionalTypes1.ts, 270, 1)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 276, 13)) +>T91 : Symbol(T91, Decl(conditionalTypes1.ts, 274, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 276, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 276, 16)) const f41 = (a: T91): T90 => a; ->f41 : Symbol(f41, Decl(conditionalTypes1.ts, 273, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 273, 16)) ->T91 : Symbol(T91, Decl(conditionalTypes1.ts, 270, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) ->T90 : Symbol(T90, Decl(conditionalTypes1.ts, 266, 1)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 273, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 273, 16)) +>f41 : Symbol(f41, Decl(conditionalTypes1.ts, 277, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 277, 16)) +>T91 : Symbol(T91, Decl(conditionalTypes1.ts, 274, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) +>T90 : Symbol(T90, Decl(conditionalTypes1.ts, 270, 1)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 277, 16)) type T92 = T extends () => 0 ? () => 1 : () => 2; ->T92 : Symbol(T92, Decl(conditionalTypes1.ts, 273, 40)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 275, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 275, 9)) +>T92 : Symbol(T92, Decl(conditionalTypes1.ts, 277, 40)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 279, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 279, 9)) type T93 = T extends () => 0 ? () => 1 : () => 2; ->T93 : Symbol(T93, Decl(conditionalTypes1.ts, 275, 52)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 276, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 276, 9)) +>T93 : Symbol(T93, Decl(conditionalTypes1.ts, 279, 52)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 280, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 280, 9)) const f42 = (a: T92): T93 => a; ->f42 : Symbol(f42, Decl(conditionalTypes1.ts, 277, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 277, 16)) ->T92 : Symbol(T92, Decl(conditionalTypes1.ts, 273, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) ->T93 : Symbol(T93, Decl(conditionalTypes1.ts, 275, 52)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 277, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 277, 16)) +>f42 : Symbol(f42, Decl(conditionalTypes1.ts, 281, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 281, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 281, 16)) +>T92 : Symbol(T92, Decl(conditionalTypes1.ts, 277, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 281, 13)) +>T93 : Symbol(T93, Decl(conditionalTypes1.ts, 279, 52)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 281, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 281, 16)) const f43 = (a: T93): T92 => a; ->f43 : Symbol(f43, Decl(conditionalTypes1.ts, 278, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 278, 16)) ->T93 : Symbol(T93, Decl(conditionalTypes1.ts, 275, 52)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) ->T92 : Symbol(T92, Decl(conditionalTypes1.ts, 273, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 278, 13)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 278, 16)) +>f43 : Symbol(f43, Decl(conditionalTypes1.ts, 282, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 282, 16)) +>T93 : Symbol(T93, Decl(conditionalTypes1.ts, 279, 52)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) +>T92 : Symbol(T92, Decl(conditionalTypes1.ts, 277, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 282, 16)) type T94 = T extends string ? true : 42; ->T94 : Symbol(T94, Decl(conditionalTypes1.ts, 278, 40)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 280, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 280, 9)) +>T94 : Symbol(T94, Decl(conditionalTypes1.ts, 282, 40)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 284, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 284, 9)) type T95 = T extends string ? boolean : number; ->T95 : Symbol(T95, Decl(conditionalTypes1.ts, 280, 43)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 281, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 281, 9)) +>T95 : Symbol(T95, Decl(conditionalTypes1.ts, 284, 43)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 285, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 285, 9)) const f44 = (value: T94): T95 => value; ->f44 : Symbol(f44, Decl(conditionalTypes1.ts, 282, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 282, 16)) ->T94 : Symbol(T94, Decl(conditionalTypes1.ts, 278, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) ->T95 : Symbol(T95, Decl(conditionalTypes1.ts, 280, 43)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 282, 13)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 282, 16)) +>f44 : Symbol(f44, Decl(conditionalTypes1.ts, 286, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 286, 13)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 286, 16)) +>T94 : Symbol(T94, Decl(conditionalTypes1.ts, 282, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 286, 13)) +>T95 : Symbol(T95, Decl(conditionalTypes1.ts, 284, 43)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 286, 13)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 286, 16)) const f45 = (value: T95): T94 => value; // Error ->f45 : Symbol(f45, Decl(conditionalTypes1.ts, 283, 5)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 283, 13)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 283, 16)) ->T95 : Symbol(T95, Decl(conditionalTypes1.ts, 280, 43)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 283, 13)) ->T94 : Symbol(T94, Decl(conditionalTypes1.ts, 278, 40)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 283, 13)) ->value : Symbol(value, Decl(conditionalTypes1.ts, 283, 16)) +>f45 : Symbol(f45, Decl(conditionalTypes1.ts, 287, 5)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 287, 13)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 287, 16)) +>T95 : Symbol(T95, Decl(conditionalTypes1.ts, 284, 43)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 287, 13)) +>T94 : Symbol(T94, Decl(conditionalTypes1.ts, 282, 40)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 287, 13)) +>value : Symbol(value, Decl(conditionalTypes1.ts, 287, 16)) // Repro from #21863 function f50() { ->f50 : Symbol(f50, Decl(conditionalTypes1.ts, 283, 48)) +>f50 : Symbol(f50, Decl(conditionalTypes1.ts, 287, 48)) type Eq = T extends U ? U extends T ? true : false : false; ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 287, 16)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 288, 12)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 288, 14)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 288, 12)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 288, 14)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 288, 14)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 288, 12)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 291, 16)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 292, 12)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 292, 14)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 292, 12)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 292, 14)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 292, 14)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 292, 12)) type If = S extends false ? U : T; ->If : Symbol(If, Decl(conditionalTypes1.ts, 288, 69)) ->S : Symbol(S, Decl(conditionalTypes1.ts, 289, 12)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 289, 14)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 289, 17)) ->S : Symbol(S, Decl(conditionalTypes1.ts, 289, 12)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 289, 17)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 289, 14)) +>If : Symbol(If, Decl(conditionalTypes1.ts, 292, 69)) +>S : Symbol(S, Decl(conditionalTypes1.ts, 293, 12)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 293, 14)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 293, 17)) +>S : Symbol(S, Decl(conditionalTypes1.ts, 293, 12)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 293, 17)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 293, 14)) type Omit = { [P in keyof T]: If, never, P>; }[keyof T]; ->Omit : Symbol(Omit, Decl(conditionalTypes1.ts, 289, 47)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 290, 14)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 290, 37)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 290, 14)) ->If : Symbol(If, Decl(conditionalTypes1.ts, 288, 69)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 287, 16)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 290, 14)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 290, 37)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 290, 37)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 290, 14)) +>Omit : Symbol(Omit, Decl(conditionalTypes1.ts, 293, 47)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 294, 14)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 294, 37)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 294, 14)) +>If : Symbol(If, Decl(conditionalTypes1.ts, 292, 69)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 291, 16)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 294, 14)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 294, 37)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 294, 37)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 294, 14)) type Omit2 = { [P in keyof T]: If, never, P>; }[keyof T]; ->Omit2 : Symbol(Omit2, Decl(conditionalTypes1.ts, 290, 94)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 291, 15)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 291, 32)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 291, 49)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 291, 15)) ->If : Symbol(If, Decl(conditionalTypes1.ts, 288, 69)) ->Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 287, 16)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 291, 15)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 291, 49)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 291, 32)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 291, 49)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 291, 15)) +>Omit2 : Symbol(Omit2, Decl(conditionalTypes1.ts, 294, 94)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 295, 15)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 295, 32)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 295, 49)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 295, 15)) +>If : Symbol(If, Decl(conditionalTypes1.ts, 292, 69)) +>Eq : Symbol(Eq, Decl(conditionalTypes1.ts, 291, 16)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 295, 15)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 295, 49)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 295, 32)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 295, 49)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 295, 15)) type A = Omit<{ a: void; b: never; }>; // 'a' ->A : Symbol(A, Decl(conditionalTypes1.ts, 291, 102)) ->Omit : Symbol(Omit, Decl(conditionalTypes1.ts, 289, 47)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 292, 19)) ->b : Symbol(b, Decl(conditionalTypes1.ts, 292, 28)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 295, 102)) +>Omit : Symbol(Omit, Decl(conditionalTypes1.ts, 293, 47)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 296, 19)) +>b : Symbol(b, Decl(conditionalTypes1.ts, 296, 28)) type B = Omit2<{ a: void; b: never; }>; // 'a' ->B : Symbol(B, Decl(conditionalTypes1.ts, 292, 42)) ->Omit2 : Symbol(Omit2, Decl(conditionalTypes1.ts, 290, 94)) ->a : Symbol(a, Decl(conditionalTypes1.ts, 293, 20)) ->b : Symbol(b, Decl(conditionalTypes1.ts, 293, 29)) +>B : Symbol(B, Decl(conditionalTypes1.ts, 296, 42)) +>Omit2 : Symbol(Omit2, Decl(conditionalTypes1.ts, 294, 94)) +>a : Symbol(a, Decl(conditionalTypes1.ts, 297, 20)) +>b : Symbol(b, Decl(conditionalTypes1.ts, 297, 29)) } // Repro from #21862 type OldDiff = ( ->OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 294, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 298, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 298, 30)) +>OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 298, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 302, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 302, 30)) & { [P in T]: P; } ->P : Symbol(P, Decl(conditionalTypes1.ts, 299, 9)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 298, 13)) ->P : Symbol(P, Decl(conditionalTypes1.ts, 299, 9)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 303, 9)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 302, 13)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 303, 9)) & { [P in U]: never; } ->P : Symbol(P, Decl(conditionalTypes1.ts, 300, 9)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 298, 30)) +>P : Symbol(P, Decl(conditionalTypes1.ts, 304, 9)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 302, 30)) & { [x: string]: never; } ->x : Symbol(x, Decl(conditionalTypes1.ts, 301, 9)) +>x : Symbol(x, Decl(conditionalTypes1.ts, 305, 9)) )[T]; ->T : Symbol(T, Decl(conditionalTypes1.ts, 298, 13)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 302, 13)) type NewDiff = T extends U ? never : T; ->NewDiff : Symbol(NewDiff, Decl(conditionalTypes1.ts, 302, 5)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 303, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 303, 15)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 303, 13)) ->U : Symbol(U, Decl(conditionalTypes1.ts, 303, 15)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 303, 13)) +>NewDiff : Symbol(NewDiff, Decl(conditionalTypes1.ts, 306, 5)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 307, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 307, 15)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 307, 13)) +>U : Symbol(U, Decl(conditionalTypes1.ts, 307, 15)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 307, 13)) interface A { ->A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 307, 45)) a: 'a'; ->a : Symbol(A.a, Decl(conditionalTypes1.ts, 304, 13)) +>a : Symbol(A.a, Decl(conditionalTypes1.ts, 308, 13)) } interface B1 extends A { ->B1 : Symbol(B1, Decl(conditionalTypes1.ts, 306, 1)) ->A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) +>B1 : Symbol(B1, Decl(conditionalTypes1.ts, 310, 1)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 307, 45)) b: 'b'; ->b : Symbol(B1.b, Decl(conditionalTypes1.ts, 307, 24)) +>b : Symbol(B1.b, Decl(conditionalTypes1.ts, 311, 24)) c: OldDiff; ->c : Symbol(B1.c, Decl(conditionalTypes1.ts, 308, 11)) ->OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 294, 1)) ->A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) +>c : Symbol(B1.c, Decl(conditionalTypes1.ts, 312, 11)) +>OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 298, 1)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 307, 45)) } interface B2 extends A { ->B2 : Symbol(B2, Decl(conditionalTypes1.ts, 310, 1)) ->A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) +>B2 : Symbol(B2, Decl(conditionalTypes1.ts, 314, 1)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 307, 45)) b: 'b'; ->b : Symbol(B2.b, Decl(conditionalTypes1.ts, 311, 24)) +>b : Symbol(B2.b, Decl(conditionalTypes1.ts, 315, 24)) c: NewDiff; ->c : Symbol(B2.c, Decl(conditionalTypes1.ts, 312, 11)) ->NewDiff : Symbol(NewDiff, Decl(conditionalTypes1.ts, 302, 5)) ->A : Symbol(A, Decl(conditionalTypes1.ts, 303, 45)) +>c : Symbol(B2.c, Decl(conditionalTypes1.ts, 316, 11)) +>NewDiff : Symbol(NewDiff, Decl(conditionalTypes1.ts, 306, 5)) +>A : Symbol(A, Decl(conditionalTypes1.ts, 307, 45)) } type c1 = B1['c']; // 'c' | 'b' ->c1 : Symbol(c1, Decl(conditionalTypes1.ts, 314, 1)) ->B1 : Symbol(B1, Decl(conditionalTypes1.ts, 306, 1)) +>c1 : Symbol(c1, Decl(conditionalTypes1.ts, 318, 1)) +>B1 : Symbol(B1, Decl(conditionalTypes1.ts, 310, 1)) type c2 = B2['c']; // 'c' | 'b' ->c2 : Symbol(c2, Decl(conditionalTypes1.ts, 315, 18)) ->B2 : Symbol(B2, Decl(conditionalTypes1.ts, 310, 1)) +>c2 : Symbol(c2, Decl(conditionalTypes1.ts, 319, 18)) +>B2 : Symbol(B2, Decl(conditionalTypes1.ts, 314, 1)) // Repro from #21929 type NonFooKeys1 = OldDiff; ->NonFooKeys1 : Symbol(NonFooKeys1, Decl(conditionalTypes1.ts, 316, 18)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 320, 17)) ->OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 294, 1)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 320, 17)) +>NonFooKeys1 : Symbol(NonFooKeys1, Decl(conditionalTypes1.ts, 320, 18)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 324, 17)) +>OldDiff : Symbol(OldDiff, Decl(conditionalTypes1.ts, 298, 1)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 324, 17)) type NonFooKeys2 = Exclude; ->NonFooKeys2 : Symbol(NonFooKeys2, Decl(conditionalTypes1.ts, 320, 61)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 321, 17)) +>NonFooKeys2 : Symbol(NonFooKeys2, Decl(conditionalTypes1.ts, 324, 61)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 325, 17)) >Exclude : Symbol(Exclude, Decl(lib.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes1.ts, 321, 17)) +>T : Symbol(T, Decl(conditionalTypes1.ts, 325, 17)) type Test1 = NonFooKeys1<{foo: 1, bar: 2, baz: 3}>; // "bar" | "baz" ->Test1 : Symbol(Test1, Decl(conditionalTypes1.ts, 321, 61)) ->NonFooKeys1 : Symbol(NonFooKeys1, Decl(conditionalTypes1.ts, 316, 18)) ->foo : Symbol(foo, Decl(conditionalTypes1.ts, 323, 26)) ->bar : Symbol(bar, Decl(conditionalTypes1.ts, 323, 33)) ->baz : Symbol(baz, Decl(conditionalTypes1.ts, 323, 41)) +>Test1 : Symbol(Test1, Decl(conditionalTypes1.ts, 325, 61)) +>NonFooKeys1 : Symbol(NonFooKeys1, Decl(conditionalTypes1.ts, 320, 18)) +>foo : Symbol(foo, Decl(conditionalTypes1.ts, 327, 26)) +>bar : Symbol(bar, Decl(conditionalTypes1.ts, 327, 33)) +>baz : Symbol(baz, Decl(conditionalTypes1.ts, 327, 41)) type Test2 = NonFooKeys2<{foo: 1, bar: 2, baz: 3}>; // "bar" | "baz" ->Test2 : Symbol(Test2, Decl(conditionalTypes1.ts, 323, 51)) ->NonFooKeys2 : Symbol(NonFooKeys2, Decl(conditionalTypes1.ts, 320, 61)) ->foo : Symbol(foo, Decl(conditionalTypes1.ts, 324, 26)) ->bar : Symbol(bar, Decl(conditionalTypes1.ts, 324, 33)) ->baz : Symbol(baz, Decl(conditionalTypes1.ts, 324, 41)) +>Test2 : Symbol(Test2, Decl(conditionalTypes1.ts, 327, 51)) +>NonFooKeys2 : Symbol(NonFooKeys2, Decl(conditionalTypes1.ts, 324, 61)) +>foo : Symbol(foo, Decl(conditionalTypes1.ts, 328, 26)) +>bar : Symbol(bar, Decl(conditionalTypes1.ts, 328, 33)) +>baz : Symbol(baz, Decl(conditionalTypes1.ts, 328, 41)) // Repro from #21729 interface Foo2 { foo: string; } ->Foo2 : Symbol(Foo2, Decl(conditionalTypes1.ts, 324, 51)) ->foo : Symbol(Foo2.foo, Decl(conditionalTypes1.ts, 328, 16)) +>Foo2 : Symbol(Foo2, Decl(conditionalTypes1.ts, 328, 51)) +>foo : Symbol(Foo2.foo, Decl(conditionalTypes1.ts, 332, 16)) interface Bar2 { bar: string; } ->Bar2 : Symbol(Bar2, Decl(conditionalTypes1.ts, 328, 31)) ->bar : Symbol(Bar2.bar, Decl(conditionalTypes1.ts, 329, 16)) +>Bar2 : Symbol(Bar2, Decl(conditionalTypes1.ts, 332, 31)) +>bar : Symbol(Bar2.bar, Decl(conditionalTypes1.ts, 333, 16)) type FooBar = Foo2 | Bar2; ->FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 329, 31)) ->Foo2 : Symbol(Foo2, Decl(conditionalTypes1.ts, 324, 51)) ->Bar2 : Symbol(Bar2, Decl(conditionalTypes1.ts, 328, 31)) +>FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 333, 31)) +>Foo2 : Symbol(Foo2, Decl(conditionalTypes1.ts, 328, 51)) +>Bar2 : Symbol(Bar2, Decl(conditionalTypes1.ts, 332, 31)) declare interface ExtractFooBar { } ->ExtractFooBar : Symbol(ExtractFooBar, Decl(conditionalTypes1.ts, 330, 26)) ->FB : Symbol(FB, Decl(conditionalTypes1.ts, 331, 32)) ->FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 329, 31)) +>ExtractFooBar : Symbol(ExtractFooBar, Decl(conditionalTypes1.ts, 334, 26)) +>FB : Symbol(FB, Decl(conditionalTypes1.ts, 335, 32)) +>FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 333, 31)) type Extracted = { ->Extracted : Symbol(Extracted, Decl(conditionalTypes1.ts, 331, 54)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) +>Extracted : Symbol(Extracted, Decl(conditionalTypes1.ts, 335, 54)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 337, 15)) [K in keyof Struct]: Struct[K] extends FooBar ? ExtractFooBar : Struct[K]; ->K : Symbol(K, Decl(conditionalTypes1.ts, 334, 5)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) ->K : Symbol(K, Decl(conditionalTypes1.ts, 334, 5)) ->FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 329, 31)) ->ExtractFooBar : Symbol(ExtractFooBar, Decl(conditionalTypes1.ts, 330, 26)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) ->K : Symbol(K, Decl(conditionalTypes1.ts, 334, 5)) ->Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 333, 15)) ->K : Symbol(K, Decl(conditionalTypes1.ts, 334, 5)) +>K : Symbol(K, Decl(conditionalTypes1.ts, 338, 5)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 337, 15)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 337, 15)) +>K : Symbol(K, Decl(conditionalTypes1.ts, 338, 5)) +>FooBar : Symbol(FooBar, Decl(conditionalTypes1.ts, 333, 31)) +>ExtractFooBar : Symbol(ExtractFooBar, Decl(conditionalTypes1.ts, 334, 26)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 337, 15)) +>K : Symbol(K, Decl(conditionalTypes1.ts, 338, 5)) +>Struct : Symbol(Struct, Decl(conditionalTypes1.ts, 337, 15)) +>K : Symbol(K, Decl(conditionalTypes1.ts, 338, 5)) } diff --git a/tests/baselines/reference/conditionalTypes1.types b/tests/baselines/reference/conditionalTypes1.types index 0d7624b07c8..538d8d75a07 100644 --- a/tests/baselines/reference/conditionalTypes1.types +++ b/tests/baselines/reference/conditionalTypes1.types @@ -941,6 +941,21 @@ function f22(x: T extends (infer U)[] ? U[] : never) { >0 : 0 } +function f23(x: T extends (infer U)[] ? U[] : never) { +>f23 : (x: T extends infer U[] ? U[] : never) => void +>T : T +>x : T extends infer U[] ? U[] : never +>T : T +>U : U +>U : U + + let e = x[0]; // string +>e : string +>x[0] : string +>x : T extends infer U[] ? U[] : never +>0 : 0 +} + // Repros from #21664 type Eq = T extends U ? U extends T ? true : false : false; From 79e5e79ef7724066889fbce97e9e6d6db4e746b5 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 28 Mar 2018 17:46:57 -0700 Subject: [PATCH 44/75] Update LKG --- lib/cs/diagnosticMessages.generated.json | 16 +- lib/de/diagnosticMessages.generated.json | 16 +- lib/enu/diagnosticMessages.generated.json.lcg | 238 +- lib/es/diagnosticMessages.generated.json | 16 +- lib/fr/diagnosticMessages.generated.json | 16 +- lib/it/diagnosticMessages.generated.json | 15 +- lib/ja/diagnosticMessages.generated.json | 16 +- lib/ko/diagnosticMessages.generated.json | 15 +- lib/lib.d.ts | 9233 ++++----- lib/lib.dom.d.ts | 9231 ++++----- lib/lib.es2016.full.d.ts | 9231 ++++----- lib/lib.es2017.full.d.ts | 9231 ++++----- lib/lib.es2018.d.ts | 2 + lib/lib.es2018.full.d.ts | 9234 ++++----- lib/lib.es2018.promise.d.ts | 32 + lib/lib.es2018.regexp.d.ts | 31 + lib/lib.es6.d.ts | 9231 ++++----- lib/lib.esnext.d.ts | 1 - lib/lib.esnext.full.d.ts | 9232 ++++----- lib/lib.webworker.d.ts | 1643 +- lib/pl/diagnosticMessages.generated.json | 15 +- lib/protocol.d.ts | 73 +- lib/pt-BR/diagnosticMessages.generated.json | 16 +- lib/ru/diagnosticMessages.generated.json | 16 +- lib/tr/diagnosticMessages.generated.json | 16 +- lib/tsc.js | 8555 +++++---- lib/tsserver.js | 14130 +++++++------- lib/tsserverlibrary.d.ts | 710 +- lib/tsserverlibrary.js | 15510 +++++++++------- lib/typescript.d.ts | 287 +- lib/typescript.js | 15184 ++++++++------- lib/typescriptServices.d.ts | 287 +- lib/typescriptServices.js | 15184 ++++++++------- lib/typingsInstaller.js | 2390 ++- lib/zh-CN/diagnosticMessages.generated.json | 16 +- lib/zh-TW/diagnosticMessages.generated.json | 16 +- 36 files changed, 75323 insertions(+), 63762 deletions(-) create mode 100644 lib/lib.es2018.promise.d.ts create mode 100644 lib/lib.es2018.regexp.d.ts diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 1b97ea68087..8ea577e3aa4 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Přistupující objekty musí být abstraktní nebo neabstraktní.", "Add_0_to_existing_import_declaration_from_1_90015": "Přidat {0} k existující deklaraci importu z {1}", "Add_async_modifier_to_containing_function_90029": "Přidat modifikátor async do obsahující funkce", + "Add_definite_assignment_assertion_to_property_0_95020": "Přidat kontrolní výraz jednoznačného přiřazení k vlastnosti {0}", "Add_index_signature_for_property_0_90017": "Přidat signaturu indexu pro vlastnost {0}", + "Add_initializer_to_property_0_95019": "Přidat inicializační výraz k vlastnosti {0}", "Add_missing_super_call_90001": "Přidat chybějící volání metody super()", "Add_this_to_unresolved_variable_90008": "Přidat k nerozpoznané proměnné this.", + "Add_undefined_type_to_property_0_95018": "Přidat typ undefined k vlastnosti {0}", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "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ě.", + "All_imports_in_import_declaration_are_unused_6192": "Žádné importy z deklarace importu se nepoužívají.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Povolte výchozí importy z modulů bez výchozího exportu. Nebude to mít vliv na generování kódu, jenom na kontrolu typů.", "Allow_javascript_files_to_be_compiled_6102": "Povolí kompilaci souborů javascript.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Když se zadá příznak --isolatedModules, nepovolují se ambientní výčty.", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Deklarace výčtu jdou sloučit jenom s oborem názvů nebo jinými deklaracemi výčtu.", "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.", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Soubor je modul CommonJS; může se převést na modul ES6.", "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}.", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "Import se může převést na výchozí import.", "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.", @@ -462,8 +469,10 @@ "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 neexistuje žádný parametr s tímto názvem.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Značka JSDoc @param má název {0}, ale žádný parametr s tímto názvem neexistuje. Musí odpovídat hodnotě arguments, pokud má typ pole.", "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 poznámku k typu nebo by za ní měly následovat značky @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.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Typy JSDoc se můžou přesunout na typy TypeScript.", "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.", @@ -476,6 +485,7 @@ "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_an_inline_JSX_factory_pragma_17017": "Při použití vložené direktivy pragma objektu pro vytváření JSX se nepodporuje fragment JSX.", "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.", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "Modul {0} nemá žádný exportovaný člen {1}. Neměli jste na mysli {2}?", "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 *.", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Vyvolá chybu u výrazů this s implikovaným typem any.", "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", "Remove_declaration_for_Colon_0_90004": "Odebrat deklaraci pro {0}", + "Remove_import_from_0_90005": "Odebrat import z {0}", "Replace_import_with_0_95015": "Nahradí import použitím: {0}.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Oznámí se chyby v případech fallthrough v příkazu switch.", @@ -657,7 +669,7 @@ "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.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Překlad pro modul {0} se našel v mezipaměti umístění {1}.", "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}.", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Tato funkce konstruktoru se může převést na deklaraci třídy.", "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á.", @@ -887,6 +900,7 @@ "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", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Určuje, jestli se místo vymazání obrazovky má zachovat zastaralý výstup konzoly v režimu sledování.", "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}()?", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index bff4663aa81..a8a0fbcccdb 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Beide Accessoren müssen abstrakt oder nicht abstrakt sein.", "Add_0_to_existing_import_declaration_from_1_90015": "\"{0}\" der vorhandenen Importdeklaration aus \"{1}\" hinzufügen", "Add_async_modifier_to_containing_function_90029": "Async-Modifizierer zur enthaltenden Funktion hinzufügen", + "Add_definite_assignment_assertion_to_property_0_95020": "Definitive Zuweisungsassertion zu Eigenschaft \"{0}\" hinzufügen", "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen", + "Add_initializer_to_property_0_95019": "Initialisierer zu Eigenschaft \"{0}\" hinzufügen", "Add_missing_super_call_90001": "Fehlenden super()-Aufruf hinzufügen", "Add_this_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"this.\" hinzufügen", + "Add_undefined_type_to_property_0_95018": "undefined-Typ zu Eigenschaft \"{0}\" hinzufügen", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "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.", + "All_imports_in_import_declaration_are_unused_6192": "Keiner der Importe in der Importdeklaration wird verwendet.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Standardimporte von Modulen ohne Standardexport zulassen. Dies wirkt sich nicht auf die Codeausgabe aus, lediglich auf die Typprüfung.", "Allow_javascript_files_to_be_compiled_6102": "Kompilierung von JavaScript-Dateien zulassen.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "const-Umgebungsenumerationen sind unzulässig, wenn das Flag \"-isolatedModules\" angegeben wird.", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enumerationsdeklarationen können nur mit Namespace- oder anderen Enumerationsdeklarationen zusammengeführt werden.", "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.", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Die Datei ist ein CommonJS-Modul, sie kann in ein ES6-Modul konvertiert werden.", "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}\".", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "Der Import kann in einen Standardimport konvertiert werden.", "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.", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Das JSDoc-Tag \"@param\" weist den Namen \"{0}\" auf, es ist jedoch kein Parameter dieses Namens vorhanden. Es läge eine Übereinstimmung mit \"arguments\" vor, wenn ein Arraytyp vorläge.", "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.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc-Typen können in TypeScript-Typen verschoben 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.", @@ -476,6 +485,7 @@ "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_an_inline_JSX_factory_pragma_17017": "Ein JSX-Fragment wird bei Verwendung eines Inline-JSX-Factory-Pragmas nicht unterstützt.", "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.", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "Das Modul \"{0}\" umfasst keinen exportierten Member \"{1}\". Meinten Sie \"{2}\"?", "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.", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Fehler für \"this\"-Ausdrücke mit einem impliziten any-Typ auslösen.", "Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.", "Remove_declaration_for_Colon_0_90004": "Deklaration entfernen für: {0}", + "Remove_import_from_0_90005": "Import aus \"{0}\" entfernen", "Replace_import_with_0_95015": "Ersetzen Sie den Import durch \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Fehler melden, wenn nicht alle Codepfade in der Funktion einen Wert zurückgeben.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Für FallTrough-Fälle in switch-Anweisung Fehler melden.", @@ -657,7 +669,7 @@ "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.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Die Auflösung für das Modul \"{0}\" wurde im Cache des Standorts \"{1}\" 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.", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Diese Konstruktorfunktion kann in eine Klassendeklaration konvertiert werden.", "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.", @@ -887,6 +900,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "Die Variablendeklarationsliste darf nicht leer sein.", "Version_0_6029": "Version {0}", "Watch_input_files_6005": "Eingabedateien überwachen.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Gibt an, ob eine veraltete Konsolenausgabe im Überwachungsmodus beibehalten wird, statt den Bildschirm zu löschen.", "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?", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index a7d77e9ac02..14d9bbb94b0 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -579,30 +579,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -639,6 +711,12 @@ + + + + + + @@ -927,6 +1005,12 @@ + + + + + + @@ -1329,6 +1413,24 @@ + + + + + + + + + + + + + + + + + + @@ -1527,6 +1629,18 @@ + + + + + + + + + + + + @@ -1635,6 +1749,12 @@ + + + + + + @@ -2289,6 +2409,12 @@ + + + + + + @@ -2313,6 +2439,12 @@ + + + + + + @@ -2385,6 +2517,12 @@ + + + + + + @@ -2511,6 +2649,18 @@ + + + + + + + + + + + + @@ -2565,6 +2715,12 @@ + + + + + + @@ -2625,6 +2781,12 @@ + + + + + + @@ -2691,6 +2853,12 @@ + + + + + + @@ -2793,6 +2961,12 @@ + + + + + + @@ -2805,6 +2979,12 @@ + + + + + + @@ -2877,6 +3057,12 @@ + + + + + + @@ -2985,6 +3171,12 @@ + + + + + + @@ -3063,6 +3255,12 @@ + + + + + + @@ -3351,6 +3549,12 @@ + + + + + + @@ -3615,6 +3819,12 @@ + + + + + + @@ -3921,6 +4131,12 @@ + + + + + + @@ -3963,9 +4179,9 @@ - + - + @@ -4197,6 +4413,12 @@ + + + + + + @@ -4767,6 +4989,12 @@ + + + + + + @@ -5343,6 +5571,12 @@ + + + + + + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index b44d3a14769..2d687fe0dd0 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Los descriptores de acceso deben ser los dos abstractos o los dos no abstractos.", "Add_0_to_existing_import_declaration_from_1_90015": "Agregar \"{0}\" a una declaración de importación existente desde \"{1}\"", "Add_async_modifier_to_containing_function_90029": "Agregar el modificador async a la función contenedora", + "Add_definite_assignment_assertion_to_property_0_95020": "Agregar aserción de asignación definitiva a la propiedad \"{0}\"", "Add_index_signature_for_property_0_90017": "Agregar una signatura de índice para la propiedad \"{0}\"", + "Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"", "Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta", "Add_this_to_unresolved_variable_90008": "Agregar \"this.\" a una variable no resuelta", + "Add_undefined_type_to_property_0_95018": "Agregar un tipo \"undefined\" a la propiedad \"{0}\"", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "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.", + "All_imports_in_import_declaration_are_unused_6192": "Todas las importaciones de la declaración de importación están sin utilizar.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permitir las importaciones predeterminadas de los módulos sin exportación predeterminada. Esto no afecta a la emisión de código, solo a la comprobación de tipos.", "Allow_javascript_files_to_be_compiled_6102": "Permitir que se compilen los archivos de JavaScript.", "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\".", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Las declaraciones de enumeración solo se pueden combinar con otras declaraciones de enumeración o de espacio de nombres.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Todas las declaraciones de enumeración 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.", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "El archivo es un módulo CommonJS; se puede convertir a un módulo ES6.", "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}'.", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "La importación puede convertirse a una importación predeterminada.", "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.", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "La etiqueta de JSDoc \"@param\" tiene el nombre \"{0}\", pero no hay ningún parámetro con ese nombre. Coincidiría con \"arguments\" si tuviera un tipo de matriz.", "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.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Los tipos de JSDoc pueden moverse a tipos de TypeScript.", "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.", @@ -476,6 +485,7 @@ "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_an_inline_JSX_factory_pragma_17017": "El fragmento JSX no se admite cuando se usa una pragma de fábrica JSX en línea", "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.", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "El módulo \"{0}\" no tiene ningún miembro exportado \"{1}\". ¿Pretendía utilizar \"{2}\"?", "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 *\".", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Generar un error en expresiones 'this' con un tipo 'any' implícito.", "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"", + "Remove_import_from_0_90005": "Quitar importación de \"{0}\"", "Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.", @@ -657,7 +669,7 @@ "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é.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La resolución del módulo \"{0}\" se encontró en la memoria caché de la ubicación \"{1}\".", "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}'.", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta función de constructor puede convertirse en una declaración de clase.", "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.", @@ -887,6 +900,7 @@ "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.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Si se debe mantener la salida de la consola no actualizada en el modo de inspección en lugar de borrar la pantalla.", "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}()\"?", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 7142fcb0d7d..1491f536b91 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Les accesseurs doivent être abstraits ou non abstraits.", "Add_0_to_existing_import_declaration_from_1_90015": "Ajouter '{0}' à la déclaration d'importation existante de \"{1}\"", "Add_async_modifier_to_containing_function_90029": "Ajouter le modificateur async dans la fonction conteneur", + "Add_definite_assignment_assertion_to_property_0_95020": "Ajouter une assertion d'assignation définie à la propriété '{0}'", "Add_index_signature_for_property_0_90017": "Ajouter une signature d'index pour la propriété '{0}'", + "Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'", "Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'", "Add_this_to_unresolved_variable_90008": "Ajouter 'this.' à la variable non résolue", + "Add_undefined_type_to_property_0_95018": "Ajouter un type 'undefined' à la propriété '{0}'", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "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.", + "All_imports_in_import_declaration_are_unused_6192": "Les importations de la déclaration d'importation ne sont pas toutes utilisées.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Autorisez les importations par défaut à partir des modules sans exportation par défaut. Cela n'affecte pas l'émission du code, juste le contrôle de type.", "Allow_javascript_files_to_be_compiled_6102": "Autorisez la compilation des fichiers JavaScript.", "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.", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Les déclarations enum ne peuvent fusionner qu'avec des espaces de noms ou d'autres déclarations enum.", "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.", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Le fichier est un module CommonJS ; il peut être converti en module ES6.", "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}'.", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "L'importation peut être convertie en importation par défaut.", "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.", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "La balise JSDoc '@param' se nomme '{0}', mais il n'existe aucun paramètre portant ce nom. Elle doit correspondre à 'arguments', si elle est de type tableau.", "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.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Les types JSDoc peuvent être déplacés vers les types TypeScript.", "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.", @@ -476,6 +485,7 @@ "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_an_inline_JSX_factory_pragma_17017": "Le fragment JSX n'est pas pris en charge quand vous utilisez un pragma de fabrique JSX inline", "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.", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "Le module '{0}' n'a aucun membre exporté '{1}'. Pensiez-vous plutôt à '{2}' ?", "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 *'.", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Déclenche une erreur sur les expressions 'this' avec un type 'any' implicite.", "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", "Remove_declaration_for_Colon_0_90004": "Supprimer la déclaration pour : '{0}'", + "Remove_import_from_0_90005": "Supprimer l'importation de '{0}'", "Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.", @@ -657,7 +669,7 @@ "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.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La résolution du module '{0}' a été trouvée dans le cache à l'emplacement '{1}'.", "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}'.", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Cette fonction constructeur peut être convertie en déclaration de classe.", "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.", @@ -887,6 +900,7 @@ "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.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Garder la sortie de console obsolète en mode espion au lieu d'effacer l'écran.", "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}()' ?", diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index 5bd0767bb28..bb468aa21d1 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Le funzioni di accesso devono essere tutte astratte o tutte non astratte.", "Add_0_to_existing_import_declaration_from_1_90015": "Aggiungere '{0}' alla dichiarazione di importazione esistente da \"{1}\"", "Add_async_modifier_to_containing_function_90029": "Aggiungere il modificatore async alla funzione contenitore", + "Add_definite_assignment_assertion_to_property_0_95020": "Aggiungere l'asserzione di assegnazione definita alla proprietà '{0}'", "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'", + "Add_initializer_to_property_0_95019": "Aggiungere l'inizializzatore alla proprietà '{0}'", "Add_missing_super_call_90001": "Aggiungere la chiamata mancante a 'super()'", "Add_this_to_unresolved_variable_90008": "Aggiungere 'this.' alla variabile non risolta", + "Add_undefined_type_to_property_0_95018": "Aggiungere il tipo 'undefined' alla proprietà '{0}'", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "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.", + "All_imports_in_import_declaration_are_unused_6192": "Tutte le importazioni nella dichiarazione di importazione sono inutilizzate.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Consente di eseguire importazioni predefinite da moduli senza esportazione predefinita. Non influisce sulla creazione del codice ma solo sul controllo dei tipi.", "Allow_javascript_files_to_be_compiled_6102": "Consente la compilazione di file JavaScript.", "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'.", @@ -379,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Il file è un modulo CommonJS; può essere convertito in un modulo ES6.", "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}'.", @@ -425,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "L'importazione può essere convertita in un'importazione predefinita.", "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.", @@ -463,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Il nome del tag '@param' di JSDoc è '{0}', ma non esiste alcun parametro con questo nome. Se contenesse un tipo matrice, corrisponderebbe ad 'arguments'.", "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.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "I tipi JSDoc possono essere convertiti in tipi TypeScript.", "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.", @@ -477,6 +485,7 @@ "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_an_inline_JSX_factory_pragma_17017": "Il frammento JSX non è supportato quando si usa una direttiva pragma factory JSX inline", "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.", @@ -508,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "Per il modulo '{0}' non esiste alcun membro esportato '{1}'. Si intendeva '{2}'?", "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 *'.", @@ -651,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Genera un errore in caso di espressioni 'this con un tipo 'any' implicito.", "Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.", "Remove_declaration_for_Colon_0_90004": "Rimuovere la dichiarazione per '{0}'", + "Remove_import_from_0_90005": "Rimuovere l'importazione da '{0}'", "Replace_import_with_0_95015": "Sostituire l'importazione con '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Segnala l'errore quando non tutti i percorsi del codice nella funzione restituiscono un valore.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Segnala errori per i casi di fallthrough nell'istruzione switch.", @@ -658,7 +669,7 @@ "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.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La risoluzione per il modulo '{0}' è stata trovata nella cache dal percorso '{1}'.", "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}'.", @@ -792,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Questa funzione del costruttore può essere convertita in una dichiarazione di classe.", "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.", @@ -888,6 +900,7 @@ "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.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Indica se mantenere l'output della console obsoleto in modalità espressione di controllo invece di pulire lo schermo.", "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}()'?", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index b1c1cf848f6..4c6ab38c57a 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "アクセサーはどちらも抽象または非抽象である必要があります。", "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\" から既存のインポート宣言に '{0}' を追加する", "Add_async_modifier_to_containing_function_90029": "含まれている関数に async 修飾子を追加します", + "Add_definite_assignment_assertion_to_property_0_95020": "プロパティ '{0}' に限定代入アサーションを追加します", "Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加する", + "Add_initializer_to_property_0_95019": "プロパティ '{0}' に初期化子を追加します", "Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加する", "Add_this_to_unresolved_variable_90008": "'this.' を未解決の変数に追加する", + "Add_undefined_type_to_property_0_95018": "プロパティ '{0}' に '未定義' の型を追加します", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json ファイルを追加すると、TypeScript ファイルと JavaScript ファイルの両方を含むプロジェクトを整理できます。詳細については、https://aka.ms/tsconfig をご覧ください。", "Additional_Checks_6176": "追加のチェック", "Advanced_Options_6178": "詳細オプション", "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' のすべての宣言には、同一の修飾子が必要です。", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' のすべての宣言には、同一の型パラメーターがある必要があります。", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象メソッドの宣言はすべて連続している必要があります。", + "All_imports_in_import_declaration_are_unused_6192": "インポート宣言内のインポートはすべて未使用です。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "既定のエクスポートがないモジュールからの既定のインポートを許可します。これは、型チェックのみのため、コード生成には影響を与えません。", "Allow_javascript_files_to_be_compiled_6102": "javascript ファイルのコンパイルを許可します。", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' フラグが指定されている場合、アンビエント const 列挙型は使用できません。", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "列挙型の宣言は、名前空間または他の列挙型の宣言とのみマージできます。", "Enum_declarations_must_all_be_const_or_non_const_2473": "列挙型宣言は、すべてが定数、またはすべてが非定数でなければなりません。", "Enum_member_expected_1132": "列挙型メンバーが必要です。", "Enum_member_must_have_initializer_1061": "列挙型メンバーには初期化子が必要です。", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "ファイルは CommonJS モジュールです。ES6 モジュールに変換される可能性があります。", "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}'。", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "インポートは既定のインポートに変換される可能性があります。", "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": "インポートはモジュールの拡張では許可されていません。外側の外部モジュールに移動することを検討してください。", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' タグに名前 '{0}' が指定されていますが、その名前のパラメーターはありません。配列型があった場合は、'arguments' と一致したはずです。", "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 の種類は、ドキュメント コメント内でのみ使用できます。", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc の種類は TypeScript の種類に移行される可能性があります。", "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}' には対応する終了タグがありません。", @@ -476,6 +485,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 要素に同じ名前の複数の属性を指定することはできません。", "JSX_expressions_must_have_one_parent_element_2657": "JSX 式には 1 つの親要素が必要です。", "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX フラグメントには対応する終了タグがありません。", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ プラグマの使用時にサポートされていません", "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "--jsxFactory を使う場合、JSX フラグメントはサポートされません", "JSX_spread_child_must_be_an_array_type_2609": "JSX スプレッドの子は、配列型でなければなりません。", "Jump_target_cannot_cross_function_boundary_1107": "ジャンプ先は関数の境界を越えることはできません。", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "モジュール '{0}' にエクスポートされたメンバー '{1}' が含まれていません。候補: '{2}'", "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 *' は併用できません。", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。", "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除する: '{0}'", + "Remove_import_from_0_90005": "'{0}' からのインポートを削除", "Replace_import_with_0_95015": "インポートを '{0}' に置換します。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch ステートメントに case のフォールスルーがある場合にエラーを報告します。", @@ -657,7 +669,7 @@ "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}' の解決がキャッシュに見つかりました。", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "モジュール '{0}' の解決が場所 '{1}' のキャッシュに見つかりました。", "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}' を解決しています。", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "このコンストラクター関数はクラス宣言に変換される可能性があります。", "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": "末尾にコンマは使用できません。", @@ -887,6 +900,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "変数宣言リストを空にすることはできません。", "Version_0_6029": "バージョン {0}", "Watch_input_files_6005": "入力ファイルを監視します。", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "画面をクリアする代わりに、古くなったコンソール出力をウォッチ モードで保持するかどうか。", "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}()' を書き込むつもりでしたか?", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index f0b94025468..77ef9cf6408 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "접근자는 모두 추상이거나 비추상이어야 합니다.", "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\"에서 기존 가져오기 선언에 '{0}' 추가", "Add_async_modifier_to_containing_function_90029": "포함된 함수에 async 한정자 추가", + "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' 속성에 한정된 할당 어설션 추가", "Add_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처 추가", + "Add_initializer_to_property_0_95019": "'{0}' 속성에 이니셜라이저 추가", "Add_missing_super_call_90001": "누락된 'super()' 호출 추가", "Add_this_to_unresolved_variable_90008": "확인되지 않은 변수에 'this.' 추가", + "Add_undefined_type_to_property_0_95018": "'{0}' 속성에 '정의되지 않은' 형식 추가", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json 파일을 추가하면 TypeScript 파일과 JavaScript 파일이 둘 다 포함된 프로젝트를 정리하는 데 도움이 됩니다. 자세한 내용은 https://aka.ms/tsconfig를 참조하세요.", "Additional_Checks_6176": "추가 검사", "Advanced_Options_6178": "고급 옵션", "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}'의 모든 선언에는 동일한 한정자가 있어야 합니다.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}'의 모든 선언에는 동일한 형식 매개 변수가 있어야 합니다.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "추상 메서드의 모든 선언은 연속적이어야 합니다.", + "All_imports_in_import_declaration_are_unused_6192": "가져오기 선언의 모든 가져오기가 사용되지 않습니다.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "기본 내보내기가 없는 모듈에서 기본 가져오기를 허용합니다. 여기서는 코드 내보내기에는 영향을 주지 않고 형식 검사만 합니다.", "Allow_javascript_files_to_be_compiled_6102": "Javascript 파일을 컴파일하도록 허용합니다.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' 플래그가 제공된 경우 앰비언트 const 열거형이 허용되지 않습니다.", @@ -379,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "파일이 CommonJS 모듈입니다. ES6 모듈로 변환될 수 있습니다.", "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}'.", @@ -425,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "가져오기가 기본 가져오기로 변환될 수 있습니다.", "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": "가져오기는 모듈 확대에서 허용되지 않습니다. 내보내기를 바깥쪽 외부 모듈로 이동하세요.", @@ -463,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "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 유형은 문서 주석 내에서만 사용될 수 있습니다.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 형식이 TypeScript 형식으로 이동될 수 있습니다.", "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}'에 닫는 태그가 없습니다.", @@ -477,6 +485,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 요소에 이름이 같은 특성을 여러 개 사용할 수 없습니다.", "JSX_expressions_must_have_one_parent_element_2657": "JSX 식에는 부모 요소가 하나 있어야 합니다.", "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 조각에 닫는 태그가 없습니다.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "인라인 JSX 팩터리 pragma를 사용할 때에는 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": "점프 대상은 함수 경계를 벗어날 수 없습니다.", @@ -508,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "모듈 '{0}'에 내보낸 멤버 '{1}'이(가) 없습니다. '{2}'이(가) 아닌지 확인하세요.", "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 *'와 함께 사용할 수 없습니다.", @@ -651,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언 제거", + "Remove_import_from_0_90005": "'{0}'에서 가져오기 제거", "Replace_import_with_0_95015": "가져오기를 '{0}'(으)로 바꿉니다.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch 문의 fallthrough case에 대한 오류를 보고합니다.", @@ -658,7 +669,7 @@ "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}' 모듈에 대한 해결을 캐시에서 찾았습니다.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' 모듈에 대한 해결을 '{1}' 위치의 캐시에서 찾았습니다.", "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}'을(를) 확인하는 중입니다.", @@ -792,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "이 생성자 함수는 클래스 선언으로 변환될 수 있습니다.", "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": "후행 쉼표는 허용되지 않습니다.", @@ -888,6 +900,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "변수 선언 목록은 비워 둘 수 없습니다.", "Version_0_6029": "버전 {0}", "Watch_input_files_6005": "조사식 입력 파일입니다.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "화면을 지우지 않고, 감시 모드의 오래된 콘솔 출력을 유지할지 여부입니다.", "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}()'을(를) 작성하시겠습니까?", diff --git a/lib/lib.d.ts b/lib/lib.d.ts index b489fdcd368..d266bf37851 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -265,7 +265,7 @@ interface Function { * @param thisArg The object to be used as the this object. * @param argArray A set of arguments to be passed to the function. */ - apply(this: Function, thisArg: any, argArray?: Readonly>): any; + apply(this: Function, thisArg: any, argArray?: any): any; /** * Calls a method of an object, substituting another object for the current object. @@ -4155,7 +4155,6 @@ interface Date { } - ///////////////////////////// /// DOM APIs ///////////////////////////// @@ -4168,10 +4167,49 @@ interface Account { rpDisplayName: string; } +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + interface Algorithm { name: string; } +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + interface AnimationEventInit extends EventInit { animationName?: string; elapsedTime?: number; @@ -4180,10 +4218,71 @@ interface AnimationEventInit extends EventInit { interface AssertionOptions { allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioContextInfo { + currentTime?: number; + sampleRate?: number; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioParamDescriptor { + defaultValue?: number; + maxValue?: number; + minValue?: number; + name?: string; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: number; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface ByteLengthChunk { + byteLength?: number; +} + interface CacheQueryOptions { cacheName?: string; ignoreMethod?: boolean; @@ -4191,6 +4290,14 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + interface ClientData { challenge: string; extensions?: WebAuthnExtensions; @@ -4200,6 +4307,12 @@ interface ClientData { tokenBinding?: string; } +interface ClientQueryOptions { + includeReserved?: boolean; + includeUncontrolled?: boolean; + type?: ClientTypes; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; @@ -4214,6 +4327,10 @@ interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation arrayOfDomainStrings?: string[]; } +interface ConstantSourceOptions { + offset?: number; +} + interface ConstrainBooleanParameters { exact?: boolean; ideal?: boolean; @@ -4239,10 +4356,27 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + interface CustomEventInit extends EventInit { detail?: T; } +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + interface DeviceAccelerationDict { x?: number | null; y?: number | null; @@ -4273,18 +4407,39 @@ interface DeviceRotationRateDict { gamma?: number | null; } -interface DOMRectInit { - height?: number; - width?: number; - x?: number; - y?: number; -} - interface DoubleRange { max?: number; min?: number; } +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: string; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: string | Algorithm; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -4294,9 +4449,13 @@ interface ErrorEventInit extends EventInit { } interface EventInit { - scoped?: boolean; bubbles?: boolean; cancelable?: boolean; + scoped?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; } interface EventModifierInit extends UIEventInit { @@ -4321,6 +4480,24 @@ interface ExceptionInformation { domain?: string | null; } +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: object | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + request: Request; + reservedClientId?: string; + targetClientId?: string; +} + interface FocusEventInit extends UIEventInit { relatedTarget?: EventTarget | null; } @@ -4340,8 +4517,12 @@ interface FocusNavigationOrigin { originWidth?: number; } +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + interface GamepadEventInit extends EventInit { - gamepad?: Gamepad | null; + gamepad?: Gamepad; } interface GetNotificationOptions { @@ -4349,8 +4530,29 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string | null; - oldURL?: string | null; + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: string | Algorithm; + info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface HmacImportParams extends Algorithm { + hash: string | Algorithm; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: string | Algorithm; + length?: number; } interface IDBIndexParameters { @@ -4363,10 +4565,15 @@ interface IDBObjectStoreParameters { keyPath?: string | string[]; } +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + interface IntersectionObserverEntryInit { - isIntersecting: boolean; boundingClientRect: DOMRectInit; intersectionRect: DOMRectInit; + isIntersecting: boolean; rootBounds: DOMRectInit; target: Element; time: number; @@ -4378,8 +4585,29 @@ interface IntersectionObserverInit { threshold?: number | number[]; } +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + interface KeyAlgorithm { - name?: string; + name: string; } interface KeyboardEventInit extends EventModifierInit { @@ -4394,125 +4622,6 @@ interface LongRange { 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; @@ -4603,6 +4712,16 @@ interface MSCredentialSpec { type: MSCredentialType; } +interface MSDCCEventInit extends EventInit { + maxFr?: number; + maxFs?: number; +} + +interface MSDSHEventInit extends EventInit { + sources?: number[]; + timestamp?: number; +} + interface MSDelay { roundTrip?: number; roundTripMax?: number; @@ -4620,7 +4739,13 @@ interface MSDescription extends RTCStats { interface MSFIDOCredentialParameters extends MSCredentialParameters { algorithm?: string | Algorithm; - authenticators?: AAGUID[]; + authenticators?: string[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSIceWarningFlags { @@ -4648,12 +4773,6 @@ interface MSIceWarningFlags { useCandidateChecksFailed?: boolean; } -interface MSIPAddressInfo { - ipAddr?: string; - manufacturerMacAddrMask?: string; - port?: number; -} - interface MSJitter { interArrival?: number; interArrivalMax?: number; @@ -4682,8 +4801,8 @@ interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; - interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; + interfaceTypeWireless?: boolean; } interface MSOutboundNetwork extends MSNetwork { @@ -4720,8 +4839,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { iceRole?: RTCIceRole; iceWarningFlags?: MSIceWarningFlags; interfaces?: MSNetworkInterfaceType; - localAddress?: string; localAddrType?: MSIceAddrType; + localAddress?: string; localInterface?: MSNetworkInterfaceType; localMR?: string; localMRTCPPort?: number; @@ -4735,8 +4854,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { portRangeMax?: number; portRangeMin?: number; protocol?: RTCIceProtocol; - remoteAddress?: string; remoteAddrType?: MSIceAddrType; + remoteAddress?: string; remoteMR?: string; remoteMRTCPPort?: number; remoteSite?: string; @@ -4805,6 +4924,133 @@ interface MSVideoSendPayload extends MSVideoPayload { sendVideoStreamsMax?: number; } +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +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 MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + channelCount?: number | ConstrainLongRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + displaySurface?: string | string[] | ConstrainDOMStringParameters; + echoCancellation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + latency?: number | ConstrainDoubleRange; + logicalSurface?: boolean | ConstrainBooleanParameters; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +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 { + channel?: string; + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: Window | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + interface MsZoomToOptions { animate?: string; contentX?: number; @@ -4824,8 +5070,14 @@ interface MutationObserverInit { subtree?: boolean; } +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; +} + interface NotificationOptions { body?: string; + data?: any; dir?: NotificationDirection; icon?: string; lang?: string; @@ -4836,18 +5088,49 @@ interface ObjectURLOptions { oneTimeOnly?: boolean; } +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + interface PaymentCurrencyAmount { currency: string; currencySystem?: string; value: string; } -interface PaymentDetails { +interface PaymentDetailsBase { displayItems?: PaymentItem[]; - error?: string; modifiers?: PaymentDetailsModifier[]; shippingOptions?: PaymentShippingOption[]; - total?: PaymentItem; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; } interface PaymentDetailsModifier { @@ -4857,6 +5140,11 @@ interface PaymentDetailsModifier { total?: PaymentItem; } +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + total?: PaymentItem; +} + interface PaymentItem { amount: PaymentCurrencyAmount; label: string; @@ -4886,10 +5174,21 @@ interface PaymentShippingOption { selected?: boolean; } +interface Pbkdf2Params extends Algorithm { + hash: string | Algorithm; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + interface PeriodicWaveConstraints { disableNormalization?: boolean; } +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[]; + real?: number[]; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -4917,35 +5216,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface PushEventInit extends ExtendableEventInit { + data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | null; + applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; userVisibleOnly?: boolean; } -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - signal?: AbortSignal; - body?: Blob | BufferSource | FormData | string | null; - 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 QueuingStrategy { + highWaterMark?: number; + size?: WritableStreamChunkCallback; } interface RTCConfiguration { @@ -4955,6 +5242,10 @@ interface RTCConfiguration { peerIdentity?: string; } +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + interface RTCDtlsFingerprint { algorithm?: string; value?: string; @@ -4965,10 +5256,6 @@ interface RTCDtlsParameters { role?: RTCDtlsRole; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCIceCandidateAttributes extends RTCStats { addressSourceUrl?: string; candidateType?: RTCStatsIceCandidateType; @@ -4996,8 +5283,8 @@ interface RTCIceCandidateDictionary { interface RTCIceCandidateInit { candidate?: string; - sdpMid?: string; sdpMLineIndex?: number; + sdpMid?: string; } interface RTCIceCandidatePair { @@ -5052,13 +5339,13 @@ interface RTCMediaStreamTrackStats extends RTCStats { echoReturnLoss?: number; echoReturnLossEnhancement?: number; frameHeight?: number; + frameWidth?: number; framesCorrupted?: number; framesDecoded?: number; framesDropped?: number; framesPerSecond?: number; framesReceived?: number; framesSent?: number; - frameWidth?: number; remoteSource?: boolean; ssrcIds?: string[]; trackIdentifier?: string; @@ -5082,6 +5369,20 @@ interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + mediaType?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtcpFeedback { parameter?: string; type?: string; @@ -5103,9 +5404,9 @@ interface RTCRtpCapabilities { interface RTCRtpCodecCapability { clockRate?: number; kind?: string; - maxptime?: number; maxSpatialLayers?: number; maxTemporalLayers?: number; + maxptime?: number; name?: string; numChannels?: number; options?: any; @@ -5122,7 +5423,7 @@ interface RTCRtpCodecParameters { name?: string; numChannels?: number; parameters?: any; - payloadType?: any; + payloadType?: number; ptime?: number; rtcpFeedback?: RTCRtcpFeedback[]; } @@ -5181,19 +5482,6 @@ 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; @@ -5245,8 +5533,70 @@ interface RTCTransportStats extends RTCStats { selectedCandidatePairId?: string; } +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: string | Algorithm; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: string | Algorithm; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + interface ScopedCredentialDescriptor { - id: BufferSource; + id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; transports?: Transport[]; type: ScopedCredentialType; } @@ -5254,7 +5604,7 @@ interface ScopedCredentialDescriptor { interface ScopedCredentialOptions { excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } @@ -5263,6 +5613,19 @@ interface ScopedCredentialParameters { type: ScopedCredentialType; } +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; @@ -5273,11 +5636,16 @@ interface ServiceWorkerMessageEventInit extends EventInit { interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; + charLength?: number; elapsedTime?: number; name?: string; utterance?: SpeechSynthesisUtterance | null; } +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + interface StoreExceptionsInformation extends ExceptionInformation { detailURI?: string | null; explanationString?: string | null; @@ -5288,6 +5656,20 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat arrayOfDomainStrings?: string[]; } +interface SyncEventInit extends ExtendableEventInit { + lastChance?: boolean; + tag: string; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } @@ -5302,14 +5684,43 @@ interface UIEventInit extends EventInit { view?: Window | null; } +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCallback; + start: WritableStreamDefaultControllerCallback; + write?: WritableStreamChunkCallback; +} + +interface VRDisplayEventInit extends EventInit { + display: VRDisplay; + reason?: VRDisplayEventReason; +} + +interface VRLayer { + leftBounds?: number[] | null; + rightBounds?: number[] | null; + source?: HTMLCanvasElement | null; +} + +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[]; + oversample?: OverSampleType; +} + interface WebAuthnExtensions { } interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; antialias?: boolean; depth?: boolean; + failIfMajorPerformanceCaveat?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; stencil?: boolean; @@ -5336,6 +5747,67 @@ type WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMErr type WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; }; +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 AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + 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 AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -5353,23 +5825,39 @@ declare var 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; +interface Animation { + currentTime: number | null; + effect: AnimationEffectReadOnly; + readonly finished: Promise; + id: string; + readonly pending: boolean; + readonly playState: "idle" | "running" | "paused" | "finished"; + playbackRate: number; + readonly ready: Promise; + startTime: number; + timeline: AnimationTimeline; + cancel(): void; + finish(): void; + oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; + onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; + pause(): void; + play(): void; + reverse(): void; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; }; +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + 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: { @@ -5377,6 +5865,43 @@ declare var AnimationEvent: { new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; }; +interface AnimationKeyFrame { + easing?: string | string[]; + offset?: number | null | (number | null)[]; + [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; +} + +interface AnimationOptions { + delay?: number; + direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; + duration?: number; + easing?: string; + endDelay?: number; + fill?: "none" | "forwards" | "backwards" | "both"| "auto"; + id?: string; + iterationStart?: number; + iterations?: number; +} + +interface AnimationPlaybackEvent extends Event { + readonly currentTime: number | null; + readonly timelineTime: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +interface AnimationTimeline { + readonly currentTime: number | null; +} + interface ApplicationCacheEventMap { "cached": Event; "checking": Event; @@ -5389,14 +5914,14 @@ interface ApplicationCacheEventMap { } 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; + oncached: ((this: ApplicationCache, ev: Event) => any) | null; + onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + onerror: ((this: ApplicationCache, ev: Event) => any) | null; + onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; readonly status: number; abort(): void; swapCache(): void; @@ -5424,9 +5949,13 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; +interface AssignedNodesOptions { + flatten?: boolean; +} + interface Attr extends Node { readonly name: string; - readonly ownerElement: Element; + readonly ownerElement: Element | null; readonly prefix: string | null; readonly specified: boolean; value: string; @@ -5453,7 +5982,7 @@ declare var AudioBuffer: { }; interface AudioBufferSourceNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface AudioBufferSourceNode extends AudioNode { @@ -5462,7 +5991,7 @@ interface AudioBufferSourceNode extends AudioNode { loop: boolean; loopEnd: number; loopStart: number; - onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null; readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; @@ -5485,7 +6014,7 @@ interface AudioContextBase extends EventTarget { readonly currentTime: number; readonly destination: AudioDestinationNode; readonly listener: AudioListener; - onstatechange: (this: AudioContext, ev: Event) => any; + onstatechange: ((this: AudioContext, ev: Event) => any) | null; readonly sampleRate: number; readonly state: AudioContextState; close(): Promise; @@ -5535,10 +6064,15 @@ declare var AudioDestinationNode: { }; interface AudioListener { + /** @deprecated */ dopplerFactor: number; + /** @deprecated */ speedOfSound: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -5556,9 +6090,13 @@ interface AudioNode extends EventTarget { 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; + disconnect(): void; + disconnect(output: number): void; + disconnect(destination: AudioNode): void; + disconnect(destination: AudioNode, output: number): void; + disconnect(destination: AudioNode, output: number, input: number): void; + disconnect(destination: AudioParam): void; + disconnect(destination: AudioParam, output: number): void; } declare var AudioNode: { @@ -5569,12 +6107,12 @@ declare var AudioNode: { interface AudioParam { readonly defaultValue: number; value: number; - cancelScheduledValues(startTime: number): AudioParam; + cancelScheduledValues(cancelTime: 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; + setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam; } declare var AudioParam: { @@ -5615,9 +6153,9 @@ interface AudioTrackListEventMap { 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; + onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: AudioTrackList, ev: Event) => any) | null; + onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -5650,11 +6188,33 @@ declare var BeforeUnloadEvent: { new(): BeforeUnloadEvent; }; +interface BhxBrowser { + readonly lastError: DOMException; + checkMatchesGlobExpression(pattern: string, value: string): boolean; + checkMatchesUriExpression(pattern: string, value: string): boolean; + clearLastError(): void; + currentWindowId(): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + getThisAddress(): any; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericListenerHandler(eventHandler: Function): void; + setLastError(parameters: string): void; + webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void; +} + +declare var BhxBrowser: { + prototype: BhxBrowser; + new(): BhxBrowser; +}; + interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; - readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -5677,113 +6237,50 @@ declare var 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; +interface BlobPropertyBag { + endings?: string; + type?: string; } -declare var Cache: { - prototype: Cache; - new(): Cache; +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + close(): void; + postMessage(message: any): 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 CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): Promise; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; } -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -}; - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; +interface ByteLengthQueuingStrategy { + highWaterMark: number; + size(chunk?: any): number; } -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; +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -5794,190 +6291,8 @@ declare var 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 { + escape(value: string): string; supports(property: string, value?: string): boolean; } declare var CSS: CSS; @@ -6037,7 +6352,7 @@ interface CSSKeyframesRule extends CSSRule { name: string; appendRule(rule: string): void; deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; + findRule(rule: string): CSSKeyframeRule | null; } declare var CSSKeyframesRule: { @@ -6078,14 +6393,14 @@ declare var CSSPageRule: { interface CSSRule { cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; + readonly parentRule: CSSRule | null; + readonly parentStyleSheet: CSSStyleSheet | null; 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 KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -6101,8 +6416,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAME_RULE: number; readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -6114,7 +6429,7 @@ declare var CSSRule: { interface CSSRuleList { readonly length: number; - item(index: number): CSSRule; + item(index: number): CSSRule | null; [index: number]: CSSRule; } @@ -6126,8 +6441,8 @@ declare var CSSRuleList: { interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignmentBaseline: string | null; alignSelf: string | null; + alignmentBaseline: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -6203,9 +6518,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; - columns: string | null; columnSpan: string | null; columnWidth: any; + columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -6239,11 +6554,32 @@ interface CSSStyleDeclaration { fontStyle: string | null; fontVariant: string | null; fontWeight: string | null; + gap: string | null; glyphOrientationHorizontal: string | null; glyphOrientationVertical: string | null; + grid: string | null; + gridArea: string | null; + gridAutoColumns: string | null; + gridAutoFlow: string | null; + gridAutoRows: string | null; + gridColumn: string | null; + gridColumnEnd: string | null; + gridColumnGap: string | null; + gridColumnStart: string | null; + gridGap: string | null; + gridRow: string | null; + gridRowEnd: string | null; + gridRowGap: string | null; + gridRowStart: string | null; + gridTemplate: string | null; + gridTemplateAreas: string | null; + gridTemplateColumns: string | null; + gridTemplateRows: string | null; height: string | null; imeMode: string | null; justifyContent: string | null; + justifyItems: string | null; + justifySelf: string | null; kerning: string | null; layoutGrid: string | null; layoutGridChar: string | null; @@ -6270,29 +6606,30 @@ interface CSSStyleDeclaration { markerMid: string | null; markerStart: string | null; mask: string | null; + maskImage: 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; + msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumns: string | null; msGridColumnSpan: any; + msGridColumns: string | null; msGridRow: any; msGridRowAlign: string | null; - msGridRows: string | null; msGridRowSpan: any; + msGridRows: string | null; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -6321,6 +6658,8 @@ interface CSSStyleDeclaration { msWrapFlow: string; msWrapMargin: any; msWrapThrough: string; + objectFit: string | null; + objectPosition: string | null; opacity: string | null; order: string | null; orphans: string | null; @@ -6341,13 +6680,16 @@ interface CSSStyleDeclaration { pageBreakBefore: string | null; pageBreakInside: string | null; readonly parentRule: CSSRule; + penAction: string | null; perspective: string | null; perspectiveOrigin: string | null; pointerEvents: string | null; position: string | null; quotes: string | null; + resize: string | null; right: string | null; rotate: string | null; + rowGap: string | null; rubyAlign: string | null; rubyOverhang: string | null; rubyPosition: string | null; @@ -6366,6 +6708,7 @@ interface CSSStyleDeclaration { textAlign: string | null; textAlignLast: string | null; textAnchor: string | null; + textCombineUpright: string | null; textDecoration: string | null; textIndent: string | null; textJustify: string | null; @@ -6387,6 +6730,7 @@ interface CSSStyleDeclaration { transitionTimingFunction: string | null; translate: string | null; unicodeBidi: string | null; + userSelect: string | null; verticalAlign: string | null; visibility: string | null; webkitAlignContent: string | null; @@ -6428,9 +6772,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; - webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; + webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -6469,13 +6813,11 @@ interface CSSStyleDeclaration { 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; + setProperty(propertyName: string, value: string | null, priority?: string | null): void; [index: number]: string; } @@ -6485,7 +6827,6 @@ declare var CSSStyleDeclaration: { }; interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; selectorText: string; readonly style: CSSStyleDeclaration; } @@ -6497,21 +6838,32 @@ declare var CSSStyleRule: { interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; + /** @deprecated */ cssText: string; + /** @deprecated */ readonly id: string; + /** @deprecated */ readonly imports: StyleSheetList; + /** @deprecated */ readonly isAlternate: boolean; + /** @deprecated */ readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; + readonly ownerRule: CSSRule | null; + /** @deprecated */ readonly owningElement: Element; - readonly pages: StyleSheetPageList; + /** @deprecated */ + readonly pages: any; + /** @deprecated */ readonly readOnly: boolean; readonly rules: CSSRuleList; + /** @deprecated */ addImport(bstrURL: string, lIndex?: number): number; + /** @deprecated */ 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; + /** @deprecated */ removeImport(lIndex: number): void; removeRule(lIndex: number): void; } @@ -6529,6 +6881,380 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; +interface Cache { + add(request: Request | string): Promise; + addAll(requests: (Request | string)[]): Promise; + delete(request: Request | string, options?: CacheQueryOptions): Promise; + keys(request?: Request | string, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + matchAll(request?: Request | string, options?: CacheQueryOptions): Promise; + put(request: Request | string, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface Canvas2DContextAttributes { + alpha?: boolean; + storage?: boolean; + willReadFrequently?: boolean; + [attribute: string]: boolean | string | undefined; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +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; + arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: 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 CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends 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; + mozImageSmoothingEnabled: boolean; + msFillRule: CanvasFillRule; + oImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + webkitImageSmoothingEnabled: 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; + drawFocusIfNeeded(path: Path2D, 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; + isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(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 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 ChildNode { + remove(): void; +} + +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 ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(data?: string): 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 ComputedTimingProperties { + activeDuration: number; + currentIteration: number | null; + endTime: number; + localTime: number | null; + progress: number | null; +} + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: 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; + markTimeline(label?: string): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ContentScriptGlobalScope extends EventTarget { + readonly msContentScript: ExtensionScriptApis; + readonly window: Window; +} + +declare var ContentScriptGlobalScope: { + prototype: ContentScriptGlobalScope; + new(): ContentScriptGlobalScope; +}; + +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 CountQueuingStrategy { + highWaterMark: number; + size(): number; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(strategy: QueuingStrategy): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null; +} + +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 CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + whenDefined(name: string): PromiseLike; +} + interface CustomEvent extends Event { readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; @@ -6539,6 +7265,194 @@ declare var CustomEvent: { new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; +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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +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 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 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(...tokens: string[]): void; + contains(token: string): boolean; + item(index: number): string | null; + remove(...tokens: string[]): void; + replace(oldToken: string, newToken: string): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DataCue extends TextTrackCue { data: ArrayBuffer; addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -6585,10 +7499,11 @@ declare var DataTransferItem: { interface DataTransferItemList { readonly length: number; add(data: File): DataTransferItem | null; + add(data: string, type: string): DataTransferItem | null; clear(): void; item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: DataTransferItem; + [name: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -6675,11 +7590,30 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; }; +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforedeactivate": UIEvent; + "activate": Event; + "beforeactivate": Event; + "beforedeactivate": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -6687,7 +7621,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "click": MouseEvent; "contextmenu": PointerEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -6697,7 +7631,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "fullscreenchange": Event; @@ -6717,25 +7651,25 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "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; + "MSContentZoom": Event; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSManipulationStateChanged": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "mssitemodejumplistitemremoved": Event; + "msthumbnailclick": Event; "pause": Event; "play": Event; "playing": Event; @@ -6766,7 +7700,15 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "webkitfullscreenerror": Event; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { +interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent { + /** + * 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; /** * Gets the object that has the focus when the parent document has focus. */ @@ -6782,11 +7724,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * 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; + readonly anchors: HTMLCollectionOf; /** * Retrieves a collection of all applet objects in the document. */ - applets: HTMLCollectionOf; + readonly applets: HTMLCollectionOf; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ @@ -6822,7 +7764,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Gets a reference to the root node of the document. */ - documentElement: HTMLElement; + readonly documentElement: HTMLElement; /** * Sets or gets the security domain of the document. */ @@ -6830,7 +7772,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all embed objects in the document. */ - embeds: HTMLCollectionOf; + readonly embeds: HTMLCollectionOf; /** * Sets or gets the foreground (text) color of the document. */ @@ -6838,7 +7780,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of all form objects in the document. */ - forms: HTMLCollectionOf; + readonly forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; @@ -6846,7 +7788,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of img objects in the document. */ - images: HTMLCollectionOf; + readonly images: HTMLCollectionOf; /** * Gets the implementation object of the current document. */ @@ -6866,322 +7808,323 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. */ - links: HTMLCollectionOf; + readonly links: HTMLCollectionOf; /** * Contains information about the current URL. */ - readonly location: Location; - msCapsLockWarningOff: boolean; + location: Location; msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; /** * Fires when the user aborts the download. * @param ev The event. */ - onabort: (this: Document, ev: UIEvent) => any; + onabort: ((this: Document, ev: UIEvent) => any) | null; /** * Fires when the object is set as the active element. * @param ev The event. */ - onactivate: (this: Document, ev: UIEvent) => any; + onactivate: ((this: Document, ev: Event) => any) | null; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ - onbeforeactivate: (this: Document, ev: UIEvent) => any; + onbeforeactivate: ((this: Document, ev: Event) => any) | null; /** * 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; + onbeforedeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ - onblur: (this: Document, ev: FocusEvent) => any; + onblur: ((this: Document, ev: FocusEvent) => any) | null; /** * 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; + oncanplay: ((this: Document, ev: Event) => any) | null; + oncanplaythrough: ((this: Document, ev: Event) => any) | null; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ - onchange: (this: Document, ev: Event) => any; + onchange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ - onclick: (this: Document, ev: MouseEvent) => any; + onclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ - ondblclick: (this: Document, ev: MouseEvent) => any; + ondblclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + ondeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ - ondrag: (this: Document, ev: DragEvent) => any; + ondrag: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragend: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragenter: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragleave: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragover: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragstart: ((this: Document, ev: DragEvent) => any) | null; + ondrop: ((this: Document, ev: DragEvent) => any) | null; /** * Occurs when the duration attribute is updated. * @param ev The event. */ - ondurationchange: (this: Document, ev: Event) => any; + ondurationchange: ((this: Document, ev: Event) => any) | null; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ - onemptied: (this: Document, ev: Event) => any; + onemptied: ((this: Document, ev: Event) => any) | null; /** * Occurs when the end of playback is reached. * @param ev The event */ - onended: (this: Document, ev: MediaStreamErrorEvent) => any; + onended: ((this: Document, ev: Event) => any) | null; /** * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (this: Document, ev: ErrorEvent) => any; + onerror: ((this: Document, ev: ErrorEvent) => any) | null; /** * 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; + onfocus: ((this: Document, ev: FocusEvent) => any) | null; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + oninput: ((this: Document, ev: Event) => any) | null; + oninvalid: ((this: Document, ev: Event) => any) | null; /** * Fires when the user presses a key. * @param ev The keyboard event */ - onkeydown: (this: Document, ev: KeyboardEvent) => any; + onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ - onkeypress: (this: Document, ev: KeyboardEvent) => any; + onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user releases a key. * @param ev The keyboard event */ - onkeyup: (this: Document, ev: KeyboardEvent) => any; + onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires immediately after the browser loads the object. * @param ev The event. */ - onload: (this: Document, ev: Event) => any; + onload: ((this: Document, ev: Event) => any) | null; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ - onloadeddata: (this: Document, ev: Event) => any; + onloadeddata: ((this: Document, ev: Event) => any) | null; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ - onloadedmetadata: (this: Document, ev: Event) => any; + onloadedmetadata: ((this: Document, ev: Event) => any) | null; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ - onloadstart: (this: Document, ev: Event) => any; + onloadstart: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ - onmousedown: (this: Document, ev: MouseEvent) => any; + onmousedown: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ - onmousemove: (this: Document, ev: MouseEvent) => any; + onmousemove: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseout: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ - onmouseover: (this: Document, ev: MouseEvent) => any; + onmouseover: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseup: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmousewheel: ((this: Document, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: Document, ev: Event) => any) | null; + onmsgesturechange: ((this: Document, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null; + onmsgestureend: ((this: Document, ev: Event) => any) | null; + onmsgesturehold: ((this: Document, ev: Event) => any) | null; + onmsgesturestart: ((this: Document, ev: Event) => any) | null; + onmsgesturetap: ((this: Document, ev: Event) => any) | null; + onmsinertiastart: ((this: Document, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null; + onmspointercancel: ((this: Document, ev: Event) => any) | null; + onmspointerdown: ((this: Document, ev: Event) => any) | null; + onmspointerenter: ((this: Document, ev: Event) => any) | null; + onmspointerleave: ((this: Document, ev: Event) => any) | null; + onmspointermove: ((this: Document, ev: Event) => any) | null; + onmspointerout: ((this: Document, ev: Event) => any) | null; + onmspointerover: ((this: Document, ev: Event) => any) | null; + onmspointerup: ((this: Document, ev: Event) => any) | null; /** * 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; + onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null; /** * 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; + onmsthumbnailclick: ((this: Document, ev: Event) => any) | null; /** * Occurs when playback is paused. * @param ev The event. */ - onpause: (this: Document, ev: Event) => any; + onpause: ((this: Document, ev: Event) => any) | null; /** * Occurs when the play method is requested. * @param ev The event. */ - onplay: (this: Document, ev: Event) => any; + onplay: ((this: Document, ev: Event) => any) | null; /** * 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; + onplaying: ((this: Document, ev: Event) => any) | null; + onpointerlockchange: ((this: Document, ev: Event) => any) | null; + onpointerlockerror: ((this: Document, ev: Event) => any) | null; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ - onprogress: (this: Document, ev: ProgressEvent) => any; + onprogress: ((this: Document, ev: ProgressEvent) => any) | null; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ - onratechange: (this: Document, ev: Event) => any; + onratechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the state of the object has changed. * @param ev The event */ - onreadystatechange: (this: Document, ev: Event) => any; + onreadystatechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user resets a form. * @param ev The event. */ - onreset: (this: Document, ev: Event) => any; + onreset: ((this: Document, ev: Event) => any) | null; /** * 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; + onscroll: ((this: Document, ev: UIEvent) => any) | null; /** * Occurs when the seek operation ends. * @param ev The event. */ - onseeked: (this: Document, ev: Event) => any; + onseeked: ((this: Document, ev: Event) => any) | null; /** * Occurs when the current playback position is moved. * @param ev The event. */ - onseeking: (this: Document, ev: Event) => any; + onseeking: ((this: Document, ev: Event) => any) | null; /** * Fires when the current selection changes. * @param ev The event. */ - onselect: (this: Document, ev: UIEvent) => any; + onselect: ((this: Document, ev: UIEvent) => any) | null; /** * 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; + onselectionchange: ((this: Document, ev: Event) => any) | null; + onselectstart: ((this: Document, ev: Event) => any) | null; /** * Occurs when the download has stopped. * @param ev The event. */ - onstalled: (this: Document, ev: Event) => any; + onstalled: ((this: Document, ev: Event) => any) | null; /** * 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; + onstop: ((this: Document, ev: Event) => any) | null; + onsubmit: ((this: Document, ev: Event) => any) | null; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ - onsuspend: (this: Document, ev: Event) => any; + onsuspend: ((this: Document, ev: Event) => any) | null; /** * 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; + ontimeupdate: ((this: Document, ev: Event) => any) | null; + ontouchcancel: ((this: Document, ev: TouchEvent) => any) | null; + ontouchend: ((this: Document, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Document, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Document, ev: TouchEvent) => any) | null; + onvisibilitychange: (this: Document, ev: Event) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ - onvolumechange: (this: Document, ev: Event) => any; + onvolumechange: ((this: Document, ev: Event) => any) | null; /** * 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; + onwaiting: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null; + readonly plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** * Retrieves a value that indicates the current state of the object. @@ -7198,7 +8141,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all script objects in the document. */ - scripts: HTMLCollectionOf; + readonly 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. @@ -7208,14 +8151,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * 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. @@ -7231,7 +8166,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string | null; - onvisibilitychange: (this: Document, ev: Event) => any; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; @@ -7327,6 +8261,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver: Node): XPathNSResolver; /** * 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. @@ -7335,7 +8270,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @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. @@ -7362,6 +8296,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; + elementsFromPoint(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. @@ -7380,6 +8315,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Causes the element to receive the focus and executes the code specified by the onfocus event. */ + /** @deprecated */ focus(): void; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. @@ -7452,10 +8388,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ queryCommandValue(commandId: string): string; releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** @@ -7479,7 +8411,79 @@ declare var Document: { new(): Document; }; -interface DocumentFragment extends Node, NodeSelector, ParentNode { +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + 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: "MSDCCEvent"): MSDCCEvent; + createEvent(eventInterface: "MSDSHEvent"): MSDSHEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + 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: "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: "PromiseRejectionEvent"): PromiseRejectionEvent; + 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: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + 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: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DocumentFragment extends Node, ParentNode { getElementById(elementId: string): HTMLElement | null; } @@ -7488,6 +8492,14 @@ declare var DocumentFragment: { new(): DocumentFragment; }; +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly styleSheets: StyleSheetList; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + getSelection(): Selection | null; +} + interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; readonly internalSubset: string | null; @@ -7502,149 +8514,6 @@ declare var 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; @@ -7670,209 +8539,23 @@ declare var 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 EXT_blend_minmax { + readonly MAX_EXT: number; + readonly MIN_EXT: number; } -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 | null; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB_EXT: number; +} + +interface EXT_shader_texture_lod { +} interface EXT_texture_filter_anisotropic { readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; @@ -7886,14 +8569,262 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; }; +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": Event; + "command": Event; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSGotPointerCapture": Event; + "MSInertiaStart": Event; + "MSLostPointerCapture": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode { + readonly assignedSlot: HTMLSlotElement | null; + readonly attributes: NamedNodeMap; + 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) | null; + oncommand: ((this: Element, ev: Event) => any) | null; + ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onmsgesturechange: ((this: Element, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null; + onmsgestureend: ((this: Element, ev: Event) => any) | null; + onmsgesturehold: ((this: Element, ev: Event) => any) | null; + onmsgesturestart: ((this: Element, ev: Event) => any) | null; + onmsgesturetap: ((this: Element, ev: Event) => any) | null; + onmsgotpointercapture: ((this: Element, ev: Event) => any) | null; + onmsinertiastart: ((this: Element, ev: Event) => any) | null; + onmslostpointercapture: ((this: Element, ev: Event) => any) | null; + onmspointercancel: ((this: Element, ev: Event) => any) | null; + onmspointerdown: ((this: Element, ev: Event) => any) | null; + onmspointerenter: ((this: Element, ev: Event) => any) | null; + onmspointerleave: ((this: Element, ev: Event) => any) | null; + onmspointermove: ((this: Element, ev: Event) => any) | null; + onmspointerout: ((this: Element, ev: Event) => any) | null; + onmspointerover: ((this: Element, ev: Event) => any) | null; + onmspointerup: ((this: Element, ev: Event) => any) | null; + ontouchcancel: ((this: Element, ev: TouchEvent) => any) | null; + ontouchend: ((this: Element, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Element, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Element, ev: TouchEvent) => any) | null; + onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; + outerHTML: string; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly shadowRoot: ShadowRoot | null; + slot: string; + readonly tagName: string; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + getAttribute(qualifiedName: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + getElementsByClassName(classNames: string): NodeListOf; + 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; + hasAttributes(): boolean; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + matches(selectors: string): boolean; + msGetRegionContent(): any; + 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; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + setAttribute(qualifiedName: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): 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: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + readonly style: CSSStyleDeclaration; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ElementDefinitionOptions { + extends: string; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly nextElementSibling: Element | null; + readonly previousElementSibling: Element | null; +} + +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(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly scoped: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget | null; + readonly timeStamp: number; + readonly type: string; + deepPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(typeArg: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; - fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; genericSynchronousFunction(functionId: number, parameters?: string): string; + genericWebRuntimeCallout(to: any, from: any, payload: string): void; getExtensionId(): string; - registerGenericFunctionCallbackHandler(callbackHandler: any): void; - registerGenericPersistentCallbackHandler(callbackHandler: any): void; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericPersistentCallbackHandler(callbackHandler: Function): void; + registerWebRuntimeCallbackHandler(handler: Function): any; } declare var ExtensionScriptApis: { @@ -7910,10 +8841,11 @@ declare var External: { }; interface File extends Blob { + readonly lastModified: number; + /** @deprecated */ readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; - readonly lastModified: number; } declare var File: { @@ -7923,7 +8855,7 @@ declare var File: { interface FileList { readonly length: number; - item(index: number): File; + item(index: number): File | null; [index: number]: File; } @@ -7932,21 +8864,49 @@ declare var FileList: { new(): FileList; }; -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; 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; + readAsText(blob: Blob, label?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[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: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface FocusEvent extends UIEvent { @@ -7984,7 +8944,8 @@ interface FormData { declare var FormData: { prototype: FormData; - new (form?: HTMLFormElement): FormData; + new(): FormData; + new(form: HTMLFormElement): FormData; }; interface GainNode extends AudioNode { @@ -8000,9 +8961,13 @@ interface Gamepad { readonly axes: number[]; readonly buttons: GamepadButton[]; readonly connected: boolean; + readonly displayId: number; + readonly hand: GamepadHand; + readonly hapticActuators: GamepadHapticActuator[]; readonly id: string; readonly index: number; - readonly mapping: string; + readonly mapping: GamepadMappingType; + readonly pose: GamepadPose | null; readonly timestamp: number; } @@ -8013,6 +8978,7 @@ declare var Gamepad: { interface GamepadButton { readonly pressed: boolean; + readonly touched: boolean; readonly value: number; } @@ -8030,6 +8996,32 @@ declare var GamepadEvent: { new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; }; +interface GamepadHapticActuator { + readonly type: GamepadHapticActuatorType; + pulse(value: number, duration: number): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GamepadPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; +} + +declare var GamepadPose: { + prototype: GamepadPose; + new(): GamepadPose; +}; + interface Geolocation { clearWatch(watchId: number): void; getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; @@ -8041,45 +9033,41 @@ declare var Geolocation: { new(): Geolocation; }; -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; +interface GetSVGDocument { + getSVGDocument(): Document; } -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; +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; } -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; +interface GlobalEventHandlers { + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + 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; } -declare var History: { - prototype: History; - new(): History; -}; +interface GlobalFetch { + fetch(input?: Request | string, init?: RequestInit): Promise; +} interface HTMLAllCollection { readonly length: number; @@ -8093,55 +9081,30 @@ declare var HTMLAllCollection: { new(): HTMLAllCollection; }; -interface HTMLAnchorElement extends HTMLElement { +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + Methods: string; /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Sets or retrieves the coordinates of the object. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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. @@ -8150,14 +9113,12 @@ interface HTMLAnchorElement extends HTMLElement { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ 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. */ + /** @deprecated */ shape: string; /** * Sets or retrieves the window or frame at which to target content. @@ -8169,10 +9130,6 @@ interface HTMLAnchorElement extends HTMLElement { 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; @@ -8185,70 +9142,44 @@ declare var HTMLAnchorElement: { }; interface HTMLAppletElement extends HTMLElement { + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ 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. */ + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; /** * Sets or retrieves the shape of the object. */ + /** @deprecated */ 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; + /** @deprecated */ + object: string; + /** @deprecated */ vspace: number; - width: number; + /** @deprecated */ + width: string; 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; @@ -8260,7 +9191,7 @@ declare var HTMLAppletElement: { new(): HTMLAppletElement; }; -interface HTMLAreaElement extends HTMLElement { +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { /** * Sets or retrieves a text alternative to the graphic. */ @@ -8270,43 +9201,12 @@ interface HTMLAreaElement extends HTMLElement { */ 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. */ + /** @deprecated */ 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. */ @@ -8315,10 +9215,6 @@ interface HTMLAreaElement extends HTMLElement { * 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; @@ -8350,6 +9246,23 @@ declare var HTMLAudioElement: { new(): HTMLAudioElement; }; +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. + */ + /** @deprecated */ + 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 HTMLBaseElement extends HTMLElement { /** * Gets or sets the baseline URL on which relative links are based. @@ -8374,10 +9287,12 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ face: string; /** * Sets or retrieves the font size of the object. */ + /** @deprecated */ 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; @@ -8390,51 +9305,34 @@ declare var HTMLBaseFontElement: { new(): HTMLBaseFontElement; }; -interface HTMLBodyElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { + /** @deprecated */ + aLink: string; + /** @deprecated */ background: string; - bgColor: any; + /** @deprecated */ + bgColor: string; bgProperties: string; - link: any; + /** @deprecated */ + link: string; + /** @deprecated */ 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; + onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; + onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null; + /** @deprecated */ + text: string; + /** @deprecated */ + vLink: string; 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; @@ -8446,22 +9344,6 @@ declare var 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. @@ -8487,7 +9369,7 @@ interface HTMLButtonElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -8557,12 +9439,12 @@ interface HTMLCanvasElement extends HTMLElement { * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ msToBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; /** * 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; @@ -8598,6 +9480,26 @@ declare var HTMLCollection: { new(): HTMLCollection; }; +interface HTMLCollectionOf extends HTMLCollectionBase { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface HTMLDListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLDataElement extends HTMLElement { value: string; addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8612,7 +9514,7 @@ declare var HTMLDataElement: { }; interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; + readonly 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; @@ -8624,6 +9526,36 @@ declare var HTMLDataListElement: { new(): HTMLDataListElement; }; +interface HTMLDetailsElement extends HTMLElement { + open: boolean; + addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; + addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + interface HTMLDirectoryElement extends HTMLElement { compact: boolean; addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8641,6 +9573,7 @@ interface HTMLDivElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. @@ -8657,19 +9590,6 @@ declare var 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; @@ -8684,12 +9604,12 @@ declare var HTMLDocument: { interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforecopy": ClipboardEvent; - "beforecut": ClipboardEvent; - "beforedeactivate": UIEvent; - "beforepaste": ClipboardEvent; + "activate": Event; + "beforeactivate": Event; + "beforecopy": Event; + "beforecut": Event; + "beforedeactivate": Event; + "beforepaste": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -8700,7 +9620,7 @@ interface HTMLElementEventMap extends ElementEventMap { "cuechange": Event; "cut": ClipboardEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -8710,7 +9630,7 @@ interface HTMLElementEventMap extends ElementEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "input": Event; @@ -8730,8 +9650,8 @@ interface HTMLElementEventMap extends ElementEventMap { "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": WheelEvent; - "MSContentZoom": UIEvent; - "MSManipulationStateChanged": MSManipulationEvent; + "MSContentZoom": Event; + "MSManipulationStateChanged": Event; "paste": ClipboardEvent; "pause": Event; "play": Event; @@ -8752,9 +9672,8 @@ interface HTMLElementEventMap extends ElementEventMap { "waiting": Event; } -interface HTMLElement extends Element { +interface HTMLElement extends Element, ElementCSSInlineStyle { accessKey: string; - readonly children: HTMLCollection; contentEditable: string; readonly dataset: DOMStringMap; dir: string; @@ -8769,84 +9688,83 @@ interface HTMLElement extends Element { 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; + onabort: ((this: HTMLElement, ev: UIEvent) => any) | null; + onactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecut: ((this: HTMLElement, ev: Event) => any) | null; + onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null; + onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oncanplay: ((this: HTMLElement, ev: Event) => any) | null; + oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null; + onchange: ((this: HTMLElement, ev: Event) => any) | null; + onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null; + oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + oncuechange: ((this: HTMLElement, ev: Event) => any) | null; + oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + ondeactivate: ((this: HTMLElement, ev: Event) => any) | null; + ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondurationchange: ((this: HTMLElement, ev: Event) => any) | null; + onemptied: ((this: HTMLElement, ev: Event) => any) | null; + onended: ((this: HTMLElement, ev: Event) => any) | null; + onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null; + onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oninput: ((this: HTMLElement, ev: Event) => any) | null; + oninvalid: ((this: HTMLElement, ev: Event) => any) | null; + onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onload: ((this: HTMLElement, ev: Event) => any) | null; + onloadeddata: ((this: HTMLElement, ev: Event) => any) | null; + onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null; + onloadstart: ((this: HTMLElement, ev: Event) => any) | null; + onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null; + onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + onpause: ((this: HTMLElement, ev: Event) => any) | null; + onplay: ((this: HTMLElement, ev: Event) => any) | null; + onplaying: ((this: HTMLElement, ev: Event) => any) | null; + onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null; + onratechange: ((this: HTMLElement, ev: Event) => any) | null; + onreset: ((this: HTMLElement, ev: Event) => any) | null; + onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null; + onseeked: ((this: HTMLElement, ev: Event) => any) | null; + onseeking: ((this: HTMLElement, ev: Event) => any) | null; + onselect: ((this: HTMLElement, ev: UIEvent) => any) | null; + onselectstart: ((this: HTMLElement, ev: Event) => any) | null; + onstalled: ((this: HTMLElement, ev: Event) => any) | null; + onsubmit: ((this: HTMLElement, ev: Event) => any) | null; + onsuspend: ((this: HTMLElement, ev: Event) => any) | null; + ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null; + onvolumechange: ((this: HTMLElement, ev: Event) => any) | null; + onwaiting: ((this: HTMLElement, ev: Event) => any) | null; outerText: string; spellcheck: boolean; - readonly style: CSSStyleDeclaration; tabIndex: number; title: string; + animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; blur(): void; click(): void; dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; 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; @@ -8883,6 +9801,7 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * Retrieves the palette used for the embedded document. @@ -8963,6 +9882,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ 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; @@ -9043,6 +9963,7 @@ interface HTMLFormElement extends HTMLElement { * Retrieves a form object or an object from an elements collection. */ namedItem(name: string): any; + reportValidity(): boolean; /** * Fires when the user resets a form. */ @@ -9051,8 +9972,6 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ 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; @@ -9081,14 +10000,17 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + /** @deprecated */ + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + /** @deprecated */ + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. @@ -9101,30 +10023,37 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a URI to a long description of the object. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ marginWidth: string; /** * Sets or retrieves the frame name. */ + /** @deprecated */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ + /** @deprecated */ noResize: boolean; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ + /** @deprecated */ src: string; /** * Sets or retrieves the width of the object. @@ -9141,64 +10070,29 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; }; -interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { /** * Sets or retrieves the frame widths of the object. */ + /** @deprecated */ 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; + onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null; + onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null; /** * Sets or retrieves the frame heights of the object. */ + /** @deprecated */ 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; @@ -9211,7 +10105,35 @@ declare var HTMLFrameSetElement: { new(): HTMLFrameSetElement; }; +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + /** @deprecated */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + 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 HTMLHeadElement extends HTMLElement { + /** @deprecated */ 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; @@ -9228,6 +10150,7 @@ interface HTMLHeadingElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ 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; @@ -9240,34 +10163,11 @@ declare var 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. */ + /** @deprecated */ 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; @@ -9280,6 +10180,19 @@ declare var HTMLHtmlElement: { new(): HTMLHtmlElement; }; +interface HTMLHyperlinkElementUtils { + hash: string; + host: string; + hostname: string; + href: string; + origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + toString(): string; +} + interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; } @@ -9288,78 +10201,64 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ 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; + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ 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. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ 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; + readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** - * Sets or retrieves the vertical margin for the object. + * Sets or retrives the content of the page that is to contain. */ - vspace: number; + srcdoc: string; /** * 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; @@ -9375,6 +10274,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -9383,6 +10283,7 @@ interface HTMLImageElement extends HTMLElement { /** * Specifies the properties of a border drawn around an object. */ + /** @deprecated */ border: string; /** * Retrieves whether the object is fully loaded. @@ -9390,6 +10291,7 @@ interface HTMLImageElement extends HTMLElement { readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; /** * Sets or retrieves the height of the object. */ @@ -9397,6 +10299,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ hspace: number; /** * Sets or retrieves whether the image is a server-side image map. @@ -9406,6 +10309,7 @@ interface HTMLImageElement extends HTMLElement { * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. */ longDesc: string; + /** @deprecated */ lowsrc: string; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -9423,6 +10327,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * The original height of the image resource before sizing. @@ -9445,6 +10350,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the vertical margin for the object. */ + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -9472,6 +10378,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -9485,18 +10392,10 @@ interface HTMLInputElement 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 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. */ @@ -9529,7 +10428,7 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -9537,16 +10436,12 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + height: number; indeterminate: boolean; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ - readonly list: HTMLElement; + readonly list: HTMLElement | null; /** * 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. */ @@ -9559,6 +10454,7 @@ interface HTMLInputElement extends HTMLElement { * 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; + minLength: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ @@ -9580,21 +10476,20 @@ interface HTMLInputElement extends HTMLElement { * When present, marks an element that can't be submitted without a value. */ required: boolean; - selectionDirection: string; + selectionDirection: string | null; /** * Gets or sets the end position or offset of a text selection. */ - selectionEnd: number; + selectionEnd: number | null; /** * Gets or sets the starting position or offset of a text selection. */ - selectionStart: number; + selectionStart: number | null; 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. */ @@ -9606,6 +10501,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ + /** @deprecated */ 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. @@ -9619,25 +10515,20 @@ interface HTMLInputElement extends HTMLElement { * Returns the value of the data at the cursor's current position. */ value: string; - valueAsDate: Date; + valueAsDate: any; /** * 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; + width: number; /** * 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. */ @@ -9679,48 +10570,8 @@ declare var 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 { + /** @deprecated */ type: string; /** * Sets or retrieves the value of a list item. @@ -9737,11 +10588,56 @@ declare var HTMLLIElement: { new(): HTMLLIElement; }; +interface HTMLLabelElement extends HTMLElement { + readonly control: HTMLInputElement | null; + /** + * 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; + 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. + */ + /** @deprecated */ + 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 HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; + crossOrigin: string | null; + /** @deprecated */ disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. @@ -9751,6 +10647,8 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { * Sets or retrieves the language code of the object. */ hreflang: string; + import?: Document; + integrity: string; /** * Sets or retrieves the media type. */ @@ -9762,17 +10660,17 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ rev: string; /** * Sets or retrieves the window or frame at which to target content. */ + /** @deprecated */ 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; @@ -9784,6 +10682,18 @@ declare var HTMLLinkElement: { new(): HTMLLinkElement; }; +interface HTMLMainElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. @@ -9811,21 +10721,37 @@ interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { } interface HTMLMarqueeElement extends HTMLElement { + /** @deprecated */ behavior: string; - bgColor: any; + /** @deprecated */ + bgColor: string; + /** @deprecated */ direction: string; + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; + /** @deprecated */ loop: number; - onbounce: (this: HTMLMarqueeElement, ev: Event) => any; - onfinish: (this: HTMLMarqueeElement, ev: Event) => any; - onstart: (this: HTMLMarqueeElement, ev: Event) => any; + /** @deprecated */ + onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ scrollAmount: number; + /** @deprecated */ scrollDelay: number; + /** @deprecated */ trueSpeed: boolean; + /** @deprecated */ vspace: number; + /** @deprecated */ width: string; + /** @deprecated */ start(): void; + /** @deprecated */ 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; @@ -9840,7 +10766,7 @@ declare var HTMLMarqueeElement: { interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; - "msneedkey": MSMediaKeyNeededEvent; + "msneedkey": Event; } interface HTMLMediaElement extends HTMLElement { @@ -9885,7 +10811,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Returns an object representing the current error state of the audio or video element. */ - readonly error: MediaError; + readonly error: MediaError | null; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ @@ -9903,6 +10829,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ + /** @deprecated */ readonly msKeys: MSMediaKeys; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -9932,8 +10859,9 @@ interface HTMLMediaElement extends HTMLElement { * Gets the current network activity for the element. */ readonly networkState: number; - onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null; + /** @deprecated */ + onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null; /** * Gets a flag that specifies whether playback is paused. */ @@ -9950,7 +10878,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: number; + readonly readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -9963,18 +10891,18 @@ interface HTMLMediaElement extends HTMLElement { * The address or URL of the a media resource that is to be considered. */ src: string; - srcObject: MediaStream | null; + srcObject: MediaStream | MediaSource | Blob | 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; + addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack; /** * Returns a string that specifies whether the client can play a given media resource type. */ - canPlayType(type: string): string; + canPlayType(type: string): CanPlayTypeResult; /** * Resets the audio or video object and loads a new media resource. */ @@ -9988,6 +10916,7 @@ interface HTMLMediaElement extends HTMLElement { * Inserts the specified audio effect into media pipeline. */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + /** @deprecated */ msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Specifies the media protection manager for a given media pipeline. @@ -10032,6 +10961,7 @@ declare var HTMLMediaElement: { }; interface HTMLMenuElement extends HTMLElement { + /** @deprecated */ compact: boolean; type: string; addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -10049,6 +10979,7 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. @@ -10065,10 +10996,12 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ + /** @deprecated */ scheme: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ + /** @deprecated */ 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; @@ -10119,41 +11052,63 @@ declare var HTMLModElement: { new(): HTMLModElement; }; +interface HTMLOListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLObjectElement extends HTMLElement, GetSVGDocument { - align: 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; + /** @deprecated */ + align: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ border: string; /** * Sets or retrieves the URL of the file containing the compiled Java class. */ + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ + /** @deprecated */ codeType: string; /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + readonly contentDocument: Document | null; /** * Sets or retrieves the URL that references the data of the object. */ data: string; + /** @deprecated */ declare: boolean; /** * Retrieves a reference to the form that the object is embedded in. @@ -10163,6 +11118,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the height of the object. */ height: string; + /** @deprecated */ hspace: number; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -10188,11 +11144,13 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a message to be displayed while an object is loading. */ + /** @deprecated */ standby: string; /** * Sets or retrieves the MIME type of the object. */ type: string; + typemustmatch: boolean; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ @@ -10205,6 +11163,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -10214,7 +11173,6 @@ 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. */ @@ -10235,54 +11193,16 @@ declare var 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; @@ -10338,7 +11258,7 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; remove(index: number): void; } @@ -10350,7 +11270,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; readonly form: HTMLFormElement | null; - readonly htmlFor: DOMSettableTokenList; + readonly htmlFor: DOMTokenList; name: string; readonly type: string; readonly validationMessage: string; @@ -10375,6 +11295,7 @@ interface HTMLParagraphElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -10396,6 +11317,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the content type of the resource designated by the value attribute. */ + /** @deprecated */ type: string; /** * Sets or retrieves the value of an input parameter for an element. @@ -10404,6 +11326,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the data type of the value attribute. */ + /** @deprecated */ 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; @@ -10432,6 +11355,7 @@ interface HTMLPreElement extends HTMLElement { /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ + /** @deprecated */ 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; @@ -10502,11 +11426,15 @@ interface HTMLScriptElement extends HTMLElement { /** * Sets or retrieves the event for which the script is written. */ + /** @deprecated */ event: string; /** * Sets or retrieves the object that is bound to the event script. */ + /** @deprecated */ htmlFor: string; + integrity: string; + noModule: boolean; /** * Retrieves the URL to an external file that contains the source code or data. */ @@ -10519,7 +11447,6 @@ interface HTMLScriptElement extends HTMLElement { * 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; @@ -10562,7 +11489,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the index of the selected option in a select object. */ selectedIndex: number; - selectedOptions: HTMLCollectionOf; + readonly selectedOptions: HTMLCollectionOf; /** * Sets or retrieves the number of rows in the list box. */ @@ -10592,7 +11519,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -10602,7 +11529,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + item(name?: any, index?: any): Element | null; /** * 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. @@ -10630,11 +11557,21 @@ declare var HTMLSelectElement: { new(): HTMLSelectElement; }; +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; + addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; + /** @deprecated */ msKeySystem: string; sizes: string; /** @@ -10670,6 +11607,7 @@ declare var HTMLSpanElement: { }; interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** @deprecated */ disabled: boolean; /** * Sets or retrieves the media type. @@ -10690,15 +11628,24 @@ declare var HTMLStyleElement: { new(): HTMLStyleElement; }; +interface HTMLSummaryElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. */ + /** @deprecated */ 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; @@ -10710,7 +11657,7 @@ declare var HTMLTableCaptionElement: { new(): HTMLTableCaptionElement; }; -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableCellElement extends HTMLElement { /** * Sets or retrieves abbreviated text for the object. */ @@ -10718,16 +11665,23 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. */ + /** @deprecated */ axis: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves the position of the object in the cells collection of a row. */ readonly cellIndex: number; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number columns in the table that the object should span. */ @@ -10739,10 +11693,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves the height of the object. */ - height: any; + /** @deprecated */ + height: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ + /** @deprecated */ noWrap: boolean; /** * Sets or retrieves how many rows in a table the cell should span. @@ -10752,9 +11708,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ 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; @@ -10767,19 +11726,27 @@ declare var HTMLTableCellElement: { new(): HTMLTableCellElement; }; -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableColElement extends HTMLElement { /** * Sets or retrieves the alignment of the object relative to the display or table. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of columns in the group. */ span: number; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ - width: any; + /** @deprecated */ + width: string; 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; @@ -10807,67 +11774,64 @@ interface HTMLTableElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; /** * Retrieves the caption object of a table. */ - caption: HTMLTableCaptionElement; + caption: HTMLTableCaptionElement | null; /** * Sets or retrieves the amount of space between the border of the cell and the content of the cell. */ + /** @deprecated */ cellPadding: string; /** * Sets or retrieves the amount of space between cells in a table. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + readonly rows: HTMLCollectionOf; /** * Sets or retrieves which dividing lines (inner borders) are displayed. */ + /** @deprecated */ rules: string; /** * Sets or retrieves a description and/or structure of the object. */ + /** @deprecated */ summary: string; /** * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. */ - tBodies: HTMLCollectionOf; + readonly tBodies: HTMLCollectionOf; /** * Retrieves the tFoot object of the table. */ - tFoot: HTMLTableSectionElement; + tFoot: HTMLTableSectionElement | null; /** * Retrieves the tHead object of the table. */ - tHead: HTMLTableSectionElement; + tHead: HTMLTableSectionElement | null; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ width: string; /** * Creates an empty caption element in the table. @@ -10919,9 +11883,6 @@ declare var 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; @@ -10934,20 +11895,22 @@ declare var HTMLTableHeaderCellElement: { new(): HTMLTableHeaderCellElement; }; -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableRowElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves a collection of all cells in the table row. */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; + readonly cells: HTMLCollectionOf; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Retrieves the position of the object in the rows collection for the table. */ @@ -10956,6 +11919,8 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Retrieves the position of the object in the collection. */ readonly sectionRowIndex: number; + /** @deprecated */ + vAlign: string; /** * 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. @@ -10977,15 +11942,22 @@ declare var HTMLTableRowElement: { new(): HTMLTableRowElement; }; -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableSectionElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of horizontal rows contained in the object. */ - rows: HTMLCollectionOf; + readonly rows: HTMLCollectionOf; + /** @deprecated */ + vAlign: string; /** * 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. @@ -11042,6 +12014,7 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; + minLength: number; /** * Sets or retrieves the name of the object. */ @@ -11070,10 +12043,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -11098,7 +12067,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -11187,7 +12155,9 @@ declare var HTMLTrackElement: { }; interface HTMLUListElement extends HTMLElement { + /** @deprecated */ compact: boolean; + /** @deprecated */ 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; @@ -11229,9 +12199,9 @@ interface HTMLVideoElement extends HTMLMediaElement { msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; - onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; /** * 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. */ @@ -11254,10 +12224,10 @@ interface HTMLVideoElement extends HTMLMediaElement { 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; + 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; @@ -11269,13 +12239,71 @@ declare var HTMLVideoElement: { new(): HTMLVideoElement; }; +interface HTMLegendElement { + readonly form: HTMLFormElement | null; +} + +declare var HTMLegendElement: { + prototype: HTMLegendElement; + new(): HTMLegendElement; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string; + readonly oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: Function, thisArg?: any): 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; + scrollRestoration: ScrollRestoration; + readonly state: any; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): 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 HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + interface IDBCursor { readonly direction: IDBCursorDirection; - key: IDBKeyRange | IDBValidKey; + readonly key: IDBKeyRange | number | string | Date | IDBArrayKey; readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; + readonly source: IDBObjectStore | IDBIndex; advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; + continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void; delete(): IDBRequest; update(value: any): IDBRequest; readonly NEXT: string; @@ -11310,16 +12338,14 @@ interface IDBDatabaseEventMap { 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; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: Event) => any) | null; + readonly version: number; 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; @@ -11331,6 +12357,10 @@ declare var IDBDatabase: { new(): IDBDatabase; }; +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + interface IDBFactory { cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; @@ -11343,16 +12373,16 @@ declare var IDBFactory: { }; interface IDBIndex { - keyPath: string | string[]; + readonly keyPath: string | string[]; + multiEntry: boolean; 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; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -11377,21 +12407,21 @@ declare var IDBKeyRange: { }; interface IDBObjectStore { + autoIncrement: boolean; readonly indexNames: DOMStringList; - keyPath: string | string[]; + readonly keyPath: string | string[] | null; readonly name: string; readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): 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; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; } declare var IDBObjectStore: { @@ -11405,8 +12435,8 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { } interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: IDBOpenDBRequest, ev: Event) => any; - onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; 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; @@ -11425,11 +12455,11 @@ interface IDBRequestEventMap { interface IDBRequest extends EventTarget { readonly error: DOMException; - onerror: (this: IDBRequest, ev: Event) => any; - onsuccess: (this: IDBRequest, ev: Event) => any; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; readonly readyState: IDBRequestReadyState; readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; + readonly 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; @@ -11452,9 +12482,9 @@ 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; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -11493,8 +12523,23 @@ declare var IIRFilterNode: { new(): IIRFilterNode; }; +interface ImageBitmap { + readonly height: number; + readonly width: number; + close(): void; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + interface ImageData { - data: Uint8ClampedArray; + readonly data: Uint8ClampedArray; readonly height: number; readonly width: number; } @@ -11524,10 +12569,10 @@ interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; readonly intersectionRect: ClientRect | DOMRect; + readonly isIntersecting: boolean; readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; - readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -11537,19 +12582,23 @@ declare var IntersectionObserverEntry: { interface KeyboardEvent extends UIEvent { readonly altKey: boolean; - readonly char: string | null; + /** @deprecated */ + char: string; + /** @deprecated */ readonly charCode: number; + readonly code: string; readonly ctrlKey: boolean; readonly key: string; + /** @deprecated */ readonly keyCode: number; - readonly locale: string; readonly location: number; readonly metaKey: boolean; readonly repeat: boolean; readonly shiftKey: boolean; + /** @deprecated */ readonly which: number; - readonly code: string; getModifierState(keyArg: string): boolean; + /** @deprecated */ 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; @@ -11570,6 +12619,10 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_STANDARD: number; }; +interface LinkStyle { + readonly sheet: StyleSheet | null; +} + interface ListeningStateChangedEvent extends Event { readonly label: string; readonly state: ListeningState; @@ -11601,14 +12654,327 @@ declare var Location: { new(): Location; }; -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; } -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; +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 MSDCCEvent extends Event { + readonly maxFr: number; + readonly maxFs: number; +} + +declare var MSDCCEvent: { + prototype: MSDCCEvent; + new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent; +}; + +interface MSDSHEvent extends Event { + readonly sources: number[]; + readonly timestamp: number; +} + +declare var MSDSHEvent: { + prototype: MSDSHEvent; + new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent; +}; + +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 MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +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 MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null; + 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 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 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 MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string | null): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string; +}; + +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 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 MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MSStreamReaderEventMap { + "abort": UIEvent; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSStreamReader extends EventTarget { + readonly error: DOMError; + onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null; + onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null; + onload: ((this: MSStreamReader, ev: Event) => any) | null; + onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: MSStreamReader, ev: Event) => any) | null; + onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; + 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; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface MediaDeviceInfo { @@ -11628,7 +12994,7 @@ interface MediaDevicesEventMap { } interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; + ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; @@ -11691,26 +13057,16 @@ declare var MediaKeyMessageEvent: { new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; }; -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: BufferSource): 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: BufferSource): Promise; + generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: BufferSource): Promise; + update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; } declare var MediaKeySession: { @@ -11720,9 +13076,9 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: BufferSource): MediaKeyStatus; - has(keyId: BufferSource): boolean; + forEach(callback: Function, thisArg?: any): void; + get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus; + has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean; } declare var MediaKeyStatusMap: { @@ -11741,13 +13097,23 @@ declare var MediaKeySystemAccess: { new(): MediaKeySystemAccess; }; +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + interface MediaList { readonly length: number; mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; + appendMedium(medium: string): void; + deleteMedium(medium: string): void; + item(index: number): string | null; + toString(): number; [index: number]: string; } @@ -11794,10 +13160,10 @@ interface MediaStreamEventMap { 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; + onactive: ((this: MediaStream, ev: Event) => any) | null; + onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + oninactive: ((this: MediaStream, ev: Event) => any) | null; + onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; addTrack(track: MediaStreamTrack): void; clone(): MediaStream; getAudioTracks(): MediaStreamTrack[]; @@ -11814,7 +13180,9 @@ interface MediaStream extends EventTarget { declare var MediaStream: { prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; + new(): MediaStream; + new(stream: MediaStream): MediaStream; + new(tracks: MediaStreamTrack[]): MediaStream; }; interface MediaStreamAudioSourceNode extends AudioNode { @@ -11867,10 +13235,10 @@ interface MediaStreamTrack extends EventTarget { 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; + onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readonly: boolean; readonly readyState: MediaStreamTrackState; readonly remote: boolean; @@ -11913,9 +13281,9 @@ declare var 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; + readonly ports: ReadonlyArray; + readonly source: Window | null; + initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void; } declare var MessageEvent: { @@ -11928,7 +13296,7 @@ interface MessagePortEventMap { } interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; @@ -11974,6 +13342,7 @@ interface MouseEvent extends UIEvent { readonly clientX: number; readonly clientY: number; readonly ctrlKey: boolean; + /** @deprecated */ readonly fromElement: Element; readonly layerX: number; readonly layerY: number; @@ -11988,7 +13357,9 @@ interface MouseEvent extends UIEvent { readonly screenX: number; readonly screenY: number; readonly shiftKey: boolean; + /** @deprecated */ readonly toElement: Element; + /** @deprecated */ readonly which: number; readonly x: number; readonly y: number; @@ -12001,456 +13372,6 @@ declare var 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; @@ -12491,7 +13412,7 @@ interface MutationRecord { readonly previousSibling: Node | null; readonly removedNodes: NodeList; readonly target: Node; - readonly type: string; + readonly type: MutationRecordType; } declare var MutationRecord: { @@ -12501,13 +13422,13 @@ declare var 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; + getNamedItem(qualifiedName: string): Attr | null; + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + item(index: number): Attr | null; + removeNamedItem(qualifiedName: string): Attr; + removeNamedItemNS(namespace: string | null, localName: string): Attr; + setNamedItem(attr: Attr): Attr | null; + setNamedItemNS(attr: Attr): Attr | null; [index: number]: Attr; } @@ -12516,39 +13437,13 @@ declare var 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 { +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage { + readonly activeVRDisplays: ReadonlyArray; readonly authentication: WebAuthentication; readonly cookieEnabled: boolean; + readonly doNotTrack: string | null; gamepadInputEmulation: GamepadInputEmulationType; - readonly language: string; + readonly geolocation: Geolocation; readonly maxTouchPoints: number; readonly mimeTypes: MimeTypeArray; readonly msManipulationViewsEnabled: boolean; @@ -12558,10 +13453,8 @@ 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[]; + getGamepads(): (Gamepad | null)[]; + getVRDisplays(): Promise; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; @@ -12573,10 +13466,50 @@ declare var Navigator: { new(): Navigator; }; +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +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 NavigatorLanguage { + readonly language: string; + readonly languages: ReadonlyArray; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getDisplayMedia(constraints: MediaStreamConstraints): Promise; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + interface Node extends EventTarget { - readonly attributes: NamedNodeMap; readonly baseURI: string | null; - readonly childNodes: NodeList; + readonly childNodes: NodeListOf; readonly firstChild: Node | null; readonly lastChild: Node | null; readonly localName: string | null; @@ -12594,7 +13527,6 @@ interface Node extends EventTarget { 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; @@ -12649,7 +13581,7 @@ declare var Node: { }; interface NodeFilter { - acceptNode(n: Node): number; + acceptNode(node: Node): number; } declare var NodeFilter: { @@ -12672,13 +13604,14 @@ declare var NodeFilter: { }; interface NodeIterator { + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; detach(): void; - nextNode(): Node; - previousNode(): Node; + nextNode(): Node | null; + previousNode(): Node | null; } declare var NodeIterator: { @@ -12697,6 +13630,21 @@ declare var NodeList: { new(): NodeList; }; +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +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 NotificationEventMap { "click": Event; "close": Event; @@ -12705,16 +13653,17 @@ interface NotificationEventMap { } interface Notification extends EventTarget { - readonly body: string; + readonly body: string | null; + readonly data: any; 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 icon: string | null; + readonly lang: string | null; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; readonly permission: NotificationPermission; - readonly tag: string; + readonly tag: string | null; readonly title: string; close(): void; addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -12781,6 +13730,14 @@ declare var OES_texture_half_float_linear: { new(): OES_texture_half_float_linear; }; +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; +} + interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; } @@ -12796,7 +13753,7 @@ interface OfflineAudioContextEventMap extends AudioContextEventMap { interface OfflineAudioContext extends AudioContextBase { readonly length: number; - oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; + oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null; startRendering(): Promise; suspend(suspendTime: number): Promise; addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -12811,13 +13768,13 @@ declare var OfflineAudioContext: { }; interface OscillatorNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface OscillatorNode extends AudioNode { readonly detune: AudioParam; readonly frequency: AudioParam; - onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: OscillatorNode, ev: Event) => any) | null; type: OscillatorType; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; @@ -12868,8 +13825,11 @@ interface PannerNode extends AudioNode { panningModel: PanningModelType; refDistance: number; rolloffFactor: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -12878,12 +13838,28 @@ declare var PannerNode: { new(): PannerNode; }; -interface Path2D extends Object, CanvasPathMethods { +interface ParentNode { + readonly children: HTMLCollection; + 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 ParentNode { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; +} + +interface Path2D extends CanvasPathMethods { } declare var Path2D: { prototype: Path2D; - new(path?: Path2D): Path2D; + new(d?: Path2D | string): Path2D; }; interface PaymentAddress { @@ -12912,12 +13888,14 @@ interface PaymentRequestEventMap { } interface PaymentRequest extends EventTarget { - onshippingaddresschange: (this: PaymentRequest, ev: Event) => any; - onshippingoptionchange: (this: PaymentRequest, ev: Event) => any; + readonly id: string; + onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; + onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; readonly shippingType: PaymentShippingType | null; abort(): Promise; + canMakePayment(): 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; @@ -12927,11 +13905,11 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; - new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; }; interface PaymentRequestUpdateEvent extends Event { - updateWith(d: Promise): void; + updateWith(detailsPromise: Promise): void; } declare var PaymentRequestUpdateEvent: { @@ -12945,6 +13923,7 @@ interface PaymentResponse { readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; + readonly requestId: string; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; @@ -12956,16 +13935,50 @@ declare var PaymentResponse: { new(): PaymentResponse; }; +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 Performance { + /** @deprecated */ readonly navigation: PerformanceNavigation; + readonly timeOrigin: number; + /** @deprecated */ 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; + getEntriesByName(name: string, type?: string): any; + getEntriesByType(type: string): any; + /** @deprecated */ getMarks(markName?: string): any; + /** @deprecated */ getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; @@ -12984,6 +13997,7 @@ interface PerformanceEntry { readonly entryType: string; readonly name: string; readonly startTime: number; + toJSON(): any; } declare var PerformanceEntry: { @@ -13027,28 +14041,41 @@ declare var PerformanceNavigation: { }; interface PerformanceNavigationTiming extends PerformanceEntry { + /** @deprecated */ readonly connectEnd: number; + /** @deprecated */ readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; + /** @deprecated */ readonly domLoading: number; + /** @deprecated */ + readonly domainLookupEnd: number; + /** @deprecated */ + readonly domainLookupStart: number; + /** @deprecated */ readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; + /** @deprecated */ readonly navigationStart: number; readonly redirectCount: number; + /** @deprecated */ readonly redirectEnd: number; + /** @deprecated */ readonly redirectStart: number; + /** @deprecated */ readonly requestStart: number; + /** @deprecated */ readonly responseEnd: number; + /** @deprecated */ readonly responseStart: number; readonly type: NavigationType; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly workerStart: number; } declare var PerformanceNavigationTiming: { @@ -13068,6 +14095,7 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly workerStart: number; } declare var PerformanceResourceTiming: { @@ -13078,13 +14106,13 @@ declare var 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 domainLookupEnd: number; + readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -13095,9 +14123,9 @@ interface PerformanceTiming { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly secureConnectionStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; - readonly secureConnectionStart: number; toJSON(): any; } @@ -13106,35 +14134,6 @@ declare var 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 { } @@ -13216,12 +14215,11 @@ declare var 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; + new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent; }; interface Position { @@ -13269,10 +14267,21 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; + new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent; }; +interface PromiseRejectionEvent extends Event { + readonly promise: PromiseLike; + readonly reason: any; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: PromiseLike; + reason?: any; +} + interface PushManager { + readonly supportedContentEncodings: ReadonlyArray; getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; subscribe(options?: PushSubscriptionOptionsInit): Promise; @@ -13284,7 +14293,8 @@ declare var PushManager: { }; interface PushSubscription { - readonly endpoint: USVString; + readonly endpoint: string; + readonly expirationTime: number | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): any; @@ -13306,112 +14316,13 @@ declare var 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 | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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; +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } -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; - readonly signal: AbortSignal; - 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; +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDtlsTransportEventMap { @@ -13457,7 +14368,7 @@ interface RTCDtmfSender extends EventTarget { readonly canInsertDTMF: boolean; readonly duration: number; readonly interToneGap: number; - ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null; readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; @@ -13472,19 +14383,10 @@ declare var 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; + sdpMid: string | null; toJSON(): any; } @@ -13589,28 +14491,28 @@ interface RTCPeerConnection extends EventTarget { 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; + onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null; + oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; + onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; readonly remoteDescription: RTCSessionDescription | null; readonly signalingState: RTCSignalingState; - addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise; addStream(stream: MediaStream): void; close(): void; - createAnswer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - createOffer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, options?: RTCOfferOptions): Promise; + createAnswer(options?: RTCOfferOptions): Promise; + createOffer(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; + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit): 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; @@ -13633,10 +14535,14 @@ declare var RTCPeerConnectionIceEvent: { interface RTCRtpReceiverEventMap { "error": Event; + "msdecodercapacitychange": Event; + "msdsh": Event; } interface RTCRtpReceiver extends RTCStatsProvider { onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -13733,433 +14639,122 @@ declare var RTCStatsProvider: { new(): RTCStatsProvider; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; +interface RandomSource { + getRandomValues(array: T): T; } -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; +declare var RandomSource: { + prototype: RandomSource; + new(): RandomSource; }; -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; - lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; - unlockOrientation(): 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; +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 | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + insertNode(node: Node): void; + isPointInRange(node: Node, offset: number): boolean; + selectNode(node: Node): void; + selectNodeContents(node: Node): void; + setEnd(node: Node, offset: number): void; + setEndAfter(node: Node): void; + setEndBefore(node: Node): void; + setStart(node: Node, offset: number): void; + setStartAfter(node: Node): void; + setStartBefore(node: 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 Selection: { - prototype: Selection; - new(): Selection; +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 ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -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; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; }; -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } -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; +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; }; -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 { +interface Request extends 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 signal: AbortSignal | null; + readonly type: RequestType; readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; + clone(): Request; } -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; }; -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; +interface Response extends Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; } -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; +declare var Response: { + prototype: Response; + new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; }; interface SVGAElement extends SVGGraphicsElement, SVGURIReference { @@ -14279,6 +14874,11 @@ declare var SVGAnimatedNumberList: { new(): SVGAnimatedNumberList; }; +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; readonly baseVal: SVGPreserveAspectRatio; @@ -14415,21 +15015,21 @@ interface SVGElementEventMap extends ElementEventMap { "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; +interface SVGElement extends Element, ElementCSSInlineStyle { + readonly className: any; + onclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null; + onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null; + onload: ((this: SVGElement, ev: Event) => any) | null; + onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null; + readonly ownerSVGElement: SVGSVGElement | null; + readonly viewportElement: SVGElement | null; + /** @deprecated */ 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; @@ -14459,7 +15059,9 @@ declare var SVGElementInstance: { }; interface SVGElementInstanceList { + /** @deprecated */ readonly length: number; + /** @deprecated */ item(index: number): SVGElementInstance; } @@ -14942,7 +15544,9 @@ declare var SVGFETurbulenceElement: { }; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { + /** @deprecated */ readonly filterResX: SVGAnimatedInteger; + /** @deprecated */ readonly filterResY: SVGAnimatedInteger; readonly filterUnits: SVGAnimatedEnumeration; readonly height: SVGAnimatedLength; @@ -14950,6 +15554,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + /** @deprecated */ 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; @@ -14962,6 +15567,19 @@ declare var SVGFilterElement: { new(): SVGFilterElement; }; +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 SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; readonly width: SVGAnimatedLength; @@ -15014,12 +15632,15 @@ declare var SVGGradientElement: { }; interface SVGGraphicsElement extends SVGElement, SVGTests { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; + /** @deprecated */ + readonly farthestViewportElement: SVGElement | null; + /** @deprecated */ + readonly nearestViewportElement: SVGElement | null; readonly transform: SVGAnimatedTransformList; getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; + getCTM(): SVGMatrix | null; + getScreenCTM(): SVGMatrix | null; + /** @deprecated */ 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; @@ -15101,22 +15722,6 @@ declare var 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; @@ -15133,6 +15738,22 @@ declare var SVGLineElement: { new(): SVGLineElement; }; +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 SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -15143,12 +15764,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: 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; @@ -15158,12 +15779,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; }; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { @@ -15247,26 +15868,47 @@ declare var SVGNumberList: { }; interface SVGPathElement extends SVGGraphicsElement { + /** @deprecated */ readonly pathSegList: SVGPathSegList; + /** @deprecated */ createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + /** @deprecated */ createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + /** @deprecated */ createSVGPathSegClosePath(): SVGPathSegClosePath; + /** @deprecated */ createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + /** @deprecated */ createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + /** @deprecated */ createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + /** @deprecated */ createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + /** @deprecated */ createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + /** @deprecated */ createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + /** @deprecated */ createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + /** @deprecated */ getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; @@ -15712,6 +16354,84 @@ declare var SVGRectElement: { new(): SVGRectElement; }; +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + contentScriptType: string; + /** @deprecated */ + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: ((this: SVGSVGElement, ev: Event) => any) | null; + onerror: ((this: SVGSVGElement, ev: Event) => any) | null; + onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onunload: ((this: SVGSVGElement, ev: Event) => any) | null; + onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; + /** @deprecated */ + readonly pixelUnitToMillimeterX: number; + /** @deprecated */ + readonly pixelUnitToMillimeterY: number; + /** @deprecated */ + readonly screenPixelToMillimeterX: number; + /** @deprecated */ + readonly screenPixelToMillimeterY: number; + /** @deprecated */ + 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; + /** @deprecated */ + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + /** @deprecated */ + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + /** @deprecated */ + pauseAnimations(): void; + /** @deprecated */ + setCurrentTime(seconds: number): void; + /** @deprecated */ + suspendRedraw(maxWaitMilliseconds: number): number; + /** @deprecated */ + unpauseAnimations(): void; + /** @deprecated */ + unsuspendRedraw(suspendHandleID: number): void; + /** @deprecated */ + 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 SVGScriptElement extends SVGElement, SVGURIReference { type: string; addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -15754,6 +16474,15 @@ declare var SVGStringList: { new(): SVGStringList; }; +interface SVGStylable { + className: any; +} + +declare var SVGStylable: { + prototype: SVGStylable; + new(): SVGStylable; +}; + interface SVGStyleElement extends SVGElement { disabled: boolean; media: string; @@ -15770,69 +16499,6 @@ declare var 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; @@ -15857,6 +16523,27 @@ declare var SVGSymbolElement: { new(): SVGSymbolElement; }; +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 SVGTests { + readonly requiredExtensions: SVGStringList; + /** @deprecated */ + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + /** @deprecated */ + hasExtension(extension: string): boolean; +} + interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; readonly textLength: SVGAnimatedLength; @@ -16003,18 +16690,10 @@ declare var 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; +interface SVGURIReference { + readonly href: SVGAnimatedString; } -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -}; - interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -16023,9 +16702,9 @@ interface SVGUnitTypes { declare var SVGUnitTypes: SVGUnitTypes; interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; + readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; + readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -16040,7 +16719,8 @@ declare var SVGUseElement: { new(): SVGUseElement; }; -interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { +interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ 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; @@ -16076,6 +16756,477 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; +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; + /** @deprecated */ + 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) | null; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + unlockOrientation(): 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 ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + /** @deprecated */ + readonly bufferSize: number; + /** @deprecated */ + onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null; + 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 ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEvent extends Event { + readonly blockedURI: string; + readonly columnNumber: number; + readonly documentURI: string; + readonly effectiveDirective: string; + readonly lineNumber: number; + readonly originalPolicy: string; + readonly referrer: string; + readonly sourceFile: string; + readonly statusCode: number; + readonly violatedDirective: string; +} + +declare var SecurityPolicyViolationEvent: { + prototype: SecurityPolicyViolationEvent; + new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent; +}; + +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 ServiceUIFrameContext { + getCachedFrameMessage(key: string): string; + postFrameMessage(key: string, data: string): void; +} +declare var ServiceUIFrameContext: ServiceUIFrameContext; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + 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; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): 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: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | 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) | null; + readonly pushManager: PushManager; + readonly scope: string; + 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 ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: "open" | "closed"; +} + +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 | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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) | null; + 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 charLength: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance; +} + +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) | null; + onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + 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(): 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, value: string): void; + [key: string]: any; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + readonly key: string | null; + readonly newValue: string | null; + readonly oldValue: string | null; + readonly storageArea: Storage | null; + readonly url: string; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StorageEventInit extends EventInit { + key?: string; + newValue?: string; + oldValue?: string; + storageArea?: Storage; + url: string; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string | null; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet | null; + readonly title: string | null; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index: number): StyleSheet | null; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SyncManager { getTags(): Promise; register(tag: string): Promise; @@ -16087,8 +17238,8 @@ declare var SyncManager: { }; interface Text extends CharacterData { - readonly wholeText: string; readonly assignedSlot: HTMLSlotElement | null; + readonly wholeText: string; splitText(offset: number): Text; } @@ -16097,10 +17248,30 @@ declare var Text: { new(data?: string): Text; }; +interface TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + 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; @@ -16151,10 +17322,10 @@ interface TextTrack extends EventTarget { 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; + mode: TextTrackMode | number; + oncuechange: ((this: TextTrack, ev: Event) => any) | null; + onerror: ((this: TextTrack, ev: Event) => any) | null; + onload: ((this: TextTrack, ev: Event) => any) | null; readonly readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; @@ -16191,8 +17362,8 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { endTime: number; id: string; - onenter: (this: TextTrackCue, ev: Event) => any; - onexit: (this: TextTrackCue, ev: Event) => any; + onenter: ((this: TextTrackCue, ev: Event) => any) | null; + onexit: ((this: TextTrackCue, ev: Event) => any) | null; pauseOnExit: boolean; startTime: number; text: string; @@ -16278,6 +17449,7 @@ interface TouchEvent extends UIEvent { readonly shiftKey: boolean; readonly targetTouches: TouchList; readonly touches: TouchList; + /** @deprecated */ readonly which: number; } @@ -16286,6 +17458,12 @@ declare var TouchEvent: { new(type: string, touchEventInit?: TouchEventInit): TouchEvent; }; +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + interface TouchList { readonly length: number; item(index: number): Touch | null; @@ -16319,17 +17497,18 @@ declare var TransitionEvent: { interface TreeWalker { currentNode: Node; + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; + firstChild(): Node | null; + lastChild(): Node | null; + nextNode(): Node | null; + nextSibling(): Node | null; + parentNode(): Node | null; + previousNode(): Node | null; + previousSibling(): Node | null; } declare var TreeWalker: { @@ -16348,15 +17527,6 @@ declare var 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; @@ -16368,8 +17538,8 @@ interface URL { port: string; protocol: string; search: string; - username: string; readonly searchParams: URLSearchParams; + username: string; toString(): string; } @@ -16380,6 +17550,142 @@ declare var URL: { revokeObjectURL(url: string): 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; + new (init?: string | URLSearchParams): URLSearchParams; +}; + +interface VRDisplay extends EventTarget { + readonly capabilities: VRDisplayCapabilities; + depthFar: number; + depthNear: number; + readonly displayId: number; + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + readonly stageParameters: VRStageParameters | null; + cancelAnimationFrame(handle: number): void; + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + getFrameData(frameData: VRFrameData): boolean; + getLayers(): VRLayer[]; + /** @deprecated */ + getPose(): VRPose; + requestAnimationFrame(callback: FrameRequestCallback): number; + requestPresent(layers: VRLayer[]): Promise; + resetPose(): void; + submitFrame(pose?: VRPose): void; +} + +declare var VRDisplay: { + prototype: VRDisplay; + new(): VRDisplay; +}; + +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} + +declare var VRDisplayCapabilities: { + prototype: VRDisplayCapabilities; + new(): VRDisplayCapabilities; +}; + +interface VRDisplayEvent extends Event { + readonly display: VRDisplay; + readonly reason: VRDisplayEventReason | null; +} + +declare var VRDisplayEvent: { + prototype: VRDisplayEvent; + new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent; +}; + +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} + +declare var VREyeParameters: { + prototype: VREyeParameters; + new(): VREyeParameters; +}; + +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} + +declare var VRFieldOfView: { + prototype: VRFieldOfView; + new(): VRFieldOfView; +}; + +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} + +declare var VRFrameData: { + prototype: VRFrameData; + new(): VRFrameData; +}; + +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} + +declare var VRPose: { + prototype: VRPose; + new(): VRPose; +}; + interface ValidityState { readonly badInput: boolean; readonly customError: boolean; @@ -16388,10 +17694,10 @@ interface ValidityState { readonly rangeUnderflow: boolean; readonly stepMismatch: boolean; readonly tooLong: boolean; + readonly tooShort: boolean; readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; - readonly tooShort: boolean; } declare var ValidityState: { @@ -16434,9 +17740,9 @@ interface VideoTrackListEventMap { 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; + onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: VideoTrackList, ev: Event) => any) | null; + onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; @@ -16452,6 +17758,137 @@ declare var VideoTrackList: { new(): VideoTrackList; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly RGB32F_EXT: number; + readonly RGBA32F_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + 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_SRGB8_ALPHA8_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_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; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +}; + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_SRGB_S3TC_DXT1_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_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +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 WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_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 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 DRAW_BUFFER0_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 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 MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + interface WaveShaperNode extends AudioNode { curve: Float32Array | null; oversample: OverSampleType; @@ -16463,8 +17900,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -16484,44 +17921,6 @@ declare var 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; @@ -16598,8 +17997,8 @@ interface WebGLRenderingContext { 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; + bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void; + bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void; checkFramebufferStatus(target: number): number; clear(mask: number): void; clearColor(red: number, green: number, blue: number, alpha: number): void; @@ -16607,8 +18006,8 @@ interface WebGLRenderingContext { 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; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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; @@ -16698,7 +18097,7 @@ interface WebGLRenderingContext { 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; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | 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; @@ -16863,13 +18262,13 @@ interface WebGLRenderingContext { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -16894,9 +18293,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -16926,18 +18325,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -16971,20 +18370,6 @@ interface WebGLRenderingContext { 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; @@ -17017,9 +18402,23 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -17165,13 +18564,13 @@ declare var WebGLRenderingContext: { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -17196,9 +18595,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -17228,18 +18627,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -17273,20 +18672,6 @@ declare var WebGLRenderingContext: { 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; @@ -17319,9 +18704,23 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -17382,6 +18781,9 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; +interface WebGLVertexArrayObjectOES { +} + interface WebKitCSSMatrix { a: number; b: number; @@ -17482,18 +18884,6 @@ declare var 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; @@ -17502,18 +18892,18 @@ interface WebSocketEventMap { } interface WebSocket extends EventTarget { - binaryType: string; + binaryType: BinaryType; 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; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; readonly protocol: string; readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: USVString | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; @@ -17558,8 +18948,6 @@ declare var WheelEvent: { interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "afterprint": Event; - "beforeprint": Event; "beforeunload": BeforeUnloadEvent; "blur": FocusEvent; "canplay": Event; @@ -17581,7 +18969,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; @@ -17603,21 +18991,21 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "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; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -17647,19 +19035,32 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "touchstart": TouchEvent; "unload": Event; "volumechange": Event; + "vrdisplayactivate": Event; + "vrdisplayblur": Event; + "vrdisplayconnect": Event; + "vrdisplaydeactivate": Event; + "vrdisplaydisconnect": Event; + "vrdisplayfocus": Event; + "vrdisplaypointerrestricted": Event; + "vrdisplaypointerunrestricted": Event; + "vrdisplaypresentchange": Event; "waiting": Event; } interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { + Blob: typeof Blob; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; readonly applicationCache: ApplicationCache; readonly caches: CacheStorage; readonly clientInformation: Navigator; readonly closed: boolean; readonly crypto: Crypto; + customElements: CustomElementRegistry; defaultStatus: string; readonly devicePixelRatio: number; - readonly document: Document; readonly doNotTrack: string; + readonly document: Document; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -17669,7 +19070,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly innerWidth: number; readonly isSecureContext: boolean; readonly length: number; - readonly location: Location; + location: Location; readonly locationbar: BarProp; readonly menubar: BarProp; readonly msContentScript: ExtensionScriptApis; @@ -17677,99 +19078,106 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + onabort: ((this: Window, ev: UIEvent) => any) | null; + onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; + onblur: ((this: Window, ev: FocusEvent) => any) | null; + oncanplay: ((this: Window, ev: Event) => any) | null; + oncanplaythrough: ((this: Window, ev: Event) => any) | null; + onchange: ((this: Window, ev: Event) => any) | null; + onclick: ((this: Window, ev: MouseEvent) => any) | null; + oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; + oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; + ondblclick: ((this: Window, ev: MouseEvent) => any) | null; + ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; + ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; + ondrag: ((this: Window, ev: DragEvent) => any) | null; + ondragend: ((this: Window, ev: DragEvent) => any) | null; + ondragenter: ((this: Window, ev: DragEvent) => any) | null; + ondragleave: ((this: Window, ev: DragEvent) => any) | null; + ondragover: ((this: Window, ev: DragEvent) => any) | null; + ondragstart: ((this: Window, ev: DragEvent) => any) | null; + ondrop: ((this: Window, ev: DragEvent) => any) | null; + ondurationchange: ((this: Window, ev: Event) => any) | null; + onemptied: ((this: Window, ev: Event) => any) | null; + onended: ((this: Window, ev: Event) => any) | null; 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; + onfocus: ((this: Window, ev: FocusEvent) => any) | null; + onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; + oninput: ((this: Window, ev: Event) => any) | null; + oninvalid: ((this: Window, ev: Event) => any) | null; + onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; + onload: ((this: Window, ev: Event) => any) | null; + onloadeddata: ((this: Window, ev: Event) => any) | null; + onloadedmetadata: ((this: Window, ev: Event) => any) | null; + onloadstart: ((this: Window, ev: Event) => any) | null; + onmessage: ((this: Window, ev: MessageEvent) => any) | null; + onmousedown: ((this: Window, ev: MouseEvent) => any) | null; + onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; + onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; + onmousemove: ((this: Window, ev: MouseEvent) => any) | null; + onmouseout: ((this: Window, ev: MouseEvent) => any) | null; + onmouseover: ((this: Window, ev: MouseEvent) => any) | null; + onmouseup: ((this: Window, ev: MouseEvent) => any) | null; + onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; + onmsgesturechange: ((this: Window, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; + onmsgestureend: ((this: Window, ev: Event) => any) | null; + onmsgesturehold: ((this: Window, ev: Event) => any) | null; + onmsgesturestart: ((this: Window, ev: Event) => any) | null; + onmsgesturetap: ((this: Window, ev: Event) => any) | null; + onmsinertiastart: ((this: Window, ev: Event) => any) | null; + onmspointercancel: ((this: Window, ev: Event) => any) | null; + onmspointerdown: ((this: Window, ev: Event) => any) | null; + onmspointerenter: ((this: Window, ev: Event) => any) | null; + onmspointerleave: ((this: Window, ev: Event) => any) | null; + onmspointermove: ((this: Window, ev: Event) => any) | null; + onmspointerout: ((this: Window, ev: Event) => any) | null; + onmspointerover: ((this: Window, ev: Event) => any) | null; + onmspointerup: ((this: Window, ev: Event) => any) | null; + onoffline: ((this: Window, ev: Event) => any) | null; + ononline: ((this: Window, ev: Event) => any) | null; + onorientationchange: ((this: Window, ev: Event) => any) | null; + onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpause: ((this: Window, ev: Event) => any) | null; + onplay: ((this: Window, ev: Event) => any) | null; + onplaying: ((this: Window, ev: Event) => any) | null; + onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; + onprogress: ((this: Window, ev: ProgressEvent) => any) | null; + onratechange: ((this: Window, ev: Event) => any) | null; + onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; + onreset: ((this: Window, ev: Event) => any) | null; + onresize: ((this: Window, ev: UIEvent) => any) | null; + onscroll: ((this: Window, ev: UIEvent) => any) | null; + onseeked: ((this: Window, ev: Event) => any) | null; + onseeking: ((this: Window, ev: Event) => any) | null; + onselect: ((this: Window, ev: UIEvent) => any) | null; + onstalled: ((this: Window, ev: Event) => any) | null; + onstorage: ((this: Window, ev: StorageEvent) => any) | null; + onsubmit: ((this: Window, ev: Event) => any) | null; + onsuspend: ((this: Window, ev: Event) => any) | null; + ontimeupdate: ((this: Window, ev: Event) => any) | null; 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; + onunload: ((this: Window, ev: Event) => any) | null; + onvolumechange: ((this: Window, ev: Event) => any) | null; + onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplayblur: ((this: Window, ev: Event) => any) | null; + onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + onwaiting: ((this: Window, ev: Event) => any) | null; + readonly opener: any; + readonly orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; readonly pageXOffset: number; @@ -17782,9 +19190,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; - readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; + readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -17793,20 +19201,18 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + 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; departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; getSelection(): Selection; matchMedia(mediaQuery: string): MediaQueryList; moveBy(x?: number, y?: number): void; @@ -17820,19 +19226,17 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window requestAnimationFrame(callback: FrameRequestCallback): number; resizeBy(x?: number, y?: number): void; resizeTo(x?: number, y?: number): void; + scroll(options?: ScrollToOptions): void; scroll(x?: number, y?: number): void; + scrollBy(options?: ScrollToOptions): void; scrollBy(x?: number, y?: number): void; + scrollTo(options?: ScrollToOptions): 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; @@ -17844,12 +19248,79 @@ declare var Window: { new(): Window; }; +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowEventHandlersEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "hashchange": HashChangeEvent; + "message": MessageEvent; + "offline": Event; + "online": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface WindowEventHandlers { + onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; + onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; + ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; + onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers extends 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 WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; } interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: Worker, ev: MessageEvent) => any; + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** @deprecated */ postMessage(message: any, transfer?: any[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -17863,6 +19334,41 @@ declare var Worker: { new(stringUrl: string): Worker; }; +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +declare var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; +}; + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: any): Promise; +} + +declare var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(): WritableStreamDefaultWriter; +}; + 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; @@ -17880,7 +19386,8 @@ interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -17892,15 +19399,12 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { 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; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): 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; @@ -17924,6 +19428,30 @@ declare var XMLHttpRequest: { readonly UNSENT: 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) | null; + onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + 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 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; @@ -18027,1070 +19555,16 @@ declare var 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; +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: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[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 ElementCreationOptions { - is?: 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 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; -} - -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 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; - 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; -} - -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; -} - -interface AnimationKeyFrame { - offset?: number | null | (number | null)[]; - easing?: string | string[]; - [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; -} - -interface AnimationOptions { - id?: string; - delay?: number; - direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; - duration?: number; - easing?: string; - endDelay?: number; - fill?: "none" | "forwards" | "backwards" | "both"| "auto"; - iterationStart?: number; - iterations?: number; -} - -interface AnimationTimeline { - readonly currentTime: number | null; -} - -interface ComputedTimingProperties { - endTime: number; - activeDuration: number; - localTime: number | null; - progress: number | null; - currentIteration: number | null; -} - -interface AnimationEffectReadOnly { - readonly timing: number; - getComputedTiming(): ComputedTimingProperties; -} - -interface AnimationPlaybackEventInit extends EventInit { - currentTime?: number | null; - timelineTime?: number | null; -} - -interface AnimationPlaybackEvent extends Event { - readonly currentTime: number | null; - readonly timelineTime: number | null; -} - -declare var AnimationPlaybackEvent: { - prototype: AnimationPlaybackEvent; - new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; -}; - -interface Animation { - currentTime: number | null; - effect: AnimationEffectReadOnly; - readonly finished: Promise; - id: string; - readonly pending: boolean; - readonly playState: "idle" | "running" | "paused" | "finished"; - playbackRate: number; - readonly ready: Promise; - startTime: number; - timeline: AnimationTimeline; - oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; - onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; - cancel(): void; - finish(): void; - pause(): void; - play(): void; - reverse(): void; -} - -declare var Animation: { - prototype: Animation; - new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; }; declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; @@ -19098,66 +19572,95 @@ declare type EventListenerOrEventListenerObject = EventListener | EventListenerO interface DecodeErrorCallback { (error: DOMException): void; } + interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } + interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; } + +interface EventHandlerNonNull { + (event: Event): any; +} + interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, 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 MediaQueryListListener { + (mql: MediaQueryList): void; } + 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 WritableStreamChunkCallback { + (chunk: any, controller: WritableStreamDefaultController): void; +} + +interface WritableStreamDefaultControllerCallback { + (controller: WritableStreamDefaultController): void; +} + +interface WritableStreamErrorCallback { + (reason: string): void; +} + interface HTMLElementTagNameMap { "a": HTMLAnchorElement; "abbr": HTMLElement; @@ -19284,7 +19787,6 @@ interface HTMLElementTagNameMap { "var": HTMLElement; "video": HTMLVideoElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } @@ -19347,18 +19849,28 @@ interface SVGElementTagNameMap { /** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ 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 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 Blob: typeof Blob; +declare var URL: typeof URL; +declare var URLSearchParams: typeof URLSearchParams; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; declare var closed: boolean; declare var crypto: Crypto; +declare var customElements: CustomElementRegistry; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var document: Document; declare var doNotTrack: string; +declare var document: Document; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -19376,97 +19888,104 @@ 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 onabort: ((this: Window, ev: UIEvent) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +declare var onchange: ((this: Window, ev: Event) => any) | null; +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; +declare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; +declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +declare var onemptied: ((this: Window, ev: Event) => any) | null; +declare var onended: ((this: Window, ev: Event) => any) | null; 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 onfocus: ((this: Window, ev: FocusEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onload: ((this: Window, ev: Event) => any) | null; +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadstart: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; +declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; +declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; +declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; +declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; +declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; +declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; +declare var onmspointermove: ((this: Window, ev: Event) => any) | null; +declare var onmspointerout: ((this: Window, ev: Event) => any) | null; +declare var onmspointerover: ((this: Window, ev: Event) => any) | null; +declare var onmspointerup: ((this: Window, ev: Event) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onorientationchange: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpause: ((this: Window, ev: Event) => any) | null; +declare var onplay: ((this: Window, ev: Event) => any) | null; +declare var onplaying: ((this: Window, ev: Event) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onratechange: ((this: Window, ev: Event) => any) | null; +declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onseeked: ((this: Window, ev: Event) => any) | null; +declare var onseeking: ((this: Window, ev: Event) => any) | null; +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; 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 onunload: ((this: Window, ev: Event) => any) | null; +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; +declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; @@ -19481,9 +20000,9 @@ 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 scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -19492,17 +20011,18 @@ 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 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 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 getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; declare function getSelection(): Selection; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; @@ -19516,23 +20036,21 @@ 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(options?: ScrollToOptions): void; declare function scroll(x?: number, y?: number): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(options?: ScrollToOptions): 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 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; @@ -19543,26 +20061,36 @@ 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 onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; 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 fetch(input?: Request | string, 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 ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type IDBValidKey = number | string | Date | IDBArrayKey; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = Blob | BufferSource | FormData | string; +type MutationRecordType = "attributes" | "characterData" | "childList"; +type AAGUID = string; +type BodyInit = any; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; @@ -19584,9 +20112,6 @@ 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; @@ -19595,35 +20120,32 @@ 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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type AppendMode = "segments" | "sequence"; +type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "suspended" | "running" | "closed"; +type BinaryType = "blob" | "arraybuffer"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanPlayTypeResult = "" | "maybe" | "probably"; type CanvasFillRule = "nonzero" | "evenodd"; type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; +type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; +type EndOfStreamError = "network" | "decode"; type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; +type GamepadHand = "" | "left" | "right"; +type GamepadHapticActuatorType = "vibration"; type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type GamepadMappingType = "" | "standard"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; 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"; @@ -19631,25 +20153,23 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaStreamTrackState = "live" | "ended"; 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 PanningModelType = "equalpower" | "HRTF"; +type PaymentComplete = "success" | "fail" | "unknown"; 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"; @@ -19657,9 +20177,9 @@ 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 RTCIceGatherPolicy = "all" | "nohost" | "relay"; 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"; @@ -19670,9 +20190,22 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " 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 ReadyState = "closed" | "open" | "ended"; +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 ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; +type TextTrackMode = "disabled" | "hidden" | "showing"; type Transport = "usb" | "nfc" | "ble"; +type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; +type VREye = "left" | "right"; type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 32d6620a4eb..44bcc45d6f3 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -18,7 +18,6 @@ and limitations under the License. /// - ///////////////////////////// /// DOM APIs ///////////////////////////// @@ -31,10 +30,49 @@ interface Account { rpDisplayName: string; } +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + interface Algorithm { name: string; } +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + interface AnimationEventInit extends EventInit { animationName?: string; elapsedTime?: number; @@ -43,10 +81,71 @@ interface AnimationEventInit extends EventInit { interface AssertionOptions { allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioContextInfo { + currentTime?: number; + sampleRate?: number; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioParamDescriptor { + defaultValue?: number; + maxValue?: number; + minValue?: number; + name?: string; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: number; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface ByteLengthChunk { + byteLength?: number; +} + interface CacheQueryOptions { cacheName?: string; ignoreMethod?: boolean; @@ -54,6 +153,14 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + interface ClientData { challenge: string; extensions?: WebAuthnExtensions; @@ -63,6 +170,12 @@ interface ClientData { tokenBinding?: string; } +interface ClientQueryOptions { + includeReserved?: boolean; + includeUncontrolled?: boolean; + type?: ClientTypes; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; @@ -77,6 +190,10 @@ interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation arrayOfDomainStrings?: string[]; } +interface ConstantSourceOptions { + offset?: number; +} + interface ConstrainBooleanParameters { exact?: boolean; ideal?: boolean; @@ -102,10 +219,27 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + interface CustomEventInit extends EventInit { detail?: T; } +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + interface DeviceAccelerationDict { x?: number | null; y?: number | null; @@ -136,18 +270,39 @@ interface DeviceRotationRateDict { gamma?: number | null; } -interface DOMRectInit { - height?: number; - width?: number; - x?: number; - y?: number; -} - interface DoubleRange { max?: number; min?: number; } +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: string; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: string | Algorithm; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -157,9 +312,13 @@ interface ErrorEventInit extends EventInit { } interface EventInit { - scoped?: boolean; bubbles?: boolean; cancelable?: boolean; + scoped?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; } interface EventModifierInit extends UIEventInit { @@ -184,6 +343,24 @@ interface ExceptionInformation { domain?: string | null; } +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: object | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + request: Request; + reservedClientId?: string; + targetClientId?: string; +} + interface FocusEventInit extends UIEventInit { relatedTarget?: EventTarget | null; } @@ -203,8 +380,12 @@ interface FocusNavigationOrigin { originWidth?: number; } +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + interface GamepadEventInit extends EventInit { - gamepad?: Gamepad | null; + gamepad?: Gamepad; } interface GetNotificationOptions { @@ -212,8 +393,29 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string | null; - oldURL?: string | null; + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: string | Algorithm; + info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface HmacImportParams extends Algorithm { + hash: string | Algorithm; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: string | Algorithm; + length?: number; } interface IDBIndexParameters { @@ -226,10 +428,15 @@ interface IDBObjectStoreParameters { keyPath?: string | string[]; } +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + interface IntersectionObserverEntryInit { - isIntersecting: boolean; boundingClientRect: DOMRectInit; intersectionRect: DOMRectInit; + isIntersecting: boolean; rootBounds: DOMRectInit; target: Element; time: number; @@ -241,8 +448,29 @@ interface IntersectionObserverInit { threshold?: number | number[]; } +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + interface KeyAlgorithm { - name?: string; + name: string; } interface KeyboardEventInit extends EventModifierInit { @@ -257,125 +485,6 @@ interface LongRange { 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; @@ -466,6 +575,16 @@ interface MSCredentialSpec { type: MSCredentialType; } +interface MSDCCEventInit extends EventInit { + maxFr?: number; + maxFs?: number; +} + +interface MSDSHEventInit extends EventInit { + sources?: number[]; + timestamp?: number; +} + interface MSDelay { roundTrip?: number; roundTripMax?: number; @@ -483,7 +602,13 @@ interface MSDescription extends RTCStats { interface MSFIDOCredentialParameters extends MSCredentialParameters { algorithm?: string | Algorithm; - authenticators?: AAGUID[]; + authenticators?: string[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSIceWarningFlags { @@ -511,12 +636,6 @@ interface MSIceWarningFlags { useCandidateChecksFailed?: boolean; } -interface MSIPAddressInfo { - ipAddr?: string; - manufacturerMacAddrMask?: string; - port?: number; -} - interface MSJitter { interArrival?: number; interArrivalMax?: number; @@ -545,8 +664,8 @@ interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; - interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; + interfaceTypeWireless?: boolean; } interface MSOutboundNetwork extends MSNetwork { @@ -583,8 +702,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { iceRole?: RTCIceRole; iceWarningFlags?: MSIceWarningFlags; interfaces?: MSNetworkInterfaceType; - localAddress?: string; localAddrType?: MSIceAddrType; + localAddress?: string; localInterface?: MSNetworkInterfaceType; localMR?: string; localMRTCPPort?: number; @@ -598,8 +717,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { portRangeMax?: number; portRangeMin?: number; protocol?: RTCIceProtocol; - remoteAddress?: string; remoteAddrType?: MSIceAddrType; + remoteAddress?: string; remoteMR?: string; remoteMRTCPPort?: number; remoteSite?: string; @@ -668,6 +787,133 @@ interface MSVideoSendPayload extends MSVideoPayload { sendVideoStreamsMax?: number; } +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +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 MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + channelCount?: number | ConstrainLongRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + displaySurface?: string | string[] | ConstrainDOMStringParameters; + echoCancellation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + latency?: number | ConstrainDoubleRange; + logicalSurface?: boolean | ConstrainBooleanParameters; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +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 { + channel?: string; + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: Window | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + interface MsZoomToOptions { animate?: string; contentX?: number; @@ -687,8 +933,14 @@ interface MutationObserverInit { subtree?: boolean; } +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; +} + interface NotificationOptions { body?: string; + data?: any; dir?: NotificationDirection; icon?: string; lang?: string; @@ -699,18 +951,49 @@ interface ObjectURLOptions { oneTimeOnly?: boolean; } +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + interface PaymentCurrencyAmount { currency: string; currencySystem?: string; value: string; } -interface PaymentDetails { +interface PaymentDetailsBase { displayItems?: PaymentItem[]; - error?: string; modifiers?: PaymentDetailsModifier[]; shippingOptions?: PaymentShippingOption[]; - total?: PaymentItem; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; } interface PaymentDetailsModifier { @@ -720,6 +1003,11 @@ interface PaymentDetailsModifier { total?: PaymentItem; } +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + total?: PaymentItem; +} + interface PaymentItem { amount: PaymentCurrencyAmount; label: string; @@ -749,10 +1037,21 @@ interface PaymentShippingOption { selected?: boolean; } +interface Pbkdf2Params extends Algorithm { + hash: string | Algorithm; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + interface PeriodicWaveConstraints { disableNormalization?: boolean; } +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[]; + real?: number[]; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -780,35 +1079,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface PushEventInit extends ExtendableEventInit { + data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | null; + applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; userVisibleOnly?: boolean; } -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - signal?: AbortSignal; - body?: Blob | BufferSource | FormData | string | null; - 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 QueuingStrategy { + highWaterMark?: number; + size?: WritableStreamChunkCallback; } interface RTCConfiguration { @@ -818,6 +1105,10 @@ interface RTCConfiguration { peerIdentity?: string; } +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + interface RTCDtlsFingerprint { algorithm?: string; value?: string; @@ -828,10 +1119,6 @@ interface RTCDtlsParameters { role?: RTCDtlsRole; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCIceCandidateAttributes extends RTCStats { addressSourceUrl?: string; candidateType?: RTCStatsIceCandidateType; @@ -859,8 +1146,8 @@ interface RTCIceCandidateDictionary { interface RTCIceCandidateInit { candidate?: string; - sdpMid?: string; sdpMLineIndex?: number; + sdpMid?: string; } interface RTCIceCandidatePair { @@ -915,13 +1202,13 @@ interface RTCMediaStreamTrackStats extends RTCStats { echoReturnLoss?: number; echoReturnLossEnhancement?: number; frameHeight?: number; + frameWidth?: number; framesCorrupted?: number; framesDecoded?: number; framesDropped?: number; framesPerSecond?: number; framesReceived?: number; framesSent?: number; - frameWidth?: number; remoteSource?: boolean; ssrcIds?: string[]; trackIdentifier?: string; @@ -945,6 +1232,20 @@ interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + mediaType?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtcpFeedback { parameter?: string; type?: string; @@ -966,9 +1267,9 @@ interface RTCRtpCapabilities { interface RTCRtpCodecCapability { clockRate?: number; kind?: string; - maxptime?: number; maxSpatialLayers?: number; maxTemporalLayers?: number; + maxptime?: number; name?: string; numChannels?: number; options?: any; @@ -985,7 +1286,7 @@ interface RTCRtpCodecParameters { name?: string; numChannels?: number; parameters?: any; - payloadType?: any; + payloadType?: number; ptime?: number; rtcpFeedback?: RTCRtcpFeedback[]; } @@ -1044,19 +1345,6 @@ 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; @@ -1108,8 +1396,70 @@ interface RTCTransportStats extends RTCStats { selectedCandidatePairId?: string; } +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: string | Algorithm; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: string | Algorithm; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + interface ScopedCredentialDescriptor { - id: BufferSource; + id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; transports?: Transport[]; type: ScopedCredentialType; } @@ -1117,7 +1467,7 @@ interface ScopedCredentialDescriptor { interface ScopedCredentialOptions { excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } @@ -1126,6 +1476,19 @@ interface ScopedCredentialParameters { type: ScopedCredentialType; } +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; @@ -1136,11 +1499,16 @@ interface ServiceWorkerMessageEventInit extends EventInit { interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; + charLength?: number; elapsedTime?: number; name?: string; utterance?: SpeechSynthesisUtterance | null; } +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + interface StoreExceptionsInformation extends ExceptionInformation { detailURI?: string | null; explanationString?: string | null; @@ -1151,6 +1519,20 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat arrayOfDomainStrings?: string[]; } +interface SyncEventInit extends ExtendableEventInit { + lastChance?: boolean; + tag: string; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } @@ -1165,14 +1547,43 @@ interface UIEventInit extends EventInit { view?: Window | null; } +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCallback; + start: WritableStreamDefaultControllerCallback; + write?: WritableStreamChunkCallback; +} + +interface VRDisplayEventInit extends EventInit { + display: VRDisplay; + reason?: VRDisplayEventReason; +} + +interface VRLayer { + leftBounds?: number[] | null; + rightBounds?: number[] | null; + source?: HTMLCanvasElement | null; +} + +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[]; + oversample?: OverSampleType; +} + interface WebAuthnExtensions { } interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; antialias?: boolean; depth?: boolean; + failIfMajorPerformanceCaveat?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; stencil?: boolean; @@ -1199,6 +1610,67 @@ type WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMErr type WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; }; +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 AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + 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 AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1216,23 +1688,39 @@ declare var 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; +interface Animation { + currentTime: number | null; + effect: AnimationEffectReadOnly; + readonly finished: Promise; + id: string; + readonly pending: boolean; + readonly playState: "idle" | "running" | "paused" | "finished"; + playbackRate: number; + readonly ready: Promise; + startTime: number; + timeline: AnimationTimeline; + cancel(): void; + finish(): void; + oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; + onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; + pause(): void; + play(): void; + reverse(): void; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; }; +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + 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: { @@ -1240,6 +1728,43 @@ declare var AnimationEvent: { new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; }; +interface AnimationKeyFrame { + easing?: string | string[]; + offset?: number | null | (number | null)[]; + [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; +} + +interface AnimationOptions { + delay?: number; + direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; + duration?: number; + easing?: string; + endDelay?: number; + fill?: "none" | "forwards" | "backwards" | "both"| "auto"; + id?: string; + iterationStart?: number; + iterations?: number; +} + +interface AnimationPlaybackEvent extends Event { + readonly currentTime: number | null; + readonly timelineTime: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +interface AnimationTimeline { + readonly currentTime: number | null; +} + interface ApplicationCacheEventMap { "cached": Event; "checking": Event; @@ -1252,14 +1777,14 @@ interface ApplicationCacheEventMap { } 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; + oncached: ((this: ApplicationCache, ev: Event) => any) | null; + onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + onerror: ((this: ApplicationCache, ev: Event) => any) | null; + onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; readonly status: number; abort(): void; swapCache(): void; @@ -1287,9 +1812,13 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; +interface AssignedNodesOptions { + flatten?: boolean; +} + interface Attr extends Node { readonly name: string; - readonly ownerElement: Element; + readonly ownerElement: Element | null; readonly prefix: string | null; readonly specified: boolean; value: string; @@ -1316,7 +1845,7 @@ declare var AudioBuffer: { }; interface AudioBufferSourceNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface AudioBufferSourceNode extends AudioNode { @@ -1325,7 +1854,7 @@ interface AudioBufferSourceNode extends AudioNode { loop: boolean; loopEnd: number; loopStart: number; - onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null; readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; @@ -1348,7 +1877,7 @@ interface AudioContextBase extends EventTarget { readonly currentTime: number; readonly destination: AudioDestinationNode; readonly listener: AudioListener; - onstatechange: (this: AudioContext, ev: Event) => any; + onstatechange: ((this: AudioContext, ev: Event) => any) | null; readonly sampleRate: number; readonly state: AudioContextState; close(): Promise; @@ -1398,10 +1927,15 @@ declare var AudioDestinationNode: { }; interface AudioListener { + /** @deprecated */ dopplerFactor: number; + /** @deprecated */ speedOfSound: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -1419,9 +1953,13 @@ interface AudioNode extends EventTarget { 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; + disconnect(): void; + disconnect(output: number): void; + disconnect(destination: AudioNode): void; + disconnect(destination: AudioNode, output: number): void; + disconnect(destination: AudioNode, output: number, input: number): void; + disconnect(destination: AudioParam): void; + disconnect(destination: AudioParam, output: number): void; } declare var AudioNode: { @@ -1432,12 +1970,12 @@ declare var AudioNode: { interface AudioParam { readonly defaultValue: number; value: number; - cancelScheduledValues(startTime: number): AudioParam; + cancelScheduledValues(cancelTime: 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; + setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam; } declare var AudioParam: { @@ -1478,9 +2016,9 @@ interface AudioTrackListEventMap { 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; + onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: AudioTrackList, ev: Event) => any) | null; + onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -1513,11 +2051,33 @@ declare var BeforeUnloadEvent: { new(): BeforeUnloadEvent; }; +interface BhxBrowser { + readonly lastError: DOMException; + checkMatchesGlobExpression(pattern: string, value: string): boolean; + checkMatchesUriExpression(pattern: string, value: string): boolean; + clearLastError(): void; + currentWindowId(): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + getThisAddress(): any; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericListenerHandler(eventHandler: Function): void; + setLastError(parameters: string): void; + webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void; +} + +declare var BhxBrowser: { + prototype: BhxBrowser; + new(): BhxBrowser; +}; + interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; - readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1540,113 +2100,50 @@ declare var 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; +interface BlobPropertyBag { + endings?: string; + type?: string; } -declare var Cache: { - prototype: Cache; - new(): Cache; +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + close(): void; + postMessage(message: any): 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 CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): Promise; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; } -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -}; - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; +interface ByteLengthQueuingStrategy { + highWaterMark: number; + size(chunk?: any): number; } -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; +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -1657,190 +2154,8 @@ declare var 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 { + escape(value: string): string; supports(property: string, value?: string): boolean; } declare var CSS: CSS; @@ -1900,7 +2215,7 @@ interface CSSKeyframesRule extends CSSRule { name: string; appendRule(rule: string): void; deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; + findRule(rule: string): CSSKeyframeRule | null; } declare var CSSKeyframesRule: { @@ -1941,14 +2256,14 @@ declare var CSSPageRule: { interface CSSRule { cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; + readonly parentRule: CSSRule | null; + readonly parentStyleSheet: CSSStyleSheet | null; 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 KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1964,8 +2279,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAME_RULE: number; readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1977,7 +2292,7 @@ declare var CSSRule: { interface CSSRuleList { readonly length: number; - item(index: number): CSSRule; + item(index: number): CSSRule | null; [index: number]: CSSRule; } @@ -1989,8 +2304,8 @@ declare var CSSRuleList: { interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignmentBaseline: string | null; alignSelf: string | null; + alignmentBaseline: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -2066,9 +2381,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; - columns: string | null; columnSpan: string | null; columnWidth: any; + columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -2102,11 +2417,32 @@ interface CSSStyleDeclaration { fontStyle: string | null; fontVariant: string | null; fontWeight: string | null; + gap: string | null; glyphOrientationHorizontal: string | null; glyphOrientationVertical: string | null; + grid: string | null; + gridArea: string | null; + gridAutoColumns: string | null; + gridAutoFlow: string | null; + gridAutoRows: string | null; + gridColumn: string | null; + gridColumnEnd: string | null; + gridColumnGap: string | null; + gridColumnStart: string | null; + gridGap: string | null; + gridRow: string | null; + gridRowEnd: string | null; + gridRowGap: string | null; + gridRowStart: string | null; + gridTemplate: string | null; + gridTemplateAreas: string | null; + gridTemplateColumns: string | null; + gridTemplateRows: string | null; height: string | null; imeMode: string | null; justifyContent: string | null; + justifyItems: string | null; + justifySelf: string | null; kerning: string | null; layoutGrid: string | null; layoutGridChar: string | null; @@ -2133,29 +2469,30 @@ interface CSSStyleDeclaration { markerMid: string | null; markerStart: string | null; mask: string | null; + maskImage: 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; + msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumns: string | null; msGridColumnSpan: any; + msGridColumns: string | null; msGridRow: any; msGridRowAlign: string | null; - msGridRows: string | null; msGridRowSpan: any; + msGridRows: string | null; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -2184,6 +2521,8 @@ interface CSSStyleDeclaration { msWrapFlow: string; msWrapMargin: any; msWrapThrough: string; + objectFit: string | null; + objectPosition: string | null; opacity: string | null; order: string | null; orphans: string | null; @@ -2204,13 +2543,16 @@ interface CSSStyleDeclaration { pageBreakBefore: string | null; pageBreakInside: string | null; readonly parentRule: CSSRule; + penAction: string | null; perspective: string | null; perspectiveOrigin: string | null; pointerEvents: string | null; position: string | null; quotes: string | null; + resize: string | null; right: string | null; rotate: string | null; + rowGap: string | null; rubyAlign: string | null; rubyOverhang: string | null; rubyPosition: string | null; @@ -2229,6 +2571,7 @@ interface CSSStyleDeclaration { textAlign: string | null; textAlignLast: string | null; textAnchor: string | null; + textCombineUpright: string | null; textDecoration: string | null; textIndent: string | null; textJustify: string | null; @@ -2250,6 +2593,7 @@ interface CSSStyleDeclaration { transitionTimingFunction: string | null; translate: string | null; unicodeBidi: string | null; + userSelect: string | null; verticalAlign: string | null; visibility: string | null; webkitAlignContent: string | null; @@ -2291,9 +2635,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; - webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; + webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2332,13 +2676,11 @@ interface CSSStyleDeclaration { 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; + setProperty(propertyName: string, value: string | null, priority?: string | null): void; [index: number]: string; } @@ -2348,7 +2690,6 @@ declare var CSSStyleDeclaration: { }; interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; selectorText: string; readonly style: CSSStyleDeclaration; } @@ -2360,21 +2701,32 @@ declare var CSSStyleRule: { interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; + /** @deprecated */ cssText: string; + /** @deprecated */ readonly id: string; + /** @deprecated */ readonly imports: StyleSheetList; + /** @deprecated */ readonly isAlternate: boolean; + /** @deprecated */ readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; + readonly ownerRule: CSSRule | null; + /** @deprecated */ readonly owningElement: Element; - readonly pages: StyleSheetPageList; + /** @deprecated */ + readonly pages: any; + /** @deprecated */ readonly readOnly: boolean; readonly rules: CSSRuleList; + /** @deprecated */ addImport(bstrURL: string, lIndex?: number): number; + /** @deprecated */ 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; + /** @deprecated */ removeImport(lIndex: number): void; removeRule(lIndex: number): void; } @@ -2392,6 +2744,380 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; +interface Cache { + add(request: Request | string): Promise; + addAll(requests: (Request | string)[]): Promise; + delete(request: Request | string, options?: CacheQueryOptions): Promise; + keys(request?: Request | string, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + matchAll(request?: Request | string, options?: CacheQueryOptions): Promise; + put(request: Request | string, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface Canvas2DContextAttributes { + alpha?: boolean; + storage?: boolean; + willReadFrequently?: boolean; + [attribute: string]: boolean | string | undefined; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +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; + arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: 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 CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends 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; + mozImageSmoothingEnabled: boolean; + msFillRule: CanvasFillRule; + oImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + webkitImageSmoothingEnabled: 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; + drawFocusIfNeeded(path: Path2D, 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; + isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(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 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 ChildNode { + remove(): void; +} + +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 ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(data?: string): 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 ComputedTimingProperties { + activeDuration: number; + currentIteration: number | null; + endTime: number; + localTime: number | null; + progress: number | null; +} + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: 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; + markTimeline(label?: string): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ContentScriptGlobalScope extends EventTarget { + readonly msContentScript: ExtensionScriptApis; + readonly window: Window; +} + +declare var ContentScriptGlobalScope: { + prototype: ContentScriptGlobalScope; + new(): ContentScriptGlobalScope; +}; + +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 CountQueuingStrategy { + highWaterMark: number; + size(): number; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(strategy: QueuingStrategy): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null; +} + +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 CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + whenDefined(name: string): PromiseLike; +} + interface CustomEvent extends Event { readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; @@ -2402,6 +3128,194 @@ declare var CustomEvent: { new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; +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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +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 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 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(...tokens: string[]): void; + contains(token: string): boolean; + item(index: number): string | null; + remove(...tokens: string[]): void; + replace(oldToken: string, newToken: string): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DataCue extends TextTrackCue { data: ArrayBuffer; addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -2448,10 +3362,11 @@ declare var DataTransferItem: { interface DataTransferItemList { readonly length: number; add(data: File): DataTransferItem | null; + add(data: string, type: string): DataTransferItem | null; clear(): void; item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: DataTransferItem; + [name: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -2538,11 +3453,30 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; }; +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforedeactivate": UIEvent; + "activate": Event; + "beforeactivate": Event; + "beforedeactivate": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -2550,7 +3484,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "click": MouseEvent; "contextmenu": PointerEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -2560,7 +3494,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "fullscreenchange": Event; @@ -2580,25 +3514,25 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "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; + "MSContentZoom": Event; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSManipulationStateChanged": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "mssitemodejumplistitemremoved": Event; + "msthumbnailclick": Event; "pause": Event; "play": Event; "playing": Event; @@ -2629,7 +3563,15 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "webkitfullscreenerror": Event; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { +interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent { + /** + * 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; /** * Gets the object that has the focus when the parent document has focus. */ @@ -2645,11 +3587,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * 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; + readonly anchors: HTMLCollectionOf; /** * Retrieves a collection of all applet objects in the document. */ - applets: HTMLCollectionOf; + readonly applets: HTMLCollectionOf; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ @@ -2685,7 +3627,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Gets a reference to the root node of the document. */ - documentElement: HTMLElement; + readonly documentElement: HTMLElement; /** * Sets or gets the security domain of the document. */ @@ -2693,7 +3635,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all embed objects in the document. */ - embeds: HTMLCollectionOf; + readonly embeds: HTMLCollectionOf; /** * Sets or gets the foreground (text) color of the document. */ @@ -2701,7 +3643,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of all form objects in the document. */ - forms: HTMLCollectionOf; + readonly forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; @@ -2709,7 +3651,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of img objects in the document. */ - images: HTMLCollectionOf; + readonly images: HTMLCollectionOf; /** * Gets the implementation object of the current document. */ @@ -2729,322 +3671,323 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. */ - links: HTMLCollectionOf; + readonly links: HTMLCollectionOf; /** * Contains information about the current URL. */ - readonly location: Location; - msCapsLockWarningOff: boolean; + location: Location; msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; /** * Fires when the user aborts the download. * @param ev The event. */ - onabort: (this: Document, ev: UIEvent) => any; + onabort: ((this: Document, ev: UIEvent) => any) | null; /** * Fires when the object is set as the active element. * @param ev The event. */ - onactivate: (this: Document, ev: UIEvent) => any; + onactivate: ((this: Document, ev: Event) => any) | null; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ - onbeforeactivate: (this: Document, ev: UIEvent) => any; + onbeforeactivate: ((this: Document, ev: Event) => any) | null; /** * 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; + onbeforedeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ - onblur: (this: Document, ev: FocusEvent) => any; + onblur: ((this: Document, ev: FocusEvent) => any) | null; /** * 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; + oncanplay: ((this: Document, ev: Event) => any) | null; + oncanplaythrough: ((this: Document, ev: Event) => any) | null; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ - onchange: (this: Document, ev: Event) => any; + onchange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ - onclick: (this: Document, ev: MouseEvent) => any; + onclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ - ondblclick: (this: Document, ev: MouseEvent) => any; + ondblclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + ondeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ - ondrag: (this: Document, ev: DragEvent) => any; + ondrag: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragend: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragenter: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragleave: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragover: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragstart: ((this: Document, ev: DragEvent) => any) | null; + ondrop: ((this: Document, ev: DragEvent) => any) | null; /** * Occurs when the duration attribute is updated. * @param ev The event. */ - ondurationchange: (this: Document, ev: Event) => any; + ondurationchange: ((this: Document, ev: Event) => any) | null; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ - onemptied: (this: Document, ev: Event) => any; + onemptied: ((this: Document, ev: Event) => any) | null; /** * Occurs when the end of playback is reached. * @param ev The event */ - onended: (this: Document, ev: MediaStreamErrorEvent) => any; + onended: ((this: Document, ev: Event) => any) | null; /** * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (this: Document, ev: ErrorEvent) => any; + onerror: ((this: Document, ev: ErrorEvent) => any) | null; /** * 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; + onfocus: ((this: Document, ev: FocusEvent) => any) | null; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + oninput: ((this: Document, ev: Event) => any) | null; + oninvalid: ((this: Document, ev: Event) => any) | null; /** * Fires when the user presses a key. * @param ev The keyboard event */ - onkeydown: (this: Document, ev: KeyboardEvent) => any; + onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ - onkeypress: (this: Document, ev: KeyboardEvent) => any; + onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user releases a key. * @param ev The keyboard event */ - onkeyup: (this: Document, ev: KeyboardEvent) => any; + onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires immediately after the browser loads the object. * @param ev The event. */ - onload: (this: Document, ev: Event) => any; + onload: ((this: Document, ev: Event) => any) | null; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ - onloadeddata: (this: Document, ev: Event) => any; + onloadeddata: ((this: Document, ev: Event) => any) | null; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ - onloadedmetadata: (this: Document, ev: Event) => any; + onloadedmetadata: ((this: Document, ev: Event) => any) | null; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ - onloadstart: (this: Document, ev: Event) => any; + onloadstart: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ - onmousedown: (this: Document, ev: MouseEvent) => any; + onmousedown: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ - onmousemove: (this: Document, ev: MouseEvent) => any; + onmousemove: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseout: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ - onmouseover: (this: Document, ev: MouseEvent) => any; + onmouseover: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseup: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmousewheel: ((this: Document, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: Document, ev: Event) => any) | null; + onmsgesturechange: ((this: Document, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null; + onmsgestureend: ((this: Document, ev: Event) => any) | null; + onmsgesturehold: ((this: Document, ev: Event) => any) | null; + onmsgesturestart: ((this: Document, ev: Event) => any) | null; + onmsgesturetap: ((this: Document, ev: Event) => any) | null; + onmsinertiastart: ((this: Document, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null; + onmspointercancel: ((this: Document, ev: Event) => any) | null; + onmspointerdown: ((this: Document, ev: Event) => any) | null; + onmspointerenter: ((this: Document, ev: Event) => any) | null; + onmspointerleave: ((this: Document, ev: Event) => any) | null; + onmspointermove: ((this: Document, ev: Event) => any) | null; + onmspointerout: ((this: Document, ev: Event) => any) | null; + onmspointerover: ((this: Document, ev: Event) => any) | null; + onmspointerup: ((this: Document, ev: Event) => any) | null; /** * 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; + onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null; /** * 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; + onmsthumbnailclick: ((this: Document, ev: Event) => any) | null; /** * Occurs when playback is paused. * @param ev The event. */ - onpause: (this: Document, ev: Event) => any; + onpause: ((this: Document, ev: Event) => any) | null; /** * Occurs when the play method is requested. * @param ev The event. */ - onplay: (this: Document, ev: Event) => any; + onplay: ((this: Document, ev: Event) => any) | null; /** * 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; + onplaying: ((this: Document, ev: Event) => any) | null; + onpointerlockchange: ((this: Document, ev: Event) => any) | null; + onpointerlockerror: ((this: Document, ev: Event) => any) | null; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ - onprogress: (this: Document, ev: ProgressEvent) => any; + onprogress: ((this: Document, ev: ProgressEvent) => any) | null; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ - onratechange: (this: Document, ev: Event) => any; + onratechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the state of the object has changed. * @param ev The event */ - onreadystatechange: (this: Document, ev: Event) => any; + onreadystatechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user resets a form. * @param ev The event. */ - onreset: (this: Document, ev: Event) => any; + onreset: ((this: Document, ev: Event) => any) | null; /** * 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; + onscroll: ((this: Document, ev: UIEvent) => any) | null; /** * Occurs when the seek operation ends. * @param ev The event. */ - onseeked: (this: Document, ev: Event) => any; + onseeked: ((this: Document, ev: Event) => any) | null; /** * Occurs when the current playback position is moved. * @param ev The event. */ - onseeking: (this: Document, ev: Event) => any; + onseeking: ((this: Document, ev: Event) => any) | null; /** * Fires when the current selection changes. * @param ev The event. */ - onselect: (this: Document, ev: UIEvent) => any; + onselect: ((this: Document, ev: UIEvent) => any) | null; /** * 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; + onselectionchange: ((this: Document, ev: Event) => any) | null; + onselectstart: ((this: Document, ev: Event) => any) | null; /** * Occurs when the download has stopped. * @param ev The event. */ - onstalled: (this: Document, ev: Event) => any; + onstalled: ((this: Document, ev: Event) => any) | null; /** * 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; + onstop: ((this: Document, ev: Event) => any) | null; + onsubmit: ((this: Document, ev: Event) => any) | null; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ - onsuspend: (this: Document, ev: Event) => any; + onsuspend: ((this: Document, ev: Event) => any) | null; /** * 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; + ontimeupdate: ((this: Document, ev: Event) => any) | null; + ontouchcancel: ((this: Document, ev: TouchEvent) => any) | null; + ontouchend: ((this: Document, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Document, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Document, ev: TouchEvent) => any) | null; + onvisibilitychange: (this: Document, ev: Event) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ - onvolumechange: (this: Document, ev: Event) => any; + onvolumechange: ((this: Document, ev: Event) => any) | null; /** * 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; + onwaiting: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null; + readonly plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** * Retrieves a value that indicates the current state of the object. @@ -3061,7 +4004,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all script objects in the document. */ - scripts: HTMLCollectionOf; + readonly 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. @@ -3071,14 +4014,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * 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. @@ -3094,7 +4029,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string | null; - onvisibilitychange: (this: Document, ev: Event) => any; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; @@ -3190,6 +4124,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver: Node): XPathNSResolver; /** * 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. @@ -3198,7 +4133,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @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. @@ -3225,6 +4159,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; + elementsFromPoint(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. @@ -3243,6 +4178,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Causes the element to receive the focus and executes the code specified by the onfocus event. */ + /** @deprecated */ focus(): void; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. @@ -3315,10 +4251,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ queryCommandValue(commandId: string): string; releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** @@ -3342,7 +4274,79 @@ declare var Document: { new(): Document; }; -interface DocumentFragment extends Node, NodeSelector, ParentNode { +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + 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: "MSDCCEvent"): MSDCCEvent; + createEvent(eventInterface: "MSDSHEvent"): MSDSHEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + 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: "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: "PromiseRejectionEvent"): PromiseRejectionEvent; + 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: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + 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: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DocumentFragment extends Node, ParentNode { getElementById(elementId: string): HTMLElement | null; } @@ -3351,6 +4355,14 @@ declare var DocumentFragment: { new(): DocumentFragment; }; +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly styleSheets: StyleSheetList; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + getSelection(): Selection | null; +} + interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; readonly internalSubset: string | null; @@ -3365,149 +4377,6 @@ declare var 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; @@ -3533,209 +4402,23 @@ declare var 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 EXT_blend_minmax { + readonly MAX_EXT: number; + readonly MIN_EXT: number; } -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 | null; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB_EXT: number; +} + +interface EXT_shader_texture_lod { +} interface EXT_texture_filter_anisotropic { readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; @@ -3749,14 +4432,262 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; }; +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": Event; + "command": Event; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSGotPointerCapture": Event; + "MSInertiaStart": Event; + "MSLostPointerCapture": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode { + readonly assignedSlot: HTMLSlotElement | null; + readonly attributes: NamedNodeMap; + 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) | null; + oncommand: ((this: Element, ev: Event) => any) | null; + ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onmsgesturechange: ((this: Element, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null; + onmsgestureend: ((this: Element, ev: Event) => any) | null; + onmsgesturehold: ((this: Element, ev: Event) => any) | null; + onmsgesturestart: ((this: Element, ev: Event) => any) | null; + onmsgesturetap: ((this: Element, ev: Event) => any) | null; + onmsgotpointercapture: ((this: Element, ev: Event) => any) | null; + onmsinertiastart: ((this: Element, ev: Event) => any) | null; + onmslostpointercapture: ((this: Element, ev: Event) => any) | null; + onmspointercancel: ((this: Element, ev: Event) => any) | null; + onmspointerdown: ((this: Element, ev: Event) => any) | null; + onmspointerenter: ((this: Element, ev: Event) => any) | null; + onmspointerleave: ((this: Element, ev: Event) => any) | null; + onmspointermove: ((this: Element, ev: Event) => any) | null; + onmspointerout: ((this: Element, ev: Event) => any) | null; + onmspointerover: ((this: Element, ev: Event) => any) | null; + onmspointerup: ((this: Element, ev: Event) => any) | null; + ontouchcancel: ((this: Element, ev: TouchEvent) => any) | null; + ontouchend: ((this: Element, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Element, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Element, ev: TouchEvent) => any) | null; + onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; + outerHTML: string; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly shadowRoot: ShadowRoot | null; + slot: string; + readonly tagName: string; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + getAttribute(qualifiedName: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + getElementsByClassName(classNames: string): NodeListOf; + 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; + hasAttributes(): boolean; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + matches(selectors: string): boolean; + msGetRegionContent(): any; + 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; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + setAttribute(qualifiedName: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): 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: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + readonly style: CSSStyleDeclaration; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ElementDefinitionOptions { + extends: string; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly nextElementSibling: Element | null; + readonly previousElementSibling: Element | null; +} + +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(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly scoped: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget | null; + readonly timeStamp: number; + readonly type: string; + deepPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(typeArg: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; - fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; genericSynchronousFunction(functionId: number, parameters?: string): string; + genericWebRuntimeCallout(to: any, from: any, payload: string): void; getExtensionId(): string; - registerGenericFunctionCallbackHandler(callbackHandler: any): void; - registerGenericPersistentCallbackHandler(callbackHandler: any): void; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericPersistentCallbackHandler(callbackHandler: Function): void; + registerWebRuntimeCallbackHandler(handler: Function): any; } declare var ExtensionScriptApis: { @@ -3773,10 +4704,11 @@ declare var External: { }; interface File extends Blob { + readonly lastModified: number; + /** @deprecated */ readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; - readonly lastModified: number; } declare var File: { @@ -3786,7 +4718,7 @@ declare var File: { interface FileList { readonly length: number; - item(index: number): File; + item(index: number): File | null; [index: number]: File; } @@ -3795,21 +4727,49 @@ declare var FileList: { new(): FileList; }; -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; 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; + readAsText(blob: Blob, label?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[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: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface FocusEvent extends UIEvent { @@ -3847,7 +4807,8 @@ interface FormData { declare var FormData: { prototype: FormData; - new (form?: HTMLFormElement): FormData; + new(): FormData; + new(form: HTMLFormElement): FormData; }; interface GainNode extends AudioNode { @@ -3863,9 +4824,13 @@ interface Gamepad { readonly axes: number[]; readonly buttons: GamepadButton[]; readonly connected: boolean; + readonly displayId: number; + readonly hand: GamepadHand; + readonly hapticActuators: GamepadHapticActuator[]; readonly id: string; readonly index: number; - readonly mapping: string; + readonly mapping: GamepadMappingType; + readonly pose: GamepadPose | null; readonly timestamp: number; } @@ -3876,6 +4841,7 @@ declare var Gamepad: { interface GamepadButton { readonly pressed: boolean; + readonly touched: boolean; readonly value: number; } @@ -3893,6 +4859,32 @@ declare var GamepadEvent: { new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; }; +interface GamepadHapticActuator { + readonly type: GamepadHapticActuatorType; + pulse(value: number, duration: number): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GamepadPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; +} + +declare var GamepadPose: { + prototype: GamepadPose; + new(): GamepadPose; +}; + interface Geolocation { clearWatch(watchId: number): void; getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; @@ -3904,45 +4896,41 @@ declare var Geolocation: { new(): Geolocation; }; -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; +interface GetSVGDocument { + getSVGDocument(): Document; } -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; +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; } -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; +interface GlobalEventHandlers { + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + 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; } -declare var History: { - prototype: History; - new(): History; -}; +interface GlobalFetch { + fetch(input?: Request | string, init?: RequestInit): Promise; +} interface HTMLAllCollection { readonly length: number; @@ -3956,55 +4944,30 @@ declare var HTMLAllCollection: { new(): HTMLAllCollection; }; -interface HTMLAnchorElement extends HTMLElement { +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + Methods: string; /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Sets or retrieves the coordinates of the object. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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. @@ -4013,14 +4976,12 @@ interface HTMLAnchorElement extends HTMLElement { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ 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. */ + /** @deprecated */ shape: string; /** * Sets or retrieves the window or frame at which to target content. @@ -4032,10 +4993,6 @@ interface HTMLAnchorElement extends HTMLElement { 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; @@ -4048,70 +5005,44 @@ declare var HTMLAnchorElement: { }; interface HTMLAppletElement extends HTMLElement { + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ 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. */ + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; /** * Sets or retrieves the shape of the object. */ + /** @deprecated */ 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; + /** @deprecated */ + object: string; + /** @deprecated */ vspace: number; - width: number; + /** @deprecated */ + width: string; 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; @@ -4123,7 +5054,7 @@ declare var HTMLAppletElement: { new(): HTMLAppletElement; }; -interface HTMLAreaElement extends HTMLElement { +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { /** * Sets or retrieves a text alternative to the graphic. */ @@ -4133,43 +5064,12 @@ interface HTMLAreaElement extends HTMLElement { */ 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. */ + /** @deprecated */ 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. */ @@ -4178,10 +5078,6 @@ interface HTMLAreaElement extends HTMLElement { * 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; @@ -4213,6 +5109,23 @@ declare var HTMLAudioElement: { new(): HTMLAudioElement; }; +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. + */ + /** @deprecated */ + 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 HTMLBaseElement extends HTMLElement { /** * Gets or sets the baseline URL on which relative links are based. @@ -4237,10 +5150,12 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ face: string; /** * Sets or retrieves the font size of the object. */ + /** @deprecated */ 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; @@ -4253,51 +5168,34 @@ declare var HTMLBaseFontElement: { new(): HTMLBaseFontElement; }; -interface HTMLBodyElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { + /** @deprecated */ + aLink: string; + /** @deprecated */ background: string; - bgColor: any; + /** @deprecated */ + bgColor: string; bgProperties: string; - link: any; + /** @deprecated */ + link: string; + /** @deprecated */ 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; + onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; + onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null; + /** @deprecated */ + text: string; + /** @deprecated */ + vLink: string; 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; @@ -4309,22 +5207,6 @@ declare var 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. @@ -4350,7 +5232,7 @@ interface HTMLButtonElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -4420,12 +5302,12 @@ interface HTMLCanvasElement extends HTMLElement { * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ msToBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; /** * 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; @@ -4461,6 +5343,26 @@ declare var HTMLCollection: { new(): HTMLCollection; }; +interface HTMLCollectionOf extends HTMLCollectionBase { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface HTMLDListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLDataElement extends HTMLElement { value: string; addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4475,7 +5377,7 @@ declare var HTMLDataElement: { }; interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; + readonly 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; @@ -4487,6 +5389,36 @@ declare var HTMLDataListElement: { new(): HTMLDataListElement; }; +interface HTMLDetailsElement extends HTMLElement { + open: boolean; + addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; + addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + interface HTMLDirectoryElement extends HTMLElement { compact: boolean; addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4504,6 +5436,7 @@ interface HTMLDivElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. @@ -4520,19 +5453,6 @@ declare var 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; @@ -4547,12 +5467,12 @@ declare var HTMLDocument: { interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforecopy": ClipboardEvent; - "beforecut": ClipboardEvent; - "beforedeactivate": UIEvent; - "beforepaste": ClipboardEvent; + "activate": Event; + "beforeactivate": Event; + "beforecopy": Event; + "beforecut": Event; + "beforedeactivate": Event; + "beforepaste": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -4563,7 +5483,7 @@ interface HTMLElementEventMap extends ElementEventMap { "cuechange": Event; "cut": ClipboardEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -4573,7 +5493,7 @@ interface HTMLElementEventMap extends ElementEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "input": Event; @@ -4593,8 +5513,8 @@ interface HTMLElementEventMap extends ElementEventMap { "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": WheelEvent; - "MSContentZoom": UIEvent; - "MSManipulationStateChanged": MSManipulationEvent; + "MSContentZoom": Event; + "MSManipulationStateChanged": Event; "paste": ClipboardEvent; "pause": Event; "play": Event; @@ -4615,9 +5535,8 @@ interface HTMLElementEventMap extends ElementEventMap { "waiting": Event; } -interface HTMLElement extends Element { +interface HTMLElement extends Element, ElementCSSInlineStyle { accessKey: string; - readonly children: HTMLCollection; contentEditable: string; readonly dataset: DOMStringMap; dir: string; @@ -4632,84 +5551,83 @@ interface HTMLElement extends Element { 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; + onabort: ((this: HTMLElement, ev: UIEvent) => any) | null; + onactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecut: ((this: HTMLElement, ev: Event) => any) | null; + onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null; + onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oncanplay: ((this: HTMLElement, ev: Event) => any) | null; + oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null; + onchange: ((this: HTMLElement, ev: Event) => any) | null; + onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null; + oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + oncuechange: ((this: HTMLElement, ev: Event) => any) | null; + oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + ondeactivate: ((this: HTMLElement, ev: Event) => any) | null; + ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondurationchange: ((this: HTMLElement, ev: Event) => any) | null; + onemptied: ((this: HTMLElement, ev: Event) => any) | null; + onended: ((this: HTMLElement, ev: Event) => any) | null; + onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null; + onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oninput: ((this: HTMLElement, ev: Event) => any) | null; + oninvalid: ((this: HTMLElement, ev: Event) => any) | null; + onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onload: ((this: HTMLElement, ev: Event) => any) | null; + onloadeddata: ((this: HTMLElement, ev: Event) => any) | null; + onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null; + onloadstart: ((this: HTMLElement, ev: Event) => any) | null; + onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null; + onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + onpause: ((this: HTMLElement, ev: Event) => any) | null; + onplay: ((this: HTMLElement, ev: Event) => any) | null; + onplaying: ((this: HTMLElement, ev: Event) => any) | null; + onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null; + onratechange: ((this: HTMLElement, ev: Event) => any) | null; + onreset: ((this: HTMLElement, ev: Event) => any) | null; + onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null; + onseeked: ((this: HTMLElement, ev: Event) => any) | null; + onseeking: ((this: HTMLElement, ev: Event) => any) | null; + onselect: ((this: HTMLElement, ev: UIEvent) => any) | null; + onselectstart: ((this: HTMLElement, ev: Event) => any) | null; + onstalled: ((this: HTMLElement, ev: Event) => any) | null; + onsubmit: ((this: HTMLElement, ev: Event) => any) | null; + onsuspend: ((this: HTMLElement, ev: Event) => any) | null; + ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null; + onvolumechange: ((this: HTMLElement, ev: Event) => any) | null; + onwaiting: ((this: HTMLElement, ev: Event) => any) | null; outerText: string; spellcheck: boolean; - readonly style: CSSStyleDeclaration; tabIndex: number; title: string; + animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; blur(): void; click(): void; dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; 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; @@ -4746,6 +5664,7 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * Retrieves the palette used for the embedded document. @@ -4826,6 +5745,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ 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; @@ -4906,6 +5826,7 @@ interface HTMLFormElement extends HTMLElement { * Retrieves a form object or an object from an elements collection. */ namedItem(name: string): any; + reportValidity(): boolean; /** * Fires when the user resets a form. */ @@ -4914,8 +5835,6 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ 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; @@ -4944,14 +5863,17 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + /** @deprecated */ + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + /** @deprecated */ + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. @@ -4964,30 +5886,37 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a URI to a long description of the object. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ marginWidth: string; /** * Sets or retrieves the frame name. */ + /** @deprecated */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ + /** @deprecated */ noResize: boolean; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ + /** @deprecated */ src: string; /** * Sets or retrieves the width of the object. @@ -5004,64 +5933,29 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; }; -interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { /** * Sets or retrieves the frame widths of the object. */ + /** @deprecated */ 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; + onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null; + onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null; /** * Sets or retrieves the frame heights of the object. */ + /** @deprecated */ 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; @@ -5074,7 +5968,35 @@ declare var HTMLFrameSetElement: { new(): HTMLFrameSetElement; }; +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + /** @deprecated */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + 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 HTMLHeadElement extends HTMLElement { + /** @deprecated */ 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; @@ -5091,6 +6013,7 @@ interface HTMLHeadingElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ 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; @@ -5103,34 +6026,11 @@ declare var 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. */ + /** @deprecated */ 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; @@ -5143,6 +6043,19 @@ declare var HTMLHtmlElement: { new(): HTMLHtmlElement; }; +interface HTMLHyperlinkElementUtils { + hash: string; + host: string; + hostname: string; + href: string; + origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + toString(): string; +} + interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; } @@ -5151,78 +6064,64 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ 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; + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ 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. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ 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; + readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** - * Sets or retrieves the vertical margin for the object. + * Sets or retrives the content of the page that is to contain. */ - vspace: number; + srcdoc: string; /** * 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; @@ -5238,6 +6137,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5246,6 +6146,7 @@ interface HTMLImageElement extends HTMLElement { /** * Specifies the properties of a border drawn around an object. */ + /** @deprecated */ border: string; /** * Retrieves whether the object is fully loaded. @@ -5253,6 +6154,7 @@ interface HTMLImageElement extends HTMLElement { readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; /** * Sets or retrieves the height of the object. */ @@ -5260,6 +6162,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ hspace: number; /** * Sets or retrieves whether the image is a server-side image map. @@ -5269,6 +6172,7 @@ interface HTMLImageElement extends HTMLElement { * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. */ longDesc: string; + /** @deprecated */ lowsrc: string; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5286,6 +6190,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * The original height of the image resource before sizing. @@ -5308,6 +6213,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the vertical margin for the object. */ + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -5335,6 +6241,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5348,18 +6255,10 @@ interface HTMLInputElement 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 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. */ @@ -5392,7 +6291,7 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -5400,16 +6299,12 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + height: number; indeterminate: boolean; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ - readonly list: HTMLElement; + readonly list: HTMLElement | null; /** * 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. */ @@ -5422,6 +6317,7 @@ interface HTMLInputElement extends HTMLElement { * 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; + minLength: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ @@ -5443,21 +6339,20 @@ interface HTMLInputElement extends HTMLElement { * When present, marks an element that can't be submitted without a value. */ required: boolean; - selectionDirection: string; + selectionDirection: string | null; /** * Gets or sets the end position or offset of a text selection. */ - selectionEnd: number; + selectionEnd: number | null; /** * Gets or sets the starting position or offset of a text selection. */ - selectionStart: number; + selectionStart: number | null; 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. */ @@ -5469,6 +6364,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ + /** @deprecated */ 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. @@ -5482,25 +6378,20 @@ interface HTMLInputElement extends HTMLElement { * Returns the value of the data at the cursor's current position. */ value: string; - valueAsDate: Date; + valueAsDate: any; /** * 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; + width: number; /** * 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. */ @@ -5542,48 +6433,8 @@ declare var 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 { + /** @deprecated */ type: string; /** * Sets or retrieves the value of a list item. @@ -5600,11 +6451,56 @@ declare var HTMLLIElement: { new(): HTMLLIElement; }; +interface HTMLLabelElement extends HTMLElement { + readonly control: HTMLInputElement | null; + /** + * 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; + 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. + */ + /** @deprecated */ + 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 HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; + crossOrigin: string | null; + /** @deprecated */ disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. @@ -5614,6 +6510,8 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { * Sets or retrieves the language code of the object. */ hreflang: string; + import?: Document; + integrity: string; /** * Sets or retrieves the media type. */ @@ -5625,17 +6523,17 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ rev: string; /** * Sets or retrieves the window or frame at which to target content. */ + /** @deprecated */ 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; @@ -5647,6 +6545,18 @@ declare var HTMLLinkElement: { new(): HTMLLinkElement; }; +interface HTMLMainElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. @@ -5674,21 +6584,37 @@ interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { } interface HTMLMarqueeElement extends HTMLElement { + /** @deprecated */ behavior: string; - bgColor: any; + /** @deprecated */ + bgColor: string; + /** @deprecated */ direction: string; + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; + /** @deprecated */ loop: number; - onbounce: (this: HTMLMarqueeElement, ev: Event) => any; - onfinish: (this: HTMLMarqueeElement, ev: Event) => any; - onstart: (this: HTMLMarqueeElement, ev: Event) => any; + /** @deprecated */ + onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ scrollAmount: number; + /** @deprecated */ scrollDelay: number; + /** @deprecated */ trueSpeed: boolean; + /** @deprecated */ vspace: number; + /** @deprecated */ width: string; + /** @deprecated */ start(): void; + /** @deprecated */ 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; @@ -5703,7 +6629,7 @@ declare var HTMLMarqueeElement: { interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; - "msneedkey": MSMediaKeyNeededEvent; + "msneedkey": Event; } interface HTMLMediaElement extends HTMLElement { @@ -5748,7 +6674,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Returns an object representing the current error state of the audio or video element. */ - readonly error: MediaError; + readonly error: MediaError | null; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ @@ -5766,6 +6692,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ + /** @deprecated */ readonly msKeys: MSMediaKeys; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5795,8 +6722,9 @@ interface HTMLMediaElement extends HTMLElement { * Gets the current network activity for the element. */ readonly networkState: number; - onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null; + /** @deprecated */ + onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null; /** * Gets a flag that specifies whether playback is paused. */ @@ -5813,7 +6741,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: number; + readonly readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -5826,18 +6754,18 @@ interface HTMLMediaElement extends HTMLElement { * The address or URL of the a media resource that is to be considered. */ src: string; - srcObject: MediaStream | null; + srcObject: MediaStream | MediaSource | Blob | 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; + addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack; /** * Returns a string that specifies whether the client can play a given media resource type. */ - canPlayType(type: string): string; + canPlayType(type: string): CanPlayTypeResult; /** * Resets the audio or video object and loads a new media resource. */ @@ -5851,6 +6779,7 @@ interface HTMLMediaElement extends HTMLElement { * Inserts the specified audio effect into media pipeline. */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + /** @deprecated */ msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Specifies the media protection manager for a given media pipeline. @@ -5895,6 +6824,7 @@ declare var HTMLMediaElement: { }; interface HTMLMenuElement extends HTMLElement { + /** @deprecated */ compact: boolean; type: string; addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -5912,6 +6842,7 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. @@ -5928,10 +6859,12 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ + /** @deprecated */ scheme: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ + /** @deprecated */ 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; @@ -5982,41 +6915,63 @@ declare var HTMLModElement: { new(): HTMLModElement; }; +interface HTMLOListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLObjectElement extends HTMLElement, GetSVGDocument { - align: 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; + /** @deprecated */ + align: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ border: string; /** * Sets or retrieves the URL of the file containing the compiled Java class. */ + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ + /** @deprecated */ codeType: string; /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + readonly contentDocument: Document | null; /** * Sets or retrieves the URL that references the data of the object. */ data: string; + /** @deprecated */ declare: boolean; /** * Retrieves a reference to the form that the object is embedded in. @@ -6026,6 +6981,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the height of the object. */ height: string; + /** @deprecated */ hspace: number; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -6051,11 +7007,13 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a message to be displayed while an object is loading. */ + /** @deprecated */ standby: string; /** * Sets or retrieves the MIME type of the object. */ type: string; + typemustmatch: boolean; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ @@ -6068,6 +7026,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -6077,7 +7036,6 @@ 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. */ @@ -6098,54 +7056,16 @@ declare var 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; @@ -6201,7 +7121,7 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; remove(index: number): void; } @@ -6213,7 +7133,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; readonly form: HTMLFormElement | null; - readonly htmlFor: DOMSettableTokenList; + readonly htmlFor: DOMTokenList; name: string; readonly type: string; readonly validationMessage: string; @@ -6238,6 +7158,7 @@ interface HTMLParagraphElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -6259,6 +7180,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the content type of the resource designated by the value attribute. */ + /** @deprecated */ type: string; /** * Sets or retrieves the value of an input parameter for an element. @@ -6267,6 +7189,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the data type of the value attribute. */ + /** @deprecated */ 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; @@ -6295,6 +7218,7 @@ interface HTMLPreElement extends HTMLElement { /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ + /** @deprecated */ 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; @@ -6365,11 +7289,15 @@ interface HTMLScriptElement extends HTMLElement { /** * Sets or retrieves the event for which the script is written. */ + /** @deprecated */ event: string; /** * Sets or retrieves the object that is bound to the event script. */ + /** @deprecated */ htmlFor: string; + integrity: string; + noModule: boolean; /** * Retrieves the URL to an external file that contains the source code or data. */ @@ -6382,7 +7310,6 @@ interface HTMLScriptElement extends HTMLElement { * 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; @@ -6425,7 +7352,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the index of the selected option in a select object. */ selectedIndex: number; - selectedOptions: HTMLCollectionOf; + readonly selectedOptions: HTMLCollectionOf; /** * Sets or retrieves the number of rows in the list box. */ @@ -6455,7 +7382,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6465,7 +7392,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + item(name?: any, index?: any): Element | null; /** * 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. @@ -6493,11 +7420,21 @@ declare var HTMLSelectElement: { new(): HTMLSelectElement; }; +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; + addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; + /** @deprecated */ msKeySystem: string; sizes: string; /** @@ -6533,6 +7470,7 @@ declare var HTMLSpanElement: { }; interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** @deprecated */ disabled: boolean; /** * Sets or retrieves the media type. @@ -6553,15 +7491,24 @@ declare var HTMLStyleElement: { new(): HTMLStyleElement; }; +interface HTMLSummaryElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. */ + /** @deprecated */ 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; @@ -6573,7 +7520,7 @@ declare var HTMLTableCaptionElement: { new(): HTMLTableCaptionElement; }; -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableCellElement extends HTMLElement { /** * Sets or retrieves abbreviated text for the object. */ @@ -6581,16 +7528,23 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. */ + /** @deprecated */ axis: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves the position of the object in the cells collection of a row. */ readonly cellIndex: number; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number columns in the table that the object should span. */ @@ -6602,10 +7556,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves the height of the object. */ - height: any; + /** @deprecated */ + height: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ + /** @deprecated */ noWrap: boolean; /** * Sets or retrieves how many rows in a table the cell should span. @@ -6615,9 +7571,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ 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; @@ -6630,19 +7589,27 @@ declare var HTMLTableCellElement: { new(): HTMLTableCellElement; }; -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableColElement extends HTMLElement { /** * Sets or retrieves the alignment of the object relative to the display or table. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of columns in the group. */ span: number; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ - width: any; + /** @deprecated */ + width: string; 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; @@ -6670,67 +7637,64 @@ interface HTMLTableElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; /** * Retrieves the caption object of a table. */ - caption: HTMLTableCaptionElement; + caption: HTMLTableCaptionElement | null; /** * Sets or retrieves the amount of space between the border of the cell and the content of the cell. */ + /** @deprecated */ cellPadding: string; /** * Sets or retrieves the amount of space between cells in a table. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + readonly rows: HTMLCollectionOf; /** * Sets or retrieves which dividing lines (inner borders) are displayed. */ + /** @deprecated */ rules: string; /** * Sets or retrieves a description and/or structure of the object. */ + /** @deprecated */ summary: string; /** * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. */ - tBodies: HTMLCollectionOf; + readonly tBodies: HTMLCollectionOf; /** * Retrieves the tFoot object of the table. */ - tFoot: HTMLTableSectionElement; + tFoot: HTMLTableSectionElement | null; /** * Retrieves the tHead object of the table. */ - tHead: HTMLTableSectionElement; + tHead: HTMLTableSectionElement | null; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ width: string; /** * Creates an empty caption element in the table. @@ -6782,9 +7746,6 @@ declare var 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; @@ -6797,20 +7758,22 @@ declare var HTMLTableHeaderCellElement: { new(): HTMLTableHeaderCellElement; }; -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableRowElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves a collection of all cells in the table row. */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; + readonly cells: HTMLCollectionOf; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Retrieves the position of the object in the rows collection for the table. */ @@ -6819,6 +7782,8 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Retrieves the position of the object in the collection. */ readonly sectionRowIndex: number; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6840,15 +7805,22 @@ declare var HTMLTableRowElement: { new(): HTMLTableRowElement; }; -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableSectionElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of horizontal rows contained in the object. */ - rows: HTMLCollectionOf; + readonly rows: HTMLCollectionOf; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6905,6 +7877,7 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; + minLength: number; /** * Sets or retrieves the name of the object. */ @@ -6933,10 +7906,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -6961,7 +7930,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -7050,7 +8018,9 @@ declare var HTMLTrackElement: { }; interface HTMLUListElement extends HTMLElement { + /** @deprecated */ compact: boolean; + /** @deprecated */ 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; @@ -7092,9 +8062,9 @@ interface HTMLVideoElement extends HTMLMediaElement { msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; - onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; /** * 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. */ @@ -7117,10 +8087,10 @@ interface HTMLVideoElement extends HTMLMediaElement { 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; + 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; @@ -7132,13 +8102,71 @@ declare var HTMLVideoElement: { new(): HTMLVideoElement; }; +interface HTMLegendElement { + readonly form: HTMLFormElement | null; +} + +declare var HTMLegendElement: { + prototype: HTMLegendElement; + new(): HTMLegendElement; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string; + readonly oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: Function, thisArg?: any): 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; + scrollRestoration: ScrollRestoration; + readonly state: any; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): 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 HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + interface IDBCursor { readonly direction: IDBCursorDirection; - key: IDBKeyRange | IDBValidKey; + readonly key: IDBKeyRange | number | string | Date | IDBArrayKey; readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; + readonly source: IDBObjectStore | IDBIndex; advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; + continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void; delete(): IDBRequest; update(value: any): IDBRequest; readonly NEXT: string; @@ -7173,16 +8201,14 @@ interface IDBDatabaseEventMap { 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; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: Event) => any) | null; + readonly version: number; 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; @@ -7194,6 +8220,10 @@ declare var IDBDatabase: { new(): IDBDatabase; }; +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + interface IDBFactory { cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; @@ -7206,16 +8236,16 @@ declare var IDBFactory: { }; interface IDBIndex { - keyPath: string | string[]; + readonly keyPath: string | string[]; + multiEntry: boolean; 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; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -7240,21 +8270,21 @@ declare var IDBKeyRange: { }; interface IDBObjectStore { + autoIncrement: boolean; readonly indexNames: DOMStringList; - keyPath: string | string[]; + readonly keyPath: string | string[] | null; readonly name: string; readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): 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; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; } declare var IDBObjectStore: { @@ -7268,8 +8298,8 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { } interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: IDBOpenDBRequest, ev: Event) => any; - onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; 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; @@ -7288,11 +8318,11 @@ interface IDBRequestEventMap { interface IDBRequest extends EventTarget { readonly error: DOMException; - onerror: (this: IDBRequest, ev: Event) => any; - onsuccess: (this: IDBRequest, ev: Event) => any; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; readonly readyState: IDBRequestReadyState; readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; + readonly 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; @@ -7315,9 +8345,9 @@ 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; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -7356,8 +8386,23 @@ declare var IIRFilterNode: { new(): IIRFilterNode; }; +interface ImageBitmap { + readonly height: number; + readonly width: number; + close(): void; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + interface ImageData { - data: Uint8ClampedArray; + readonly data: Uint8ClampedArray; readonly height: number; readonly width: number; } @@ -7387,10 +8432,10 @@ interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; readonly intersectionRect: ClientRect | DOMRect; + readonly isIntersecting: boolean; readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; - readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -7400,19 +8445,23 @@ declare var IntersectionObserverEntry: { interface KeyboardEvent extends UIEvent { readonly altKey: boolean; - readonly char: string | null; + /** @deprecated */ + char: string; + /** @deprecated */ readonly charCode: number; + readonly code: string; readonly ctrlKey: boolean; readonly key: string; + /** @deprecated */ readonly keyCode: number; - readonly locale: string; readonly location: number; readonly metaKey: boolean; readonly repeat: boolean; readonly shiftKey: boolean; + /** @deprecated */ readonly which: number; - readonly code: string; getModifierState(keyArg: string): boolean; + /** @deprecated */ 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; @@ -7433,6 +8482,10 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_STANDARD: number; }; +interface LinkStyle { + readonly sheet: StyleSheet | null; +} + interface ListeningStateChangedEvent extends Event { readonly label: string; readonly state: ListeningState; @@ -7464,14 +8517,327 @@ declare var Location: { new(): Location; }; -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; } -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; +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 MSDCCEvent extends Event { + readonly maxFr: number; + readonly maxFs: number; +} + +declare var MSDCCEvent: { + prototype: MSDCCEvent; + new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent; +}; + +interface MSDSHEvent extends Event { + readonly sources: number[]; + readonly timestamp: number; +} + +declare var MSDSHEvent: { + prototype: MSDSHEvent; + new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent; +}; + +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 MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +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 MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null; + 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 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 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 MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string | null): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string; +}; + +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 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 MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MSStreamReaderEventMap { + "abort": UIEvent; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSStreamReader extends EventTarget { + readonly error: DOMError; + onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null; + onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null; + onload: ((this: MSStreamReader, ev: Event) => any) | null; + onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: MSStreamReader, ev: Event) => any) | null; + onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; + 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; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface MediaDeviceInfo { @@ -7491,7 +8857,7 @@ interface MediaDevicesEventMap { } interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; + ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; @@ -7554,26 +8920,16 @@ declare var MediaKeyMessageEvent: { new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; }; -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: BufferSource): 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: BufferSource): Promise; + generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: BufferSource): Promise; + update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; } declare var MediaKeySession: { @@ -7583,9 +8939,9 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: BufferSource): MediaKeyStatus; - has(keyId: BufferSource): boolean; + forEach(callback: Function, thisArg?: any): void; + get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus; + has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean; } declare var MediaKeyStatusMap: { @@ -7604,13 +8960,23 @@ declare var MediaKeySystemAccess: { new(): MediaKeySystemAccess; }; +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + interface MediaList { readonly length: number; mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; + appendMedium(medium: string): void; + deleteMedium(medium: string): void; + item(index: number): string | null; + toString(): number; [index: number]: string; } @@ -7657,10 +9023,10 @@ interface MediaStreamEventMap { 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; + onactive: ((this: MediaStream, ev: Event) => any) | null; + onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + oninactive: ((this: MediaStream, ev: Event) => any) | null; + onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; addTrack(track: MediaStreamTrack): void; clone(): MediaStream; getAudioTracks(): MediaStreamTrack[]; @@ -7677,7 +9043,9 @@ interface MediaStream extends EventTarget { declare var MediaStream: { prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; + new(): MediaStream; + new(stream: MediaStream): MediaStream; + new(tracks: MediaStreamTrack[]): MediaStream; }; interface MediaStreamAudioSourceNode extends AudioNode { @@ -7730,10 +9098,10 @@ interface MediaStreamTrack extends EventTarget { 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; + onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readonly: boolean; readonly readyState: MediaStreamTrackState; readonly remote: boolean; @@ -7776,9 +9144,9 @@ declare var 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; + readonly ports: ReadonlyArray; + readonly source: Window | null; + initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void; } declare var MessageEvent: { @@ -7791,7 +9159,7 @@ interface MessagePortEventMap { } interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; @@ -7837,6 +9205,7 @@ interface MouseEvent extends UIEvent { readonly clientX: number; readonly clientY: number; readonly ctrlKey: boolean; + /** @deprecated */ readonly fromElement: Element; readonly layerX: number; readonly layerY: number; @@ -7851,7 +9220,9 @@ interface MouseEvent extends UIEvent { readonly screenX: number; readonly screenY: number; readonly shiftKey: boolean; + /** @deprecated */ readonly toElement: Element; + /** @deprecated */ readonly which: number; readonly x: number; readonly y: number; @@ -7864,456 +9235,6 @@ declare var 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; @@ -8354,7 +9275,7 @@ interface MutationRecord { readonly previousSibling: Node | null; readonly removedNodes: NodeList; readonly target: Node; - readonly type: string; + readonly type: MutationRecordType; } declare var MutationRecord: { @@ -8364,13 +9285,13 @@ declare var 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; + getNamedItem(qualifiedName: string): Attr | null; + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + item(index: number): Attr | null; + removeNamedItem(qualifiedName: string): Attr; + removeNamedItemNS(namespace: string | null, localName: string): Attr; + setNamedItem(attr: Attr): Attr | null; + setNamedItemNS(attr: Attr): Attr | null; [index: number]: Attr; } @@ -8379,39 +9300,13 @@ declare var 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 { +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage { + readonly activeVRDisplays: ReadonlyArray; readonly authentication: WebAuthentication; readonly cookieEnabled: boolean; + readonly doNotTrack: string | null; gamepadInputEmulation: GamepadInputEmulationType; - readonly language: string; + readonly geolocation: Geolocation; readonly maxTouchPoints: number; readonly mimeTypes: MimeTypeArray; readonly msManipulationViewsEnabled: boolean; @@ -8421,10 +9316,8 @@ 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[]; + getGamepads(): (Gamepad | null)[]; + getVRDisplays(): Promise; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; @@ -8436,10 +9329,50 @@ declare var Navigator: { new(): Navigator; }; +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +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 NavigatorLanguage { + readonly language: string; + readonly languages: ReadonlyArray; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getDisplayMedia(constraints: MediaStreamConstraints): Promise; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + interface Node extends EventTarget { - readonly attributes: NamedNodeMap; readonly baseURI: string | null; - readonly childNodes: NodeList; + readonly childNodes: NodeListOf; readonly firstChild: Node | null; readonly lastChild: Node | null; readonly localName: string | null; @@ -8457,7 +9390,6 @@ interface Node extends EventTarget { 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; @@ -8512,7 +9444,7 @@ declare var Node: { }; interface NodeFilter { - acceptNode(n: Node): number; + acceptNode(node: Node): number; } declare var NodeFilter: { @@ -8535,13 +9467,14 @@ declare var NodeFilter: { }; interface NodeIterator { + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; detach(): void; - nextNode(): Node; - previousNode(): Node; + nextNode(): Node | null; + previousNode(): Node | null; } declare var NodeIterator: { @@ -8560,6 +9493,21 @@ declare var NodeList: { new(): NodeList; }; +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +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 NotificationEventMap { "click": Event; "close": Event; @@ -8568,16 +9516,17 @@ interface NotificationEventMap { } interface Notification extends EventTarget { - readonly body: string; + readonly body: string | null; + readonly data: any; 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 icon: string | null; + readonly lang: string | null; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; readonly permission: NotificationPermission; - readonly tag: string; + readonly tag: string | null; readonly title: string; close(): void; addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8644,6 +9593,14 @@ declare var OES_texture_half_float_linear: { new(): OES_texture_half_float_linear; }; +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; +} + interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; } @@ -8659,7 +9616,7 @@ interface OfflineAudioContextEventMap extends AudioContextEventMap { interface OfflineAudioContext extends AudioContextBase { readonly length: number; - oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; + oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null; startRendering(): Promise; suspend(suspendTime: number): Promise; addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8674,13 +9631,13 @@ declare var OfflineAudioContext: { }; interface OscillatorNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface OscillatorNode extends AudioNode { readonly detune: AudioParam; readonly frequency: AudioParam; - onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: OscillatorNode, ev: Event) => any) | null; type: OscillatorType; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; @@ -8731,8 +9688,11 @@ interface PannerNode extends AudioNode { panningModel: PanningModelType; refDistance: number; rolloffFactor: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -8741,12 +9701,28 @@ declare var PannerNode: { new(): PannerNode; }; -interface Path2D extends Object, CanvasPathMethods { +interface ParentNode { + readonly children: HTMLCollection; + 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 ParentNode { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; +} + +interface Path2D extends CanvasPathMethods { } declare var Path2D: { prototype: Path2D; - new(path?: Path2D): Path2D; + new(d?: Path2D | string): Path2D; }; interface PaymentAddress { @@ -8775,12 +9751,14 @@ interface PaymentRequestEventMap { } interface PaymentRequest extends EventTarget { - onshippingaddresschange: (this: PaymentRequest, ev: Event) => any; - onshippingoptionchange: (this: PaymentRequest, ev: Event) => any; + readonly id: string; + onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; + onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; readonly shippingType: PaymentShippingType | null; abort(): Promise; + canMakePayment(): 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; @@ -8790,11 +9768,11 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; - new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; }; interface PaymentRequestUpdateEvent extends Event { - updateWith(d: Promise): void; + updateWith(detailsPromise: Promise): void; } declare var PaymentRequestUpdateEvent: { @@ -8808,6 +9786,7 @@ interface PaymentResponse { readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; + readonly requestId: string; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; @@ -8819,16 +9798,50 @@ declare var PaymentResponse: { new(): PaymentResponse; }; +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 Performance { + /** @deprecated */ readonly navigation: PerformanceNavigation; + readonly timeOrigin: number; + /** @deprecated */ 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; + getEntriesByName(name: string, type?: string): any; + getEntriesByType(type: string): any; + /** @deprecated */ getMarks(markName?: string): any; + /** @deprecated */ getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; @@ -8847,6 +9860,7 @@ interface PerformanceEntry { readonly entryType: string; readonly name: string; readonly startTime: number; + toJSON(): any; } declare var PerformanceEntry: { @@ -8890,28 +9904,41 @@ declare var PerformanceNavigation: { }; interface PerformanceNavigationTiming extends PerformanceEntry { + /** @deprecated */ readonly connectEnd: number; + /** @deprecated */ readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; + /** @deprecated */ readonly domLoading: number; + /** @deprecated */ + readonly domainLookupEnd: number; + /** @deprecated */ + readonly domainLookupStart: number; + /** @deprecated */ readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; + /** @deprecated */ readonly navigationStart: number; readonly redirectCount: number; + /** @deprecated */ readonly redirectEnd: number; + /** @deprecated */ readonly redirectStart: number; + /** @deprecated */ readonly requestStart: number; + /** @deprecated */ readonly responseEnd: number; + /** @deprecated */ readonly responseStart: number; readonly type: NavigationType; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly workerStart: number; } declare var PerformanceNavigationTiming: { @@ -8931,6 +9958,7 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly workerStart: number; } declare var PerformanceResourceTiming: { @@ -8941,13 +9969,13 @@ declare var 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 domainLookupEnd: number; + readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -8958,9 +9986,9 @@ interface PerformanceTiming { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly secureConnectionStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; - readonly secureConnectionStart: number; toJSON(): any; } @@ -8969,35 +9997,6 @@ declare var 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 { } @@ -9079,12 +10078,11 @@ declare var 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; + new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent; }; interface Position { @@ -9132,10 +10130,21 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; + new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent; }; +interface PromiseRejectionEvent extends Event { + readonly promise: PromiseLike; + readonly reason: any; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: PromiseLike; + reason?: any; +} + interface PushManager { + readonly supportedContentEncodings: ReadonlyArray; getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; subscribe(options?: PushSubscriptionOptionsInit): Promise; @@ -9147,7 +10156,8 @@ declare var PushManager: { }; interface PushSubscription { - readonly endpoint: USVString; + readonly endpoint: string; + readonly expirationTime: number | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): any; @@ -9169,112 +10179,13 @@ declare var 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 | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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; +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } -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; - readonly signal: AbortSignal; - 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; +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDtlsTransportEventMap { @@ -9320,7 +10231,7 @@ interface RTCDtmfSender extends EventTarget { readonly canInsertDTMF: boolean; readonly duration: number; readonly interToneGap: number; - ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null; readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; @@ -9335,19 +10246,10 @@ declare var 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; + sdpMid: string | null; toJSON(): any; } @@ -9452,28 +10354,28 @@ interface RTCPeerConnection extends EventTarget { 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; + onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null; + oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; + onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; readonly remoteDescription: RTCSessionDescription | null; readonly signalingState: RTCSignalingState; - addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise; addStream(stream: MediaStream): void; close(): void; - createAnswer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - createOffer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, options?: RTCOfferOptions): Promise; + createAnswer(options?: RTCOfferOptions): Promise; + createOffer(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; + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit): 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; @@ -9496,10 +10398,14 @@ declare var RTCPeerConnectionIceEvent: { interface RTCRtpReceiverEventMap { "error": Event; + "msdecodercapacitychange": Event; + "msdsh": Event; } interface RTCRtpReceiver extends RTCStatsProvider { onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9596,433 +10502,122 @@ declare var RTCStatsProvider: { new(): RTCStatsProvider; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; +interface RandomSource { + getRandomValues(array: T): T; } -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; +declare var RandomSource: { + prototype: RandomSource; + new(): RandomSource; }; -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; - lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; - unlockOrientation(): 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; +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 | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + insertNode(node: Node): void; + isPointInRange(node: Node, offset: number): boolean; + selectNode(node: Node): void; + selectNodeContents(node: Node): void; + setEnd(node: Node, offset: number): void; + setEndAfter(node: Node): void; + setEndBefore(node: Node): void; + setStart(node: Node, offset: number): void; + setStartAfter(node: Node): void; + setStartBefore(node: 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 Selection: { - prototype: Selection; - new(): Selection; +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 ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -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; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; }; -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } -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; +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; }; -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 { +interface Request extends 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 signal: AbortSignal | null; + readonly type: RequestType; readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; + clone(): Request; } -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; }; -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; +interface Response extends Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; } -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; +declare var Response: { + prototype: Response; + new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; }; interface SVGAElement extends SVGGraphicsElement, SVGURIReference { @@ -10142,6 +10737,11 @@ declare var SVGAnimatedNumberList: { new(): SVGAnimatedNumberList; }; +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; readonly baseVal: SVGPreserveAspectRatio; @@ -10278,21 +10878,21 @@ interface SVGElementEventMap extends ElementEventMap { "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; +interface SVGElement extends Element, ElementCSSInlineStyle { + readonly className: any; + onclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null; + onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null; + onload: ((this: SVGElement, ev: Event) => any) | null; + onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null; + readonly ownerSVGElement: SVGSVGElement | null; + readonly viewportElement: SVGElement | null; + /** @deprecated */ 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; @@ -10322,7 +10922,9 @@ declare var SVGElementInstance: { }; interface SVGElementInstanceList { + /** @deprecated */ readonly length: number; + /** @deprecated */ item(index: number): SVGElementInstance; } @@ -10805,7 +11407,9 @@ declare var SVGFETurbulenceElement: { }; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { + /** @deprecated */ readonly filterResX: SVGAnimatedInteger; + /** @deprecated */ readonly filterResY: SVGAnimatedInteger; readonly filterUnits: SVGAnimatedEnumeration; readonly height: SVGAnimatedLength; @@ -10813,6 +11417,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + /** @deprecated */ 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; @@ -10825,6 +11430,19 @@ declare var SVGFilterElement: { new(): SVGFilterElement; }; +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 SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; readonly width: SVGAnimatedLength; @@ -10877,12 +11495,15 @@ declare var SVGGradientElement: { }; interface SVGGraphicsElement extends SVGElement, SVGTests { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; + /** @deprecated */ + readonly farthestViewportElement: SVGElement | null; + /** @deprecated */ + readonly nearestViewportElement: SVGElement | null; readonly transform: SVGAnimatedTransformList; getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; + getCTM(): SVGMatrix | null; + getScreenCTM(): SVGMatrix | null; + /** @deprecated */ 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; @@ -10964,22 +11585,6 @@ declare var 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; @@ -10996,6 +11601,22 @@ declare var SVGLineElement: { new(): SVGLineElement; }; +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 SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -11006,12 +11627,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: 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; @@ -11021,12 +11642,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; }; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { @@ -11110,26 +11731,47 @@ declare var SVGNumberList: { }; interface SVGPathElement extends SVGGraphicsElement { + /** @deprecated */ readonly pathSegList: SVGPathSegList; + /** @deprecated */ createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + /** @deprecated */ createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + /** @deprecated */ createSVGPathSegClosePath(): SVGPathSegClosePath; + /** @deprecated */ createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + /** @deprecated */ createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + /** @deprecated */ createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + /** @deprecated */ createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + /** @deprecated */ createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + /** @deprecated */ createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + /** @deprecated */ createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + /** @deprecated */ getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; @@ -11575,6 +12217,84 @@ declare var SVGRectElement: { new(): SVGRectElement; }; +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + contentScriptType: string; + /** @deprecated */ + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: ((this: SVGSVGElement, ev: Event) => any) | null; + onerror: ((this: SVGSVGElement, ev: Event) => any) | null; + onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onunload: ((this: SVGSVGElement, ev: Event) => any) | null; + onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; + /** @deprecated */ + readonly pixelUnitToMillimeterX: number; + /** @deprecated */ + readonly pixelUnitToMillimeterY: number; + /** @deprecated */ + readonly screenPixelToMillimeterX: number; + /** @deprecated */ + readonly screenPixelToMillimeterY: number; + /** @deprecated */ + 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; + /** @deprecated */ + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + /** @deprecated */ + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + /** @deprecated */ + pauseAnimations(): void; + /** @deprecated */ + setCurrentTime(seconds: number): void; + /** @deprecated */ + suspendRedraw(maxWaitMilliseconds: number): number; + /** @deprecated */ + unpauseAnimations(): void; + /** @deprecated */ + unsuspendRedraw(suspendHandleID: number): void; + /** @deprecated */ + 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 SVGScriptElement extends SVGElement, SVGURIReference { type: string; addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -11617,6 +12337,15 @@ declare var SVGStringList: { new(): SVGStringList; }; +interface SVGStylable { + className: any; +} + +declare var SVGStylable: { + prototype: SVGStylable; + new(): SVGStylable; +}; + interface SVGStyleElement extends SVGElement { disabled: boolean; media: string; @@ -11633,69 +12362,6 @@ declare var 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; @@ -11720,6 +12386,27 @@ declare var SVGSymbolElement: { new(): SVGSymbolElement; }; +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 SVGTests { + readonly requiredExtensions: SVGStringList; + /** @deprecated */ + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + /** @deprecated */ + hasExtension(extension: string): boolean; +} + interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; readonly textLength: SVGAnimatedLength; @@ -11866,18 +12553,10 @@ declare var 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; +interface SVGURIReference { + readonly href: SVGAnimatedString; } -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -}; - interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11886,9 +12565,9 @@ interface SVGUnitTypes { declare var SVGUnitTypes: SVGUnitTypes; interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; + readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; + readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -11903,7 +12582,8 @@ declare var SVGUseElement: { new(): SVGUseElement; }; -interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { +interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ 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; @@ -11939,6 +12619,477 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; +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; + /** @deprecated */ + 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) | null; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + unlockOrientation(): 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 ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + /** @deprecated */ + readonly bufferSize: number; + /** @deprecated */ + onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null; + 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 ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEvent extends Event { + readonly blockedURI: string; + readonly columnNumber: number; + readonly documentURI: string; + readonly effectiveDirective: string; + readonly lineNumber: number; + readonly originalPolicy: string; + readonly referrer: string; + readonly sourceFile: string; + readonly statusCode: number; + readonly violatedDirective: string; +} + +declare var SecurityPolicyViolationEvent: { + prototype: SecurityPolicyViolationEvent; + new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent; +}; + +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 ServiceUIFrameContext { + getCachedFrameMessage(key: string): string; + postFrameMessage(key: string, data: string): void; +} +declare var ServiceUIFrameContext: ServiceUIFrameContext; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + 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; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): 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: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | 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) | null; + readonly pushManager: PushManager; + readonly scope: string; + 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 ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: "open" | "closed"; +} + +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 | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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) | null; + 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 charLength: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance; +} + +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) | null; + onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + 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(): 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, value: string): void; + [key: string]: any; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + readonly key: string | null; + readonly newValue: string | null; + readonly oldValue: string | null; + readonly storageArea: Storage | null; + readonly url: string; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StorageEventInit extends EventInit { + key?: string; + newValue?: string; + oldValue?: string; + storageArea?: Storage; + url: string; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string | null; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet | null; + readonly title: string | null; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index: number): StyleSheet | null; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SyncManager { getTags(): Promise; register(tag: string): Promise; @@ -11950,8 +13101,8 @@ declare var SyncManager: { }; interface Text extends CharacterData { - readonly wholeText: string; readonly assignedSlot: HTMLSlotElement | null; + readonly wholeText: string; splitText(offset: number): Text; } @@ -11960,10 +13111,30 @@ declare var Text: { new(data?: string): Text; }; +interface TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + 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; @@ -12014,10 +13185,10 @@ interface TextTrack extends EventTarget { 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; + mode: TextTrackMode | number; + oncuechange: ((this: TextTrack, ev: Event) => any) | null; + onerror: ((this: TextTrack, ev: Event) => any) | null; + onload: ((this: TextTrack, ev: Event) => any) | null; readonly readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; @@ -12054,8 +13225,8 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { endTime: number; id: string; - onenter: (this: TextTrackCue, ev: Event) => any; - onexit: (this: TextTrackCue, ev: Event) => any; + onenter: ((this: TextTrackCue, ev: Event) => any) | null; + onexit: ((this: TextTrackCue, ev: Event) => any) | null; pauseOnExit: boolean; startTime: number; text: string; @@ -12141,6 +13312,7 @@ interface TouchEvent extends UIEvent { readonly shiftKey: boolean; readonly targetTouches: TouchList; readonly touches: TouchList; + /** @deprecated */ readonly which: number; } @@ -12149,6 +13321,12 @@ declare var TouchEvent: { new(type: string, touchEventInit?: TouchEventInit): TouchEvent; }; +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + interface TouchList { readonly length: number; item(index: number): Touch | null; @@ -12182,17 +13360,18 @@ declare var TransitionEvent: { interface TreeWalker { currentNode: Node; + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; + firstChild(): Node | null; + lastChild(): Node | null; + nextNode(): Node | null; + nextSibling(): Node | null; + parentNode(): Node | null; + previousNode(): Node | null; + previousSibling(): Node | null; } declare var TreeWalker: { @@ -12211,15 +13390,6 @@ declare var 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; @@ -12231,8 +13401,8 @@ interface URL { port: string; protocol: string; search: string; - username: string; readonly searchParams: URLSearchParams; + username: string; toString(): string; } @@ -12243,6 +13413,142 @@ declare var URL: { revokeObjectURL(url: string): 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; + new (init?: string | URLSearchParams): URLSearchParams; +}; + +interface VRDisplay extends EventTarget { + readonly capabilities: VRDisplayCapabilities; + depthFar: number; + depthNear: number; + readonly displayId: number; + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + readonly stageParameters: VRStageParameters | null; + cancelAnimationFrame(handle: number): void; + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + getFrameData(frameData: VRFrameData): boolean; + getLayers(): VRLayer[]; + /** @deprecated */ + getPose(): VRPose; + requestAnimationFrame(callback: FrameRequestCallback): number; + requestPresent(layers: VRLayer[]): Promise; + resetPose(): void; + submitFrame(pose?: VRPose): void; +} + +declare var VRDisplay: { + prototype: VRDisplay; + new(): VRDisplay; +}; + +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} + +declare var VRDisplayCapabilities: { + prototype: VRDisplayCapabilities; + new(): VRDisplayCapabilities; +}; + +interface VRDisplayEvent extends Event { + readonly display: VRDisplay; + readonly reason: VRDisplayEventReason | null; +} + +declare var VRDisplayEvent: { + prototype: VRDisplayEvent; + new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent; +}; + +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} + +declare var VREyeParameters: { + prototype: VREyeParameters; + new(): VREyeParameters; +}; + +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} + +declare var VRFieldOfView: { + prototype: VRFieldOfView; + new(): VRFieldOfView; +}; + +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} + +declare var VRFrameData: { + prototype: VRFrameData; + new(): VRFrameData; +}; + +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} + +declare var VRPose: { + prototype: VRPose; + new(): VRPose; +}; + interface ValidityState { readonly badInput: boolean; readonly customError: boolean; @@ -12251,10 +13557,10 @@ interface ValidityState { readonly rangeUnderflow: boolean; readonly stepMismatch: boolean; readonly tooLong: boolean; + readonly tooShort: boolean; readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; - readonly tooShort: boolean; } declare var ValidityState: { @@ -12297,9 +13603,9 @@ interface VideoTrackListEventMap { 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; + onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: VideoTrackList, ev: Event) => any) | null; + onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; @@ -12315,6 +13621,137 @@ declare var VideoTrackList: { new(): VideoTrackList; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly RGB32F_EXT: number; + readonly RGBA32F_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + 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_SRGB8_ALPHA8_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_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; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +}; + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_SRGB_S3TC_DXT1_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_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +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 WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_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 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 DRAW_BUFFER0_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 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 MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + interface WaveShaperNode extends AudioNode { curve: Float32Array | null; oversample: OverSampleType; @@ -12326,8 +13763,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -12347,44 +13784,6 @@ declare var 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; @@ -12461,8 +13860,8 @@ interface WebGLRenderingContext { 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; + bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void; + bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void; checkFramebufferStatus(target: number): number; clear(mask: number): void; clearColor(red: number, green: number, blue: number, alpha: number): void; @@ -12470,8 +13869,8 @@ interface WebGLRenderingContext { 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; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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; @@ -12561,7 +13960,7 @@ interface WebGLRenderingContext { 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; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | 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; @@ -12726,13 +14125,13 @@ interface WebGLRenderingContext { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12757,9 +14156,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12789,18 +14188,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -12834,20 +14233,6 @@ interface WebGLRenderingContext { 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; @@ -12880,9 +14265,23 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13028,13 +14427,13 @@ declare var WebGLRenderingContext: { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -13059,9 +14458,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -13091,18 +14490,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -13136,20 +14535,6 @@ declare var WebGLRenderingContext: { 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; @@ -13182,9 +14567,23 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13245,6 +14644,9 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; +interface WebGLVertexArrayObjectOES { +} + interface WebKitCSSMatrix { a: number; b: number; @@ -13345,18 +14747,6 @@ declare var 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; @@ -13365,18 +14755,18 @@ interface WebSocketEventMap { } interface WebSocket extends EventTarget { - binaryType: string; + binaryType: BinaryType; 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; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; readonly protocol: string; readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: USVString | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; @@ -13421,8 +14811,6 @@ declare var WheelEvent: { interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "afterprint": Event; - "beforeprint": Event; "beforeunload": BeforeUnloadEvent; "blur": FocusEvent; "canplay": Event; @@ -13444,7 +14832,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; @@ -13466,21 +14854,21 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "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; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -13510,19 +14898,32 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "touchstart": TouchEvent; "unload": Event; "volumechange": Event; + "vrdisplayactivate": Event; + "vrdisplayblur": Event; + "vrdisplayconnect": Event; + "vrdisplaydeactivate": Event; + "vrdisplaydisconnect": Event; + "vrdisplayfocus": Event; + "vrdisplaypointerrestricted": Event; + "vrdisplaypointerunrestricted": Event; + "vrdisplaypresentchange": Event; "waiting": Event; } interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { + Blob: typeof Blob; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; readonly applicationCache: ApplicationCache; readonly caches: CacheStorage; readonly clientInformation: Navigator; readonly closed: boolean; readonly crypto: Crypto; + customElements: CustomElementRegistry; defaultStatus: string; readonly devicePixelRatio: number; - readonly document: Document; readonly doNotTrack: string; + readonly document: Document; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13532,7 +14933,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly innerWidth: number; readonly isSecureContext: boolean; readonly length: number; - readonly location: Location; + location: Location; readonly locationbar: BarProp; readonly menubar: BarProp; readonly msContentScript: ExtensionScriptApis; @@ -13540,99 +14941,106 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + onabort: ((this: Window, ev: UIEvent) => any) | null; + onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; + onblur: ((this: Window, ev: FocusEvent) => any) | null; + oncanplay: ((this: Window, ev: Event) => any) | null; + oncanplaythrough: ((this: Window, ev: Event) => any) | null; + onchange: ((this: Window, ev: Event) => any) | null; + onclick: ((this: Window, ev: MouseEvent) => any) | null; + oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; + oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; + ondblclick: ((this: Window, ev: MouseEvent) => any) | null; + ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; + ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; + ondrag: ((this: Window, ev: DragEvent) => any) | null; + ondragend: ((this: Window, ev: DragEvent) => any) | null; + ondragenter: ((this: Window, ev: DragEvent) => any) | null; + ondragleave: ((this: Window, ev: DragEvent) => any) | null; + ondragover: ((this: Window, ev: DragEvent) => any) | null; + ondragstart: ((this: Window, ev: DragEvent) => any) | null; + ondrop: ((this: Window, ev: DragEvent) => any) | null; + ondurationchange: ((this: Window, ev: Event) => any) | null; + onemptied: ((this: Window, ev: Event) => any) | null; + onended: ((this: Window, ev: Event) => any) | null; 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; + onfocus: ((this: Window, ev: FocusEvent) => any) | null; + onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; + oninput: ((this: Window, ev: Event) => any) | null; + oninvalid: ((this: Window, ev: Event) => any) | null; + onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; + onload: ((this: Window, ev: Event) => any) | null; + onloadeddata: ((this: Window, ev: Event) => any) | null; + onloadedmetadata: ((this: Window, ev: Event) => any) | null; + onloadstart: ((this: Window, ev: Event) => any) | null; + onmessage: ((this: Window, ev: MessageEvent) => any) | null; + onmousedown: ((this: Window, ev: MouseEvent) => any) | null; + onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; + onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; + onmousemove: ((this: Window, ev: MouseEvent) => any) | null; + onmouseout: ((this: Window, ev: MouseEvent) => any) | null; + onmouseover: ((this: Window, ev: MouseEvent) => any) | null; + onmouseup: ((this: Window, ev: MouseEvent) => any) | null; + onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; + onmsgesturechange: ((this: Window, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; + onmsgestureend: ((this: Window, ev: Event) => any) | null; + onmsgesturehold: ((this: Window, ev: Event) => any) | null; + onmsgesturestart: ((this: Window, ev: Event) => any) | null; + onmsgesturetap: ((this: Window, ev: Event) => any) | null; + onmsinertiastart: ((this: Window, ev: Event) => any) | null; + onmspointercancel: ((this: Window, ev: Event) => any) | null; + onmspointerdown: ((this: Window, ev: Event) => any) | null; + onmspointerenter: ((this: Window, ev: Event) => any) | null; + onmspointerleave: ((this: Window, ev: Event) => any) | null; + onmspointermove: ((this: Window, ev: Event) => any) | null; + onmspointerout: ((this: Window, ev: Event) => any) | null; + onmspointerover: ((this: Window, ev: Event) => any) | null; + onmspointerup: ((this: Window, ev: Event) => any) | null; + onoffline: ((this: Window, ev: Event) => any) | null; + ononline: ((this: Window, ev: Event) => any) | null; + onorientationchange: ((this: Window, ev: Event) => any) | null; + onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpause: ((this: Window, ev: Event) => any) | null; + onplay: ((this: Window, ev: Event) => any) | null; + onplaying: ((this: Window, ev: Event) => any) | null; + onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; + onprogress: ((this: Window, ev: ProgressEvent) => any) | null; + onratechange: ((this: Window, ev: Event) => any) | null; + onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; + onreset: ((this: Window, ev: Event) => any) | null; + onresize: ((this: Window, ev: UIEvent) => any) | null; + onscroll: ((this: Window, ev: UIEvent) => any) | null; + onseeked: ((this: Window, ev: Event) => any) | null; + onseeking: ((this: Window, ev: Event) => any) | null; + onselect: ((this: Window, ev: UIEvent) => any) | null; + onstalled: ((this: Window, ev: Event) => any) | null; + onstorage: ((this: Window, ev: StorageEvent) => any) | null; + onsubmit: ((this: Window, ev: Event) => any) | null; + onsuspend: ((this: Window, ev: Event) => any) | null; + ontimeupdate: ((this: Window, ev: Event) => any) | null; 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; + onunload: ((this: Window, ev: Event) => any) | null; + onvolumechange: ((this: Window, ev: Event) => any) | null; + onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplayblur: ((this: Window, ev: Event) => any) | null; + onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + onwaiting: ((this: Window, ev: Event) => any) | null; + readonly opener: any; + readonly orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; readonly pageXOffset: number; @@ -13645,9 +15053,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; - readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; + readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13656,20 +15064,18 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + 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; departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; getSelection(): Selection; matchMedia(mediaQuery: string): MediaQueryList; moveBy(x?: number, y?: number): void; @@ -13683,19 +15089,17 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window requestAnimationFrame(callback: FrameRequestCallback): number; resizeBy(x?: number, y?: number): void; resizeTo(x?: number, y?: number): void; + scroll(options?: ScrollToOptions): void; scroll(x?: number, y?: number): void; + scrollBy(options?: ScrollToOptions): void; scrollBy(x?: number, y?: number): void; + scrollTo(options?: ScrollToOptions): 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; @@ -13707,12 +15111,79 @@ declare var Window: { new(): Window; }; +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowEventHandlersEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "hashchange": HashChangeEvent; + "message": MessageEvent; + "offline": Event; + "online": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface WindowEventHandlers { + onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; + onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; + ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; + onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers extends 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 WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; } interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: Worker, ev: MessageEvent) => any; + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** @deprecated */ postMessage(message: any, transfer?: any[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -13726,6 +15197,41 @@ declare var Worker: { new(stringUrl: string): Worker; }; +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +declare var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; +}; + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: any): Promise; +} + +declare var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(): WritableStreamDefaultWriter; +}; + 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; @@ -13743,7 +15249,8 @@ interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -13755,15 +15262,12 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { 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; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): 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; @@ -13787,6 +15291,30 @@ declare var XMLHttpRequest: { readonly UNSENT: 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) | null; + onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + 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 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; @@ -13890,1070 +15418,16 @@ declare var 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; +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: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[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 ElementCreationOptions { - is?: 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 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; -} - -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 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; - 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; -} - -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; -} - -interface AnimationKeyFrame { - offset?: number | null | (number | null)[]; - easing?: string | string[]; - [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; -} - -interface AnimationOptions { - id?: string; - delay?: number; - direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; - duration?: number; - easing?: string; - endDelay?: number; - fill?: "none" | "forwards" | "backwards" | "both"| "auto"; - iterationStart?: number; - iterations?: number; -} - -interface AnimationTimeline { - readonly currentTime: number | null; -} - -interface ComputedTimingProperties { - endTime: number; - activeDuration: number; - localTime: number | null; - progress: number | null; - currentIteration: number | null; -} - -interface AnimationEffectReadOnly { - readonly timing: number; - getComputedTiming(): ComputedTimingProperties; -} - -interface AnimationPlaybackEventInit extends EventInit { - currentTime?: number | null; - timelineTime?: number | null; -} - -interface AnimationPlaybackEvent extends Event { - readonly currentTime: number | null; - readonly timelineTime: number | null; -} - -declare var AnimationPlaybackEvent: { - prototype: AnimationPlaybackEvent; - new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; -}; - -interface Animation { - currentTime: number | null; - effect: AnimationEffectReadOnly; - readonly finished: Promise; - id: string; - readonly pending: boolean; - readonly playState: "idle" | "running" | "paused" | "finished"; - playbackRate: number; - readonly ready: Promise; - startTime: number; - timeline: AnimationTimeline; - oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; - onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; - cancel(): void; - finish(): void; - pause(): void; - play(): void; - reverse(): void; -} - -declare var Animation: { - prototype: Animation; - new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; }; declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; @@ -14961,66 +15435,95 @@ declare type EventListenerOrEventListenerObject = EventListener | EventListenerO interface DecodeErrorCallback { (error: DOMException): void; } + interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } + interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; } + +interface EventHandlerNonNull { + (event: Event): any; +} + interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, 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 MediaQueryListListener { + (mql: MediaQueryList): void; } + 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 WritableStreamChunkCallback { + (chunk: any, controller: WritableStreamDefaultController): void; +} + +interface WritableStreamDefaultControllerCallback { + (controller: WritableStreamDefaultController): void; +} + +interface WritableStreamErrorCallback { + (reason: string): void; +} + interface HTMLElementTagNameMap { "a": HTMLAnchorElement; "abbr": HTMLElement; @@ -15147,7 +15650,6 @@ interface HTMLElementTagNameMap { "var": HTMLElement; "video": HTMLVideoElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } @@ -15210,18 +15712,28 @@ interface SVGElementTagNameMap { /** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ 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 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 Blob: typeof Blob; +declare var URL: typeof URL; +declare var URLSearchParams: typeof URLSearchParams; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; declare var closed: boolean; declare var crypto: Crypto; +declare var customElements: CustomElementRegistry; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var document: Document; declare var doNotTrack: string; +declare var document: Document; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -15239,97 +15751,104 @@ 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 onabort: ((this: Window, ev: UIEvent) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +declare var onchange: ((this: Window, ev: Event) => any) | null; +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; +declare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; +declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +declare var onemptied: ((this: Window, ev: Event) => any) | null; +declare var onended: ((this: Window, ev: Event) => any) | null; 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 onfocus: ((this: Window, ev: FocusEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onload: ((this: Window, ev: Event) => any) | null; +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadstart: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; +declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; +declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; +declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; +declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; +declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; +declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; +declare var onmspointermove: ((this: Window, ev: Event) => any) | null; +declare var onmspointerout: ((this: Window, ev: Event) => any) | null; +declare var onmspointerover: ((this: Window, ev: Event) => any) | null; +declare var onmspointerup: ((this: Window, ev: Event) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onorientationchange: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpause: ((this: Window, ev: Event) => any) | null; +declare var onplay: ((this: Window, ev: Event) => any) | null; +declare var onplaying: ((this: Window, ev: Event) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onratechange: ((this: Window, ev: Event) => any) | null; +declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onseeked: ((this: Window, ev: Event) => any) | null; +declare var onseeking: ((this: Window, ev: Event) => any) | null; +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; 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 onunload: ((this: Window, ev: Event) => any) | null; +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; +declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; @@ -15344,9 +15863,9 @@ 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 scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -15355,17 +15874,18 @@ 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 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 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 getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; declare function getSelection(): Selection; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; @@ -15379,23 +15899,21 @@ 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(options?: ScrollToOptions): void; declare function scroll(x?: number, y?: number): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(options?: ScrollToOptions): 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 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; @@ -15406,26 +15924,36 @@ 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 onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; 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 fetch(input?: Request | string, 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 ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type IDBValidKey = number | string | Date | IDBArrayKey; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = Blob | BufferSource | FormData | string; +type MutationRecordType = "attributes" | "characterData" | "childList"; +type AAGUID = string; +type BodyInit = any; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; @@ -15447,9 +15975,6 @@ 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; @@ -15458,35 +15983,32 @@ 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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type AppendMode = "segments" | "sequence"; +type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "suspended" | "running" | "closed"; +type BinaryType = "blob" | "arraybuffer"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanPlayTypeResult = "" | "maybe" | "probably"; type CanvasFillRule = "nonzero" | "evenodd"; type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; +type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; +type EndOfStreamError = "network" | "decode"; type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; +type GamepadHand = "" | "left" | "right"; +type GamepadHapticActuatorType = "vibration"; type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type GamepadMappingType = "" | "standard"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; 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"; @@ -15494,25 +16016,23 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaStreamTrackState = "live" | "ended"; 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 PanningModelType = "equalpower" | "HRTF"; +type PaymentComplete = "success" | "fail" | "unknown"; 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"; @@ -15520,9 +16040,9 @@ 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 RTCIceGatherPolicy = "all" | "nohost" | "relay"; 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"; @@ -15533,9 +16053,22 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " 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 ReadyState = "closed" | "open" | "ended"; +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 ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; +type TextTrackMode = "disabled" | "hidden" | "showing"; type Transport = "usb" | "nfc" | "ble"; +type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; +type VREye = "left" | "right"; type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; \ No newline at end of file diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index 6ecfa6a281d..cc696316bcc 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -21,7 +21,6 @@ and limitations under the License. /// /// - ///////////////////////////// /// DOM APIs ///////////////////////////// @@ -34,10 +33,49 @@ interface Account { rpDisplayName: string; } +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + interface Algorithm { name: string; } +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + interface AnimationEventInit extends EventInit { animationName?: string; elapsedTime?: number; @@ -46,10 +84,71 @@ interface AnimationEventInit extends EventInit { interface AssertionOptions { allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioContextInfo { + currentTime?: number; + sampleRate?: number; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioParamDescriptor { + defaultValue?: number; + maxValue?: number; + minValue?: number; + name?: string; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: number; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface ByteLengthChunk { + byteLength?: number; +} + interface CacheQueryOptions { cacheName?: string; ignoreMethod?: boolean; @@ -57,6 +156,14 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + interface ClientData { challenge: string; extensions?: WebAuthnExtensions; @@ -66,6 +173,12 @@ interface ClientData { tokenBinding?: string; } +interface ClientQueryOptions { + includeReserved?: boolean; + includeUncontrolled?: boolean; + type?: ClientTypes; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; @@ -80,6 +193,10 @@ interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation arrayOfDomainStrings?: string[]; } +interface ConstantSourceOptions { + offset?: number; +} + interface ConstrainBooleanParameters { exact?: boolean; ideal?: boolean; @@ -105,10 +222,27 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + interface CustomEventInit extends EventInit { detail?: T; } +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + interface DeviceAccelerationDict { x?: number | null; y?: number | null; @@ -139,18 +273,39 @@ interface DeviceRotationRateDict { gamma?: number | null; } -interface DOMRectInit { - height?: number; - width?: number; - x?: number; - y?: number; -} - interface DoubleRange { max?: number; min?: number; } +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: string; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: string | Algorithm; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -160,9 +315,13 @@ interface ErrorEventInit extends EventInit { } interface EventInit { - scoped?: boolean; bubbles?: boolean; cancelable?: boolean; + scoped?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; } interface EventModifierInit extends UIEventInit { @@ -187,6 +346,24 @@ interface ExceptionInformation { domain?: string | null; } +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: object | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + request: Request; + reservedClientId?: string; + targetClientId?: string; +} + interface FocusEventInit extends UIEventInit { relatedTarget?: EventTarget | null; } @@ -206,8 +383,12 @@ interface FocusNavigationOrigin { originWidth?: number; } +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + interface GamepadEventInit extends EventInit { - gamepad?: Gamepad | null; + gamepad?: Gamepad; } interface GetNotificationOptions { @@ -215,8 +396,29 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string | null; - oldURL?: string | null; + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: string | Algorithm; + info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface HmacImportParams extends Algorithm { + hash: string | Algorithm; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: string | Algorithm; + length?: number; } interface IDBIndexParameters { @@ -229,10 +431,15 @@ interface IDBObjectStoreParameters { keyPath?: string | string[]; } +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + interface IntersectionObserverEntryInit { - isIntersecting: boolean; boundingClientRect: DOMRectInit; intersectionRect: DOMRectInit; + isIntersecting: boolean; rootBounds: DOMRectInit; target: Element; time: number; @@ -244,8 +451,29 @@ interface IntersectionObserverInit { threshold?: number | number[]; } +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + interface KeyAlgorithm { - name?: string; + name: string; } interface KeyboardEventInit extends EventModifierInit { @@ -260,125 +488,6 @@ interface LongRange { 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; @@ -469,6 +578,16 @@ interface MSCredentialSpec { type: MSCredentialType; } +interface MSDCCEventInit extends EventInit { + maxFr?: number; + maxFs?: number; +} + +interface MSDSHEventInit extends EventInit { + sources?: number[]; + timestamp?: number; +} + interface MSDelay { roundTrip?: number; roundTripMax?: number; @@ -486,7 +605,13 @@ interface MSDescription extends RTCStats { interface MSFIDOCredentialParameters extends MSCredentialParameters { algorithm?: string | Algorithm; - authenticators?: AAGUID[]; + authenticators?: string[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSIceWarningFlags { @@ -514,12 +639,6 @@ interface MSIceWarningFlags { useCandidateChecksFailed?: boolean; } -interface MSIPAddressInfo { - ipAddr?: string; - manufacturerMacAddrMask?: string; - port?: number; -} - interface MSJitter { interArrival?: number; interArrivalMax?: number; @@ -548,8 +667,8 @@ interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; - interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; + interfaceTypeWireless?: boolean; } interface MSOutboundNetwork extends MSNetwork { @@ -586,8 +705,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { iceRole?: RTCIceRole; iceWarningFlags?: MSIceWarningFlags; interfaces?: MSNetworkInterfaceType; - localAddress?: string; localAddrType?: MSIceAddrType; + localAddress?: string; localInterface?: MSNetworkInterfaceType; localMR?: string; localMRTCPPort?: number; @@ -601,8 +720,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { portRangeMax?: number; portRangeMin?: number; protocol?: RTCIceProtocol; - remoteAddress?: string; remoteAddrType?: MSIceAddrType; + remoteAddress?: string; remoteMR?: string; remoteMRTCPPort?: number; remoteSite?: string; @@ -671,6 +790,133 @@ interface MSVideoSendPayload extends MSVideoPayload { sendVideoStreamsMax?: number; } +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +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 MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + channelCount?: number | ConstrainLongRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + displaySurface?: string | string[] | ConstrainDOMStringParameters; + echoCancellation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + latency?: number | ConstrainDoubleRange; + logicalSurface?: boolean | ConstrainBooleanParameters; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +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 { + channel?: string; + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: Window | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + interface MsZoomToOptions { animate?: string; contentX?: number; @@ -690,8 +936,14 @@ interface MutationObserverInit { subtree?: boolean; } +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; +} + interface NotificationOptions { body?: string; + data?: any; dir?: NotificationDirection; icon?: string; lang?: string; @@ -702,18 +954,49 @@ interface ObjectURLOptions { oneTimeOnly?: boolean; } +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + interface PaymentCurrencyAmount { currency: string; currencySystem?: string; value: string; } -interface PaymentDetails { +interface PaymentDetailsBase { displayItems?: PaymentItem[]; - error?: string; modifiers?: PaymentDetailsModifier[]; shippingOptions?: PaymentShippingOption[]; - total?: PaymentItem; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; } interface PaymentDetailsModifier { @@ -723,6 +1006,11 @@ interface PaymentDetailsModifier { total?: PaymentItem; } +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + total?: PaymentItem; +} + interface PaymentItem { amount: PaymentCurrencyAmount; label: string; @@ -752,10 +1040,21 @@ interface PaymentShippingOption { selected?: boolean; } +interface Pbkdf2Params extends Algorithm { + hash: string | Algorithm; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + interface PeriodicWaveConstraints { disableNormalization?: boolean; } +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[]; + real?: number[]; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -783,35 +1082,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface PushEventInit extends ExtendableEventInit { + data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | null; + applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; userVisibleOnly?: boolean; } -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - signal?: AbortSignal; - body?: Blob | BufferSource | FormData | string | null; - 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 QueuingStrategy { + highWaterMark?: number; + size?: WritableStreamChunkCallback; } interface RTCConfiguration { @@ -821,6 +1108,10 @@ interface RTCConfiguration { peerIdentity?: string; } +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + interface RTCDtlsFingerprint { algorithm?: string; value?: string; @@ -831,10 +1122,6 @@ interface RTCDtlsParameters { role?: RTCDtlsRole; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCIceCandidateAttributes extends RTCStats { addressSourceUrl?: string; candidateType?: RTCStatsIceCandidateType; @@ -862,8 +1149,8 @@ interface RTCIceCandidateDictionary { interface RTCIceCandidateInit { candidate?: string; - sdpMid?: string; sdpMLineIndex?: number; + sdpMid?: string; } interface RTCIceCandidatePair { @@ -918,13 +1205,13 @@ interface RTCMediaStreamTrackStats extends RTCStats { echoReturnLoss?: number; echoReturnLossEnhancement?: number; frameHeight?: number; + frameWidth?: number; framesCorrupted?: number; framesDecoded?: number; framesDropped?: number; framesPerSecond?: number; framesReceived?: number; framesSent?: number; - frameWidth?: number; remoteSource?: boolean; ssrcIds?: string[]; trackIdentifier?: string; @@ -948,6 +1235,20 @@ interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + mediaType?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtcpFeedback { parameter?: string; type?: string; @@ -969,9 +1270,9 @@ interface RTCRtpCapabilities { interface RTCRtpCodecCapability { clockRate?: number; kind?: string; - maxptime?: number; maxSpatialLayers?: number; maxTemporalLayers?: number; + maxptime?: number; name?: string; numChannels?: number; options?: any; @@ -988,7 +1289,7 @@ interface RTCRtpCodecParameters { name?: string; numChannels?: number; parameters?: any; - payloadType?: any; + payloadType?: number; ptime?: number; rtcpFeedback?: RTCRtcpFeedback[]; } @@ -1047,19 +1348,6 @@ 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; @@ -1111,8 +1399,70 @@ interface RTCTransportStats extends RTCStats { selectedCandidatePairId?: string; } +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: string | Algorithm; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: string | Algorithm; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + interface ScopedCredentialDescriptor { - id: BufferSource; + id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; transports?: Transport[]; type: ScopedCredentialType; } @@ -1120,7 +1470,7 @@ interface ScopedCredentialDescriptor { interface ScopedCredentialOptions { excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } @@ -1129,6 +1479,19 @@ interface ScopedCredentialParameters { type: ScopedCredentialType; } +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; @@ -1139,11 +1502,16 @@ interface ServiceWorkerMessageEventInit extends EventInit { interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; + charLength?: number; elapsedTime?: number; name?: string; utterance?: SpeechSynthesisUtterance | null; } +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + interface StoreExceptionsInformation extends ExceptionInformation { detailURI?: string | null; explanationString?: string | null; @@ -1154,6 +1522,20 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat arrayOfDomainStrings?: string[]; } +interface SyncEventInit extends ExtendableEventInit { + lastChance?: boolean; + tag: string; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } @@ -1168,14 +1550,43 @@ interface UIEventInit extends EventInit { view?: Window | null; } +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCallback; + start: WritableStreamDefaultControllerCallback; + write?: WritableStreamChunkCallback; +} + +interface VRDisplayEventInit extends EventInit { + display: VRDisplay; + reason?: VRDisplayEventReason; +} + +interface VRLayer { + leftBounds?: number[] | null; + rightBounds?: number[] | null; + source?: HTMLCanvasElement | null; +} + +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[]; + oversample?: OverSampleType; +} + interface WebAuthnExtensions { } interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; antialias?: boolean; depth?: boolean; + failIfMajorPerformanceCaveat?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; stencil?: boolean; @@ -1202,6 +1613,67 @@ type WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMErr type WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; }; +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 AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + 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 AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1219,23 +1691,39 @@ declare var 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; +interface Animation { + currentTime: number | null; + effect: AnimationEffectReadOnly; + readonly finished: Promise; + id: string; + readonly pending: boolean; + readonly playState: "idle" | "running" | "paused" | "finished"; + playbackRate: number; + readonly ready: Promise; + startTime: number; + timeline: AnimationTimeline; + cancel(): void; + finish(): void; + oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; + onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; + pause(): void; + play(): void; + reverse(): void; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; }; +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + 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: { @@ -1243,6 +1731,43 @@ declare var AnimationEvent: { new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; }; +interface AnimationKeyFrame { + easing?: string | string[]; + offset?: number | null | (number | null)[]; + [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; +} + +interface AnimationOptions { + delay?: number; + direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; + duration?: number; + easing?: string; + endDelay?: number; + fill?: "none" | "forwards" | "backwards" | "both"| "auto"; + id?: string; + iterationStart?: number; + iterations?: number; +} + +interface AnimationPlaybackEvent extends Event { + readonly currentTime: number | null; + readonly timelineTime: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +interface AnimationTimeline { + readonly currentTime: number | null; +} + interface ApplicationCacheEventMap { "cached": Event; "checking": Event; @@ -1255,14 +1780,14 @@ interface ApplicationCacheEventMap { } 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; + oncached: ((this: ApplicationCache, ev: Event) => any) | null; + onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + onerror: ((this: ApplicationCache, ev: Event) => any) | null; + onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; readonly status: number; abort(): void; swapCache(): void; @@ -1290,9 +1815,13 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; +interface AssignedNodesOptions { + flatten?: boolean; +} + interface Attr extends Node { readonly name: string; - readonly ownerElement: Element; + readonly ownerElement: Element | null; readonly prefix: string | null; readonly specified: boolean; value: string; @@ -1319,7 +1848,7 @@ declare var AudioBuffer: { }; interface AudioBufferSourceNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface AudioBufferSourceNode extends AudioNode { @@ -1328,7 +1857,7 @@ interface AudioBufferSourceNode extends AudioNode { loop: boolean; loopEnd: number; loopStart: number; - onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null; readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; @@ -1351,7 +1880,7 @@ interface AudioContextBase extends EventTarget { readonly currentTime: number; readonly destination: AudioDestinationNode; readonly listener: AudioListener; - onstatechange: (this: AudioContext, ev: Event) => any; + onstatechange: ((this: AudioContext, ev: Event) => any) | null; readonly sampleRate: number; readonly state: AudioContextState; close(): Promise; @@ -1401,10 +1930,15 @@ declare var AudioDestinationNode: { }; interface AudioListener { + /** @deprecated */ dopplerFactor: number; + /** @deprecated */ speedOfSound: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -1422,9 +1956,13 @@ interface AudioNode extends EventTarget { 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; + disconnect(): void; + disconnect(output: number): void; + disconnect(destination: AudioNode): void; + disconnect(destination: AudioNode, output: number): void; + disconnect(destination: AudioNode, output: number, input: number): void; + disconnect(destination: AudioParam): void; + disconnect(destination: AudioParam, output: number): void; } declare var AudioNode: { @@ -1435,12 +1973,12 @@ declare var AudioNode: { interface AudioParam { readonly defaultValue: number; value: number; - cancelScheduledValues(startTime: number): AudioParam; + cancelScheduledValues(cancelTime: 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; + setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam; } declare var AudioParam: { @@ -1481,9 +2019,9 @@ interface AudioTrackListEventMap { 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; + onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: AudioTrackList, ev: Event) => any) | null; + onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -1516,11 +2054,33 @@ declare var BeforeUnloadEvent: { new(): BeforeUnloadEvent; }; +interface BhxBrowser { + readonly lastError: DOMException; + checkMatchesGlobExpression(pattern: string, value: string): boolean; + checkMatchesUriExpression(pattern: string, value: string): boolean; + clearLastError(): void; + currentWindowId(): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + getThisAddress(): any; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericListenerHandler(eventHandler: Function): void; + setLastError(parameters: string): void; + webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void; +} + +declare var BhxBrowser: { + prototype: BhxBrowser; + new(): BhxBrowser; +}; + interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; - readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1543,113 +2103,50 @@ declare var 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; +interface BlobPropertyBag { + endings?: string; + type?: string; } -declare var Cache: { - prototype: Cache; - new(): Cache; +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + close(): void; + postMessage(message: any): 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 CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): Promise; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; } -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -}; - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; +interface ByteLengthQueuingStrategy { + highWaterMark: number; + size(chunk?: any): number; } -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; +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -1660,190 +2157,8 @@ declare var 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 { + escape(value: string): string; supports(property: string, value?: string): boolean; } declare var CSS: CSS; @@ -1903,7 +2218,7 @@ interface CSSKeyframesRule extends CSSRule { name: string; appendRule(rule: string): void; deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; + findRule(rule: string): CSSKeyframeRule | null; } declare var CSSKeyframesRule: { @@ -1944,14 +2259,14 @@ declare var CSSPageRule: { interface CSSRule { cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; + readonly parentRule: CSSRule | null; + readonly parentStyleSheet: CSSStyleSheet | null; 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 KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1967,8 +2282,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAME_RULE: number; readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1980,7 +2295,7 @@ declare var CSSRule: { interface CSSRuleList { readonly length: number; - item(index: number): CSSRule; + item(index: number): CSSRule | null; [index: number]: CSSRule; } @@ -1992,8 +2307,8 @@ declare var CSSRuleList: { interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignmentBaseline: string | null; alignSelf: string | null; + alignmentBaseline: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -2069,9 +2384,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; - columns: string | null; columnSpan: string | null; columnWidth: any; + columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -2105,11 +2420,32 @@ interface CSSStyleDeclaration { fontStyle: string | null; fontVariant: string | null; fontWeight: string | null; + gap: string | null; glyphOrientationHorizontal: string | null; glyphOrientationVertical: string | null; + grid: string | null; + gridArea: string | null; + gridAutoColumns: string | null; + gridAutoFlow: string | null; + gridAutoRows: string | null; + gridColumn: string | null; + gridColumnEnd: string | null; + gridColumnGap: string | null; + gridColumnStart: string | null; + gridGap: string | null; + gridRow: string | null; + gridRowEnd: string | null; + gridRowGap: string | null; + gridRowStart: string | null; + gridTemplate: string | null; + gridTemplateAreas: string | null; + gridTemplateColumns: string | null; + gridTemplateRows: string | null; height: string | null; imeMode: string | null; justifyContent: string | null; + justifyItems: string | null; + justifySelf: string | null; kerning: string | null; layoutGrid: string | null; layoutGridChar: string | null; @@ -2136,29 +2472,30 @@ interface CSSStyleDeclaration { markerMid: string | null; markerStart: string | null; mask: string | null; + maskImage: 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; + msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumns: string | null; msGridColumnSpan: any; + msGridColumns: string | null; msGridRow: any; msGridRowAlign: string | null; - msGridRows: string | null; msGridRowSpan: any; + msGridRows: string | null; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -2187,6 +2524,8 @@ interface CSSStyleDeclaration { msWrapFlow: string; msWrapMargin: any; msWrapThrough: string; + objectFit: string | null; + objectPosition: string | null; opacity: string | null; order: string | null; orphans: string | null; @@ -2207,13 +2546,16 @@ interface CSSStyleDeclaration { pageBreakBefore: string | null; pageBreakInside: string | null; readonly parentRule: CSSRule; + penAction: string | null; perspective: string | null; perspectiveOrigin: string | null; pointerEvents: string | null; position: string | null; quotes: string | null; + resize: string | null; right: string | null; rotate: string | null; + rowGap: string | null; rubyAlign: string | null; rubyOverhang: string | null; rubyPosition: string | null; @@ -2232,6 +2574,7 @@ interface CSSStyleDeclaration { textAlign: string | null; textAlignLast: string | null; textAnchor: string | null; + textCombineUpright: string | null; textDecoration: string | null; textIndent: string | null; textJustify: string | null; @@ -2253,6 +2596,7 @@ interface CSSStyleDeclaration { transitionTimingFunction: string | null; translate: string | null; unicodeBidi: string | null; + userSelect: string | null; verticalAlign: string | null; visibility: string | null; webkitAlignContent: string | null; @@ -2294,9 +2638,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; - webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; + webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2335,13 +2679,11 @@ interface CSSStyleDeclaration { 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; + setProperty(propertyName: string, value: string | null, priority?: string | null): void; [index: number]: string; } @@ -2351,7 +2693,6 @@ declare var CSSStyleDeclaration: { }; interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; selectorText: string; readonly style: CSSStyleDeclaration; } @@ -2363,21 +2704,32 @@ declare var CSSStyleRule: { interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; + /** @deprecated */ cssText: string; + /** @deprecated */ readonly id: string; + /** @deprecated */ readonly imports: StyleSheetList; + /** @deprecated */ readonly isAlternate: boolean; + /** @deprecated */ readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; + readonly ownerRule: CSSRule | null; + /** @deprecated */ readonly owningElement: Element; - readonly pages: StyleSheetPageList; + /** @deprecated */ + readonly pages: any; + /** @deprecated */ readonly readOnly: boolean; readonly rules: CSSRuleList; + /** @deprecated */ addImport(bstrURL: string, lIndex?: number): number; + /** @deprecated */ 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; + /** @deprecated */ removeImport(lIndex: number): void; removeRule(lIndex: number): void; } @@ -2395,6 +2747,380 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; +interface Cache { + add(request: Request | string): Promise; + addAll(requests: (Request | string)[]): Promise; + delete(request: Request | string, options?: CacheQueryOptions): Promise; + keys(request?: Request | string, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + matchAll(request?: Request | string, options?: CacheQueryOptions): Promise; + put(request: Request | string, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface Canvas2DContextAttributes { + alpha?: boolean; + storage?: boolean; + willReadFrequently?: boolean; + [attribute: string]: boolean | string | undefined; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +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; + arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: 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 CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends 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; + mozImageSmoothingEnabled: boolean; + msFillRule: CanvasFillRule; + oImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + webkitImageSmoothingEnabled: 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; + drawFocusIfNeeded(path: Path2D, 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; + isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(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 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 ChildNode { + remove(): void; +} + +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 ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(data?: string): 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 ComputedTimingProperties { + activeDuration: number; + currentIteration: number | null; + endTime: number; + localTime: number | null; + progress: number | null; +} + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: 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; + markTimeline(label?: string): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ContentScriptGlobalScope extends EventTarget { + readonly msContentScript: ExtensionScriptApis; + readonly window: Window; +} + +declare var ContentScriptGlobalScope: { + prototype: ContentScriptGlobalScope; + new(): ContentScriptGlobalScope; +}; + +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 CountQueuingStrategy { + highWaterMark: number; + size(): number; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(strategy: QueuingStrategy): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null; +} + +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 CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + whenDefined(name: string): PromiseLike; +} + interface CustomEvent extends Event { readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; @@ -2405,6 +3131,194 @@ declare var CustomEvent: { new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; +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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +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 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 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(...tokens: string[]): void; + contains(token: string): boolean; + item(index: number): string | null; + remove(...tokens: string[]): void; + replace(oldToken: string, newToken: string): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DataCue extends TextTrackCue { data: ArrayBuffer; addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -2451,10 +3365,11 @@ declare var DataTransferItem: { interface DataTransferItemList { readonly length: number; add(data: File): DataTransferItem | null; + add(data: string, type: string): DataTransferItem | null; clear(): void; item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: DataTransferItem; + [name: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -2541,11 +3456,30 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; }; +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforedeactivate": UIEvent; + "activate": Event; + "beforeactivate": Event; + "beforedeactivate": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -2553,7 +3487,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "click": MouseEvent; "contextmenu": PointerEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -2563,7 +3497,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "fullscreenchange": Event; @@ -2583,25 +3517,25 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "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; + "MSContentZoom": Event; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSManipulationStateChanged": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "mssitemodejumplistitemremoved": Event; + "msthumbnailclick": Event; "pause": Event; "play": Event; "playing": Event; @@ -2632,7 +3566,15 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "webkitfullscreenerror": Event; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { +interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent { + /** + * 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; /** * Gets the object that has the focus when the parent document has focus. */ @@ -2648,11 +3590,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * 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; + readonly anchors: HTMLCollectionOf; /** * Retrieves a collection of all applet objects in the document. */ - applets: HTMLCollectionOf; + readonly applets: HTMLCollectionOf; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ @@ -2688,7 +3630,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Gets a reference to the root node of the document. */ - documentElement: HTMLElement; + readonly documentElement: HTMLElement; /** * Sets or gets the security domain of the document. */ @@ -2696,7 +3638,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all embed objects in the document. */ - embeds: HTMLCollectionOf; + readonly embeds: HTMLCollectionOf; /** * Sets or gets the foreground (text) color of the document. */ @@ -2704,7 +3646,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of all form objects in the document. */ - forms: HTMLCollectionOf; + readonly forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; @@ -2712,7 +3654,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of img objects in the document. */ - images: HTMLCollectionOf; + readonly images: HTMLCollectionOf; /** * Gets the implementation object of the current document. */ @@ -2732,322 +3674,323 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. */ - links: HTMLCollectionOf; + readonly links: HTMLCollectionOf; /** * Contains information about the current URL. */ - readonly location: Location; - msCapsLockWarningOff: boolean; + location: Location; msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; /** * Fires when the user aborts the download. * @param ev The event. */ - onabort: (this: Document, ev: UIEvent) => any; + onabort: ((this: Document, ev: UIEvent) => any) | null; /** * Fires when the object is set as the active element. * @param ev The event. */ - onactivate: (this: Document, ev: UIEvent) => any; + onactivate: ((this: Document, ev: Event) => any) | null; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ - onbeforeactivate: (this: Document, ev: UIEvent) => any; + onbeforeactivate: ((this: Document, ev: Event) => any) | null; /** * 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; + onbeforedeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ - onblur: (this: Document, ev: FocusEvent) => any; + onblur: ((this: Document, ev: FocusEvent) => any) | null; /** * 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; + oncanplay: ((this: Document, ev: Event) => any) | null; + oncanplaythrough: ((this: Document, ev: Event) => any) | null; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ - onchange: (this: Document, ev: Event) => any; + onchange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ - onclick: (this: Document, ev: MouseEvent) => any; + onclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ - ondblclick: (this: Document, ev: MouseEvent) => any; + ondblclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + ondeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ - ondrag: (this: Document, ev: DragEvent) => any; + ondrag: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragend: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragenter: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragleave: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragover: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragstart: ((this: Document, ev: DragEvent) => any) | null; + ondrop: ((this: Document, ev: DragEvent) => any) | null; /** * Occurs when the duration attribute is updated. * @param ev The event. */ - ondurationchange: (this: Document, ev: Event) => any; + ondurationchange: ((this: Document, ev: Event) => any) | null; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ - onemptied: (this: Document, ev: Event) => any; + onemptied: ((this: Document, ev: Event) => any) | null; /** * Occurs when the end of playback is reached. * @param ev The event */ - onended: (this: Document, ev: MediaStreamErrorEvent) => any; + onended: ((this: Document, ev: Event) => any) | null; /** * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (this: Document, ev: ErrorEvent) => any; + onerror: ((this: Document, ev: ErrorEvent) => any) | null; /** * 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; + onfocus: ((this: Document, ev: FocusEvent) => any) | null; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + oninput: ((this: Document, ev: Event) => any) | null; + oninvalid: ((this: Document, ev: Event) => any) | null; /** * Fires when the user presses a key. * @param ev The keyboard event */ - onkeydown: (this: Document, ev: KeyboardEvent) => any; + onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ - onkeypress: (this: Document, ev: KeyboardEvent) => any; + onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user releases a key. * @param ev The keyboard event */ - onkeyup: (this: Document, ev: KeyboardEvent) => any; + onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires immediately after the browser loads the object. * @param ev The event. */ - onload: (this: Document, ev: Event) => any; + onload: ((this: Document, ev: Event) => any) | null; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ - onloadeddata: (this: Document, ev: Event) => any; + onloadeddata: ((this: Document, ev: Event) => any) | null; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ - onloadedmetadata: (this: Document, ev: Event) => any; + onloadedmetadata: ((this: Document, ev: Event) => any) | null; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ - onloadstart: (this: Document, ev: Event) => any; + onloadstart: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ - onmousedown: (this: Document, ev: MouseEvent) => any; + onmousedown: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ - onmousemove: (this: Document, ev: MouseEvent) => any; + onmousemove: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseout: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ - onmouseover: (this: Document, ev: MouseEvent) => any; + onmouseover: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseup: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmousewheel: ((this: Document, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: Document, ev: Event) => any) | null; + onmsgesturechange: ((this: Document, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null; + onmsgestureend: ((this: Document, ev: Event) => any) | null; + onmsgesturehold: ((this: Document, ev: Event) => any) | null; + onmsgesturestart: ((this: Document, ev: Event) => any) | null; + onmsgesturetap: ((this: Document, ev: Event) => any) | null; + onmsinertiastart: ((this: Document, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null; + onmspointercancel: ((this: Document, ev: Event) => any) | null; + onmspointerdown: ((this: Document, ev: Event) => any) | null; + onmspointerenter: ((this: Document, ev: Event) => any) | null; + onmspointerleave: ((this: Document, ev: Event) => any) | null; + onmspointermove: ((this: Document, ev: Event) => any) | null; + onmspointerout: ((this: Document, ev: Event) => any) | null; + onmspointerover: ((this: Document, ev: Event) => any) | null; + onmspointerup: ((this: Document, ev: Event) => any) | null; /** * 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; + onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null; /** * 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; + onmsthumbnailclick: ((this: Document, ev: Event) => any) | null; /** * Occurs when playback is paused. * @param ev The event. */ - onpause: (this: Document, ev: Event) => any; + onpause: ((this: Document, ev: Event) => any) | null; /** * Occurs when the play method is requested. * @param ev The event. */ - onplay: (this: Document, ev: Event) => any; + onplay: ((this: Document, ev: Event) => any) | null; /** * 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; + onplaying: ((this: Document, ev: Event) => any) | null; + onpointerlockchange: ((this: Document, ev: Event) => any) | null; + onpointerlockerror: ((this: Document, ev: Event) => any) | null; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ - onprogress: (this: Document, ev: ProgressEvent) => any; + onprogress: ((this: Document, ev: ProgressEvent) => any) | null; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ - onratechange: (this: Document, ev: Event) => any; + onratechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the state of the object has changed. * @param ev The event */ - onreadystatechange: (this: Document, ev: Event) => any; + onreadystatechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user resets a form. * @param ev The event. */ - onreset: (this: Document, ev: Event) => any; + onreset: ((this: Document, ev: Event) => any) | null; /** * 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; + onscroll: ((this: Document, ev: UIEvent) => any) | null; /** * Occurs when the seek operation ends. * @param ev The event. */ - onseeked: (this: Document, ev: Event) => any; + onseeked: ((this: Document, ev: Event) => any) | null; /** * Occurs when the current playback position is moved. * @param ev The event. */ - onseeking: (this: Document, ev: Event) => any; + onseeking: ((this: Document, ev: Event) => any) | null; /** * Fires when the current selection changes. * @param ev The event. */ - onselect: (this: Document, ev: UIEvent) => any; + onselect: ((this: Document, ev: UIEvent) => any) | null; /** * 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; + onselectionchange: ((this: Document, ev: Event) => any) | null; + onselectstart: ((this: Document, ev: Event) => any) | null; /** * Occurs when the download has stopped. * @param ev The event. */ - onstalled: (this: Document, ev: Event) => any; + onstalled: ((this: Document, ev: Event) => any) | null; /** * 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; + onstop: ((this: Document, ev: Event) => any) | null; + onsubmit: ((this: Document, ev: Event) => any) | null; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ - onsuspend: (this: Document, ev: Event) => any; + onsuspend: ((this: Document, ev: Event) => any) | null; /** * 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; + ontimeupdate: ((this: Document, ev: Event) => any) | null; + ontouchcancel: ((this: Document, ev: TouchEvent) => any) | null; + ontouchend: ((this: Document, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Document, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Document, ev: TouchEvent) => any) | null; + onvisibilitychange: (this: Document, ev: Event) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ - onvolumechange: (this: Document, ev: Event) => any; + onvolumechange: ((this: Document, ev: Event) => any) | null; /** * 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; + onwaiting: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null; + readonly plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** * Retrieves a value that indicates the current state of the object. @@ -3064,7 +4007,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all script objects in the document. */ - scripts: HTMLCollectionOf; + readonly 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. @@ -3074,14 +4017,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * 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. @@ -3097,7 +4032,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string | null; - onvisibilitychange: (this: Document, ev: Event) => any; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; @@ -3193,6 +4127,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver: Node): XPathNSResolver; /** * 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. @@ -3201,7 +4136,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @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. @@ -3228,6 +4162,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; + elementsFromPoint(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. @@ -3246,6 +4181,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Causes the element to receive the focus and executes the code specified by the onfocus event. */ + /** @deprecated */ focus(): void; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. @@ -3318,10 +4254,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ queryCommandValue(commandId: string): string; releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** @@ -3345,7 +4277,79 @@ declare var Document: { new(): Document; }; -interface DocumentFragment extends Node, NodeSelector, ParentNode { +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + 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: "MSDCCEvent"): MSDCCEvent; + createEvent(eventInterface: "MSDSHEvent"): MSDSHEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + 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: "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: "PromiseRejectionEvent"): PromiseRejectionEvent; + 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: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + 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: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DocumentFragment extends Node, ParentNode { getElementById(elementId: string): HTMLElement | null; } @@ -3354,6 +4358,14 @@ declare var DocumentFragment: { new(): DocumentFragment; }; +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly styleSheets: StyleSheetList; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + getSelection(): Selection | null; +} + interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; readonly internalSubset: string | null; @@ -3368,149 +4380,6 @@ declare var 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; @@ -3536,209 +4405,23 @@ declare var 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 EXT_blend_minmax { + readonly MAX_EXT: number; + readonly MIN_EXT: number; } -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 | null; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB_EXT: number; +} + +interface EXT_shader_texture_lod { +} interface EXT_texture_filter_anisotropic { readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; @@ -3752,14 +4435,262 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; }; +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": Event; + "command": Event; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSGotPointerCapture": Event; + "MSInertiaStart": Event; + "MSLostPointerCapture": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode { + readonly assignedSlot: HTMLSlotElement | null; + readonly attributes: NamedNodeMap; + 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) | null; + oncommand: ((this: Element, ev: Event) => any) | null; + ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onmsgesturechange: ((this: Element, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null; + onmsgestureend: ((this: Element, ev: Event) => any) | null; + onmsgesturehold: ((this: Element, ev: Event) => any) | null; + onmsgesturestart: ((this: Element, ev: Event) => any) | null; + onmsgesturetap: ((this: Element, ev: Event) => any) | null; + onmsgotpointercapture: ((this: Element, ev: Event) => any) | null; + onmsinertiastart: ((this: Element, ev: Event) => any) | null; + onmslostpointercapture: ((this: Element, ev: Event) => any) | null; + onmspointercancel: ((this: Element, ev: Event) => any) | null; + onmspointerdown: ((this: Element, ev: Event) => any) | null; + onmspointerenter: ((this: Element, ev: Event) => any) | null; + onmspointerleave: ((this: Element, ev: Event) => any) | null; + onmspointermove: ((this: Element, ev: Event) => any) | null; + onmspointerout: ((this: Element, ev: Event) => any) | null; + onmspointerover: ((this: Element, ev: Event) => any) | null; + onmspointerup: ((this: Element, ev: Event) => any) | null; + ontouchcancel: ((this: Element, ev: TouchEvent) => any) | null; + ontouchend: ((this: Element, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Element, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Element, ev: TouchEvent) => any) | null; + onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; + outerHTML: string; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly shadowRoot: ShadowRoot | null; + slot: string; + readonly tagName: string; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + getAttribute(qualifiedName: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + getElementsByClassName(classNames: string): NodeListOf; + 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; + hasAttributes(): boolean; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + matches(selectors: string): boolean; + msGetRegionContent(): any; + 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; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + setAttribute(qualifiedName: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): 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: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + readonly style: CSSStyleDeclaration; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ElementDefinitionOptions { + extends: string; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly nextElementSibling: Element | null; + readonly previousElementSibling: Element | null; +} + +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(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly scoped: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget | null; + readonly timeStamp: number; + readonly type: string; + deepPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(typeArg: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; - fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; genericSynchronousFunction(functionId: number, parameters?: string): string; + genericWebRuntimeCallout(to: any, from: any, payload: string): void; getExtensionId(): string; - registerGenericFunctionCallbackHandler(callbackHandler: any): void; - registerGenericPersistentCallbackHandler(callbackHandler: any): void; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericPersistentCallbackHandler(callbackHandler: Function): void; + registerWebRuntimeCallbackHandler(handler: Function): any; } declare var ExtensionScriptApis: { @@ -3776,10 +4707,11 @@ declare var External: { }; interface File extends Blob { + readonly lastModified: number; + /** @deprecated */ readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; - readonly lastModified: number; } declare var File: { @@ -3789,7 +4721,7 @@ declare var File: { interface FileList { readonly length: number; - item(index: number): File; + item(index: number): File | null; [index: number]: File; } @@ -3798,21 +4730,49 @@ declare var FileList: { new(): FileList; }; -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; 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; + readAsText(blob: Blob, label?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[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: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface FocusEvent extends UIEvent { @@ -3850,7 +4810,8 @@ interface FormData { declare var FormData: { prototype: FormData; - new (form?: HTMLFormElement): FormData; + new(): FormData; + new(form: HTMLFormElement): FormData; }; interface GainNode extends AudioNode { @@ -3866,9 +4827,13 @@ interface Gamepad { readonly axes: number[]; readonly buttons: GamepadButton[]; readonly connected: boolean; + readonly displayId: number; + readonly hand: GamepadHand; + readonly hapticActuators: GamepadHapticActuator[]; readonly id: string; readonly index: number; - readonly mapping: string; + readonly mapping: GamepadMappingType; + readonly pose: GamepadPose | null; readonly timestamp: number; } @@ -3879,6 +4844,7 @@ declare var Gamepad: { interface GamepadButton { readonly pressed: boolean; + readonly touched: boolean; readonly value: number; } @@ -3896,6 +4862,32 @@ declare var GamepadEvent: { new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; }; +interface GamepadHapticActuator { + readonly type: GamepadHapticActuatorType; + pulse(value: number, duration: number): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GamepadPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; +} + +declare var GamepadPose: { + prototype: GamepadPose; + new(): GamepadPose; +}; + interface Geolocation { clearWatch(watchId: number): void; getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; @@ -3907,45 +4899,41 @@ declare var Geolocation: { new(): Geolocation; }; -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; +interface GetSVGDocument { + getSVGDocument(): Document; } -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; +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; } -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; +interface GlobalEventHandlers { + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + 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; } -declare var History: { - prototype: History; - new(): History; -}; +interface GlobalFetch { + fetch(input?: Request | string, init?: RequestInit): Promise; +} interface HTMLAllCollection { readonly length: number; @@ -3959,55 +4947,30 @@ declare var HTMLAllCollection: { new(): HTMLAllCollection; }; -interface HTMLAnchorElement extends HTMLElement { +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + Methods: string; /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Sets or retrieves the coordinates of the object. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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. @@ -4016,14 +4979,12 @@ interface HTMLAnchorElement extends HTMLElement { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ 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. */ + /** @deprecated */ shape: string; /** * Sets or retrieves the window or frame at which to target content. @@ -4035,10 +4996,6 @@ interface HTMLAnchorElement extends HTMLElement { 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; @@ -4051,70 +5008,44 @@ declare var HTMLAnchorElement: { }; interface HTMLAppletElement extends HTMLElement { + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ 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. */ + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; /** * Sets or retrieves the shape of the object. */ + /** @deprecated */ 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; + /** @deprecated */ + object: string; + /** @deprecated */ vspace: number; - width: number; + /** @deprecated */ + width: string; 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; @@ -4126,7 +5057,7 @@ declare var HTMLAppletElement: { new(): HTMLAppletElement; }; -interface HTMLAreaElement extends HTMLElement { +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { /** * Sets or retrieves a text alternative to the graphic. */ @@ -4136,43 +5067,12 @@ interface HTMLAreaElement extends HTMLElement { */ 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. */ + /** @deprecated */ 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. */ @@ -4181,10 +5081,6 @@ interface HTMLAreaElement extends HTMLElement { * 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; @@ -4216,6 +5112,23 @@ declare var HTMLAudioElement: { new(): HTMLAudioElement; }; +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. + */ + /** @deprecated */ + 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 HTMLBaseElement extends HTMLElement { /** * Gets or sets the baseline URL on which relative links are based. @@ -4240,10 +5153,12 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ face: string; /** * Sets or retrieves the font size of the object. */ + /** @deprecated */ 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; @@ -4256,51 +5171,34 @@ declare var HTMLBaseFontElement: { new(): HTMLBaseFontElement; }; -interface HTMLBodyElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { + /** @deprecated */ + aLink: string; + /** @deprecated */ background: string; - bgColor: any; + /** @deprecated */ + bgColor: string; bgProperties: string; - link: any; + /** @deprecated */ + link: string; + /** @deprecated */ 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; + onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; + onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null; + /** @deprecated */ + text: string; + /** @deprecated */ + vLink: string; 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; @@ -4312,22 +5210,6 @@ declare var 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. @@ -4353,7 +5235,7 @@ interface HTMLButtonElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -4423,12 +5305,12 @@ interface HTMLCanvasElement extends HTMLElement { * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ msToBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; /** * 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; @@ -4464,6 +5346,26 @@ declare var HTMLCollection: { new(): HTMLCollection; }; +interface HTMLCollectionOf extends HTMLCollectionBase { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface HTMLDListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLDataElement extends HTMLElement { value: string; addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4478,7 +5380,7 @@ declare var HTMLDataElement: { }; interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; + readonly 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; @@ -4490,6 +5392,36 @@ declare var HTMLDataListElement: { new(): HTMLDataListElement; }; +interface HTMLDetailsElement extends HTMLElement { + open: boolean; + addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; + addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + interface HTMLDirectoryElement extends HTMLElement { compact: boolean; addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4507,6 +5439,7 @@ interface HTMLDivElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. @@ -4523,19 +5456,6 @@ declare var 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; @@ -4550,12 +5470,12 @@ declare var HTMLDocument: { interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforecopy": ClipboardEvent; - "beforecut": ClipboardEvent; - "beforedeactivate": UIEvent; - "beforepaste": ClipboardEvent; + "activate": Event; + "beforeactivate": Event; + "beforecopy": Event; + "beforecut": Event; + "beforedeactivate": Event; + "beforepaste": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -4566,7 +5486,7 @@ interface HTMLElementEventMap extends ElementEventMap { "cuechange": Event; "cut": ClipboardEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -4576,7 +5496,7 @@ interface HTMLElementEventMap extends ElementEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "input": Event; @@ -4596,8 +5516,8 @@ interface HTMLElementEventMap extends ElementEventMap { "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": WheelEvent; - "MSContentZoom": UIEvent; - "MSManipulationStateChanged": MSManipulationEvent; + "MSContentZoom": Event; + "MSManipulationStateChanged": Event; "paste": ClipboardEvent; "pause": Event; "play": Event; @@ -4618,9 +5538,8 @@ interface HTMLElementEventMap extends ElementEventMap { "waiting": Event; } -interface HTMLElement extends Element { +interface HTMLElement extends Element, ElementCSSInlineStyle { accessKey: string; - readonly children: HTMLCollection; contentEditable: string; readonly dataset: DOMStringMap; dir: string; @@ -4635,84 +5554,83 @@ interface HTMLElement extends Element { 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; + onabort: ((this: HTMLElement, ev: UIEvent) => any) | null; + onactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecut: ((this: HTMLElement, ev: Event) => any) | null; + onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null; + onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oncanplay: ((this: HTMLElement, ev: Event) => any) | null; + oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null; + onchange: ((this: HTMLElement, ev: Event) => any) | null; + onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null; + oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + oncuechange: ((this: HTMLElement, ev: Event) => any) | null; + oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + ondeactivate: ((this: HTMLElement, ev: Event) => any) | null; + ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondurationchange: ((this: HTMLElement, ev: Event) => any) | null; + onemptied: ((this: HTMLElement, ev: Event) => any) | null; + onended: ((this: HTMLElement, ev: Event) => any) | null; + onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null; + onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oninput: ((this: HTMLElement, ev: Event) => any) | null; + oninvalid: ((this: HTMLElement, ev: Event) => any) | null; + onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onload: ((this: HTMLElement, ev: Event) => any) | null; + onloadeddata: ((this: HTMLElement, ev: Event) => any) | null; + onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null; + onloadstart: ((this: HTMLElement, ev: Event) => any) | null; + onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null; + onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + onpause: ((this: HTMLElement, ev: Event) => any) | null; + onplay: ((this: HTMLElement, ev: Event) => any) | null; + onplaying: ((this: HTMLElement, ev: Event) => any) | null; + onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null; + onratechange: ((this: HTMLElement, ev: Event) => any) | null; + onreset: ((this: HTMLElement, ev: Event) => any) | null; + onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null; + onseeked: ((this: HTMLElement, ev: Event) => any) | null; + onseeking: ((this: HTMLElement, ev: Event) => any) | null; + onselect: ((this: HTMLElement, ev: UIEvent) => any) | null; + onselectstart: ((this: HTMLElement, ev: Event) => any) | null; + onstalled: ((this: HTMLElement, ev: Event) => any) | null; + onsubmit: ((this: HTMLElement, ev: Event) => any) | null; + onsuspend: ((this: HTMLElement, ev: Event) => any) | null; + ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null; + onvolumechange: ((this: HTMLElement, ev: Event) => any) | null; + onwaiting: ((this: HTMLElement, ev: Event) => any) | null; outerText: string; spellcheck: boolean; - readonly style: CSSStyleDeclaration; tabIndex: number; title: string; + animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; blur(): void; click(): void; dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; 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; @@ -4749,6 +5667,7 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * Retrieves the palette used for the embedded document. @@ -4829,6 +5748,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ 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; @@ -4909,6 +5829,7 @@ interface HTMLFormElement extends HTMLElement { * Retrieves a form object or an object from an elements collection. */ namedItem(name: string): any; + reportValidity(): boolean; /** * Fires when the user resets a form. */ @@ -4917,8 +5838,6 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ 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; @@ -4947,14 +5866,17 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + /** @deprecated */ + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + /** @deprecated */ + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. @@ -4967,30 +5889,37 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a URI to a long description of the object. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ marginWidth: string; /** * Sets or retrieves the frame name. */ + /** @deprecated */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ + /** @deprecated */ noResize: boolean; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ + /** @deprecated */ src: string; /** * Sets or retrieves the width of the object. @@ -5007,64 +5936,29 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; }; -interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { /** * Sets or retrieves the frame widths of the object. */ + /** @deprecated */ 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; + onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null; + onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null; /** * Sets or retrieves the frame heights of the object. */ + /** @deprecated */ 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; @@ -5077,7 +5971,35 @@ declare var HTMLFrameSetElement: { new(): HTMLFrameSetElement; }; +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + /** @deprecated */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + 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 HTMLHeadElement extends HTMLElement { + /** @deprecated */ 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; @@ -5094,6 +6016,7 @@ interface HTMLHeadingElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ 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; @@ -5106,34 +6029,11 @@ declare var 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. */ + /** @deprecated */ 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; @@ -5146,6 +6046,19 @@ declare var HTMLHtmlElement: { new(): HTMLHtmlElement; }; +interface HTMLHyperlinkElementUtils { + hash: string; + host: string; + hostname: string; + href: string; + origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + toString(): string; +} + interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; } @@ -5154,78 +6067,64 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ 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; + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ 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. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ 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; + readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** - * Sets or retrieves the vertical margin for the object. + * Sets or retrives the content of the page that is to contain. */ - vspace: number; + srcdoc: string; /** * 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; @@ -5241,6 +6140,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5249,6 +6149,7 @@ interface HTMLImageElement extends HTMLElement { /** * Specifies the properties of a border drawn around an object. */ + /** @deprecated */ border: string; /** * Retrieves whether the object is fully loaded. @@ -5256,6 +6157,7 @@ interface HTMLImageElement extends HTMLElement { readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; /** * Sets or retrieves the height of the object. */ @@ -5263,6 +6165,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ hspace: number; /** * Sets or retrieves whether the image is a server-side image map. @@ -5272,6 +6175,7 @@ interface HTMLImageElement extends HTMLElement { * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. */ longDesc: string; + /** @deprecated */ lowsrc: string; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5289,6 +6193,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * The original height of the image resource before sizing. @@ -5311,6 +6216,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the vertical margin for the object. */ + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -5338,6 +6244,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5351,18 +6258,10 @@ interface HTMLInputElement 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 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. */ @@ -5395,7 +6294,7 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -5403,16 +6302,12 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + height: number; indeterminate: boolean; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ - readonly list: HTMLElement; + readonly list: HTMLElement | null; /** * 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. */ @@ -5425,6 +6320,7 @@ interface HTMLInputElement extends HTMLElement { * 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; + minLength: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ @@ -5446,21 +6342,20 @@ interface HTMLInputElement extends HTMLElement { * When present, marks an element that can't be submitted without a value. */ required: boolean; - selectionDirection: string; + selectionDirection: string | null; /** * Gets or sets the end position or offset of a text selection. */ - selectionEnd: number; + selectionEnd: number | null; /** * Gets or sets the starting position or offset of a text selection. */ - selectionStart: number; + selectionStart: number | null; 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. */ @@ -5472,6 +6367,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ + /** @deprecated */ 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. @@ -5485,25 +6381,20 @@ interface HTMLInputElement extends HTMLElement { * Returns the value of the data at the cursor's current position. */ value: string; - valueAsDate: Date; + valueAsDate: any; /** * 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; + width: number; /** * 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. */ @@ -5545,48 +6436,8 @@ declare var 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 { + /** @deprecated */ type: string; /** * Sets or retrieves the value of a list item. @@ -5603,11 +6454,56 @@ declare var HTMLLIElement: { new(): HTMLLIElement; }; +interface HTMLLabelElement extends HTMLElement { + readonly control: HTMLInputElement | null; + /** + * 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; + 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. + */ + /** @deprecated */ + 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 HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; + crossOrigin: string | null; + /** @deprecated */ disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. @@ -5617,6 +6513,8 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { * Sets or retrieves the language code of the object. */ hreflang: string; + import?: Document; + integrity: string; /** * Sets or retrieves the media type. */ @@ -5628,17 +6526,17 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ rev: string; /** * Sets or retrieves the window or frame at which to target content. */ + /** @deprecated */ 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; @@ -5650,6 +6548,18 @@ declare var HTMLLinkElement: { new(): HTMLLinkElement; }; +interface HTMLMainElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. @@ -5677,21 +6587,37 @@ interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { } interface HTMLMarqueeElement extends HTMLElement { + /** @deprecated */ behavior: string; - bgColor: any; + /** @deprecated */ + bgColor: string; + /** @deprecated */ direction: string; + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; + /** @deprecated */ loop: number; - onbounce: (this: HTMLMarqueeElement, ev: Event) => any; - onfinish: (this: HTMLMarqueeElement, ev: Event) => any; - onstart: (this: HTMLMarqueeElement, ev: Event) => any; + /** @deprecated */ + onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ scrollAmount: number; + /** @deprecated */ scrollDelay: number; + /** @deprecated */ trueSpeed: boolean; + /** @deprecated */ vspace: number; + /** @deprecated */ width: string; + /** @deprecated */ start(): void; + /** @deprecated */ 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; @@ -5706,7 +6632,7 @@ declare var HTMLMarqueeElement: { interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; - "msneedkey": MSMediaKeyNeededEvent; + "msneedkey": Event; } interface HTMLMediaElement extends HTMLElement { @@ -5751,7 +6677,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Returns an object representing the current error state of the audio or video element. */ - readonly error: MediaError; + readonly error: MediaError | null; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ @@ -5769,6 +6695,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ + /** @deprecated */ readonly msKeys: MSMediaKeys; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5798,8 +6725,9 @@ interface HTMLMediaElement extends HTMLElement { * Gets the current network activity for the element. */ readonly networkState: number; - onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null; + /** @deprecated */ + onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null; /** * Gets a flag that specifies whether playback is paused. */ @@ -5816,7 +6744,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: number; + readonly readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -5829,18 +6757,18 @@ interface HTMLMediaElement extends HTMLElement { * The address or URL of the a media resource that is to be considered. */ src: string; - srcObject: MediaStream | null; + srcObject: MediaStream | MediaSource | Blob | 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; + addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack; /** * Returns a string that specifies whether the client can play a given media resource type. */ - canPlayType(type: string): string; + canPlayType(type: string): CanPlayTypeResult; /** * Resets the audio or video object and loads a new media resource. */ @@ -5854,6 +6782,7 @@ interface HTMLMediaElement extends HTMLElement { * Inserts the specified audio effect into media pipeline. */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + /** @deprecated */ msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Specifies the media protection manager for a given media pipeline. @@ -5898,6 +6827,7 @@ declare var HTMLMediaElement: { }; interface HTMLMenuElement extends HTMLElement { + /** @deprecated */ compact: boolean; type: string; addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -5915,6 +6845,7 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. @@ -5931,10 +6862,12 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ + /** @deprecated */ scheme: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ + /** @deprecated */ 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; @@ -5985,41 +6918,63 @@ declare var HTMLModElement: { new(): HTMLModElement; }; +interface HTMLOListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLObjectElement extends HTMLElement, GetSVGDocument { - align: 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; + /** @deprecated */ + align: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ border: string; /** * Sets or retrieves the URL of the file containing the compiled Java class. */ + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ + /** @deprecated */ codeType: string; /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + readonly contentDocument: Document | null; /** * Sets or retrieves the URL that references the data of the object. */ data: string; + /** @deprecated */ declare: boolean; /** * Retrieves a reference to the form that the object is embedded in. @@ -6029,6 +6984,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the height of the object. */ height: string; + /** @deprecated */ hspace: number; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -6054,11 +7010,13 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a message to be displayed while an object is loading. */ + /** @deprecated */ standby: string; /** * Sets or retrieves the MIME type of the object. */ type: string; + typemustmatch: boolean; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ @@ -6071,6 +7029,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -6080,7 +7039,6 @@ 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. */ @@ -6101,54 +7059,16 @@ declare var 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; @@ -6204,7 +7124,7 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; remove(index: number): void; } @@ -6216,7 +7136,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; readonly form: HTMLFormElement | null; - readonly htmlFor: DOMSettableTokenList; + readonly htmlFor: DOMTokenList; name: string; readonly type: string; readonly validationMessage: string; @@ -6241,6 +7161,7 @@ interface HTMLParagraphElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -6262,6 +7183,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the content type of the resource designated by the value attribute. */ + /** @deprecated */ type: string; /** * Sets or retrieves the value of an input parameter for an element. @@ -6270,6 +7192,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the data type of the value attribute. */ + /** @deprecated */ 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; @@ -6298,6 +7221,7 @@ interface HTMLPreElement extends HTMLElement { /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ + /** @deprecated */ 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; @@ -6368,11 +7292,15 @@ interface HTMLScriptElement extends HTMLElement { /** * Sets or retrieves the event for which the script is written. */ + /** @deprecated */ event: string; /** * Sets or retrieves the object that is bound to the event script. */ + /** @deprecated */ htmlFor: string; + integrity: string; + noModule: boolean; /** * Retrieves the URL to an external file that contains the source code or data. */ @@ -6385,7 +7313,6 @@ interface HTMLScriptElement extends HTMLElement { * 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; @@ -6428,7 +7355,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the index of the selected option in a select object. */ selectedIndex: number; - selectedOptions: HTMLCollectionOf; + readonly selectedOptions: HTMLCollectionOf; /** * Sets or retrieves the number of rows in the list box. */ @@ -6458,7 +7385,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6468,7 +7395,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + item(name?: any, index?: any): Element | null; /** * 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. @@ -6496,11 +7423,21 @@ declare var HTMLSelectElement: { new(): HTMLSelectElement; }; +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; + addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; + /** @deprecated */ msKeySystem: string; sizes: string; /** @@ -6536,6 +7473,7 @@ declare var HTMLSpanElement: { }; interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** @deprecated */ disabled: boolean; /** * Sets or retrieves the media type. @@ -6556,15 +7494,24 @@ declare var HTMLStyleElement: { new(): HTMLStyleElement; }; +interface HTMLSummaryElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. */ + /** @deprecated */ 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; @@ -6576,7 +7523,7 @@ declare var HTMLTableCaptionElement: { new(): HTMLTableCaptionElement; }; -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableCellElement extends HTMLElement { /** * Sets or retrieves abbreviated text for the object. */ @@ -6584,16 +7531,23 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. */ + /** @deprecated */ axis: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves the position of the object in the cells collection of a row. */ readonly cellIndex: number; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number columns in the table that the object should span. */ @@ -6605,10 +7559,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves the height of the object. */ - height: any; + /** @deprecated */ + height: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ + /** @deprecated */ noWrap: boolean; /** * Sets or retrieves how many rows in a table the cell should span. @@ -6618,9 +7574,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ 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; @@ -6633,19 +7592,27 @@ declare var HTMLTableCellElement: { new(): HTMLTableCellElement; }; -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableColElement extends HTMLElement { /** * Sets or retrieves the alignment of the object relative to the display or table. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of columns in the group. */ span: number; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ - width: any; + /** @deprecated */ + width: string; 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; @@ -6673,67 +7640,64 @@ interface HTMLTableElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; /** * Retrieves the caption object of a table. */ - caption: HTMLTableCaptionElement; + caption: HTMLTableCaptionElement | null; /** * Sets or retrieves the amount of space between the border of the cell and the content of the cell. */ + /** @deprecated */ cellPadding: string; /** * Sets or retrieves the amount of space between cells in a table. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + readonly rows: HTMLCollectionOf; /** * Sets or retrieves which dividing lines (inner borders) are displayed. */ + /** @deprecated */ rules: string; /** * Sets or retrieves a description and/or structure of the object. */ + /** @deprecated */ summary: string; /** * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. */ - tBodies: HTMLCollectionOf; + readonly tBodies: HTMLCollectionOf; /** * Retrieves the tFoot object of the table. */ - tFoot: HTMLTableSectionElement; + tFoot: HTMLTableSectionElement | null; /** * Retrieves the tHead object of the table. */ - tHead: HTMLTableSectionElement; + tHead: HTMLTableSectionElement | null; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ width: string; /** * Creates an empty caption element in the table. @@ -6785,9 +7749,6 @@ declare var 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; @@ -6800,20 +7761,22 @@ declare var HTMLTableHeaderCellElement: { new(): HTMLTableHeaderCellElement; }; -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableRowElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves a collection of all cells in the table row. */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; + readonly cells: HTMLCollectionOf; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Retrieves the position of the object in the rows collection for the table. */ @@ -6822,6 +7785,8 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Retrieves the position of the object in the collection. */ readonly sectionRowIndex: number; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6843,15 +7808,22 @@ declare var HTMLTableRowElement: { new(): HTMLTableRowElement; }; -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableSectionElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of horizontal rows contained in the object. */ - rows: HTMLCollectionOf; + readonly rows: HTMLCollectionOf; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6908,6 +7880,7 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; + minLength: number; /** * Sets or retrieves the name of the object. */ @@ -6936,10 +7909,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -6964,7 +7933,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -7053,7 +8021,9 @@ declare var HTMLTrackElement: { }; interface HTMLUListElement extends HTMLElement { + /** @deprecated */ compact: boolean; + /** @deprecated */ 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; @@ -7095,9 +8065,9 @@ interface HTMLVideoElement extends HTMLMediaElement { msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; - onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; /** * 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. */ @@ -7120,10 +8090,10 @@ interface HTMLVideoElement extends HTMLMediaElement { 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; + 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; @@ -7135,13 +8105,71 @@ declare var HTMLVideoElement: { new(): HTMLVideoElement; }; +interface HTMLegendElement { + readonly form: HTMLFormElement | null; +} + +declare var HTMLegendElement: { + prototype: HTMLegendElement; + new(): HTMLegendElement; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string; + readonly oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: Function, thisArg?: any): 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; + scrollRestoration: ScrollRestoration; + readonly state: any; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): 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 HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + interface IDBCursor { readonly direction: IDBCursorDirection; - key: IDBKeyRange | IDBValidKey; + readonly key: IDBKeyRange | number | string | Date | IDBArrayKey; readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; + readonly source: IDBObjectStore | IDBIndex; advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; + continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void; delete(): IDBRequest; update(value: any): IDBRequest; readonly NEXT: string; @@ -7176,16 +8204,14 @@ interface IDBDatabaseEventMap { 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; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: Event) => any) | null; + readonly version: number; 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; @@ -7197,6 +8223,10 @@ declare var IDBDatabase: { new(): IDBDatabase; }; +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + interface IDBFactory { cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; @@ -7209,16 +8239,16 @@ declare var IDBFactory: { }; interface IDBIndex { - keyPath: string | string[]; + readonly keyPath: string | string[]; + multiEntry: boolean; 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; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -7243,21 +8273,21 @@ declare var IDBKeyRange: { }; interface IDBObjectStore { + autoIncrement: boolean; readonly indexNames: DOMStringList; - keyPath: string | string[]; + readonly keyPath: string | string[] | null; readonly name: string; readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): 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; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; } declare var IDBObjectStore: { @@ -7271,8 +8301,8 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { } interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: IDBOpenDBRequest, ev: Event) => any; - onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; 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; @@ -7291,11 +8321,11 @@ interface IDBRequestEventMap { interface IDBRequest extends EventTarget { readonly error: DOMException; - onerror: (this: IDBRequest, ev: Event) => any; - onsuccess: (this: IDBRequest, ev: Event) => any; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; readonly readyState: IDBRequestReadyState; readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; + readonly 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; @@ -7318,9 +8348,9 @@ 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; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -7359,8 +8389,23 @@ declare var IIRFilterNode: { new(): IIRFilterNode; }; +interface ImageBitmap { + readonly height: number; + readonly width: number; + close(): void; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + interface ImageData { - data: Uint8ClampedArray; + readonly data: Uint8ClampedArray; readonly height: number; readonly width: number; } @@ -7390,10 +8435,10 @@ interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; readonly intersectionRect: ClientRect | DOMRect; + readonly isIntersecting: boolean; readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; - readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -7403,19 +8448,23 @@ declare var IntersectionObserverEntry: { interface KeyboardEvent extends UIEvent { readonly altKey: boolean; - readonly char: string | null; + /** @deprecated */ + char: string; + /** @deprecated */ readonly charCode: number; + readonly code: string; readonly ctrlKey: boolean; readonly key: string; + /** @deprecated */ readonly keyCode: number; - readonly locale: string; readonly location: number; readonly metaKey: boolean; readonly repeat: boolean; readonly shiftKey: boolean; + /** @deprecated */ readonly which: number; - readonly code: string; getModifierState(keyArg: string): boolean; + /** @deprecated */ 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; @@ -7436,6 +8485,10 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_STANDARD: number; }; +interface LinkStyle { + readonly sheet: StyleSheet | null; +} + interface ListeningStateChangedEvent extends Event { readonly label: string; readonly state: ListeningState; @@ -7467,14 +8520,327 @@ declare var Location: { new(): Location; }; -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; } -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; +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 MSDCCEvent extends Event { + readonly maxFr: number; + readonly maxFs: number; +} + +declare var MSDCCEvent: { + prototype: MSDCCEvent; + new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent; +}; + +interface MSDSHEvent extends Event { + readonly sources: number[]; + readonly timestamp: number; +} + +declare var MSDSHEvent: { + prototype: MSDSHEvent; + new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent; +}; + +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 MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +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 MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null; + 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 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 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 MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string | null): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string; +}; + +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 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 MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MSStreamReaderEventMap { + "abort": UIEvent; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSStreamReader extends EventTarget { + readonly error: DOMError; + onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null; + onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null; + onload: ((this: MSStreamReader, ev: Event) => any) | null; + onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: MSStreamReader, ev: Event) => any) | null; + onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; + 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; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface MediaDeviceInfo { @@ -7494,7 +8860,7 @@ interface MediaDevicesEventMap { } interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; + ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; @@ -7557,26 +8923,16 @@ declare var MediaKeyMessageEvent: { new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; }; -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: BufferSource): 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: BufferSource): Promise; + generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: BufferSource): Promise; + update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; } declare var MediaKeySession: { @@ -7586,9 +8942,9 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: BufferSource): MediaKeyStatus; - has(keyId: BufferSource): boolean; + forEach(callback: Function, thisArg?: any): void; + get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus; + has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean; } declare var MediaKeyStatusMap: { @@ -7607,13 +8963,23 @@ declare var MediaKeySystemAccess: { new(): MediaKeySystemAccess; }; +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + interface MediaList { readonly length: number; mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; + appendMedium(medium: string): void; + deleteMedium(medium: string): void; + item(index: number): string | null; + toString(): number; [index: number]: string; } @@ -7660,10 +9026,10 @@ interface MediaStreamEventMap { 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; + onactive: ((this: MediaStream, ev: Event) => any) | null; + onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + oninactive: ((this: MediaStream, ev: Event) => any) | null; + onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; addTrack(track: MediaStreamTrack): void; clone(): MediaStream; getAudioTracks(): MediaStreamTrack[]; @@ -7680,7 +9046,9 @@ interface MediaStream extends EventTarget { declare var MediaStream: { prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; + new(): MediaStream; + new(stream: MediaStream): MediaStream; + new(tracks: MediaStreamTrack[]): MediaStream; }; interface MediaStreamAudioSourceNode extends AudioNode { @@ -7733,10 +9101,10 @@ interface MediaStreamTrack extends EventTarget { 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; + onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readonly: boolean; readonly readyState: MediaStreamTrackState; readonly remote: boolean; @@ -7779,9 +9147,9 @@ declare var 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; + readonly ports: ReadonlyArray; + readonly source: Window | null; + initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void; } declare var MessageEvent: { @@ -7794,7 +9162,7 @@ interface MessagePortEventMap { } interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; @@ -7840,6 +9208,7 @@ interface MouseEvent extends UIEvent { readonly clientX: number; readonly clientY: number; readonly ctrlKey: boolean; + /** @deprecated */ readonly fromElement: Element; readonly layerX: number; readonly layerY: number; @@ -7854,7 +9223,9 @@ interface MouseEvent extends UIEvent { readonly screenX: number; readonly screenY: number; readonly shiftKey: boolean; + /** @deprecated */ readonly toElement: Element; + /** @deprecated */ readonly which: number; readonly x: number; readonly y: number; @@ -7867,456 +9238,6 @@ declare var 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; @@ -8357,7 +9278,7 @@ interface MutationRecord { readonly previousSibling: Node | null; readonly removedNodes: NodeList; readonly target: Node; - readonly type: string; + readonly type: MutationRecordType; } declare var MutationRecord: { @@ -8367,13 +9288,13 @@ declare var 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; + getNamedItem(qualifiedName: string): Attr | null; + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + item(index: number): Attr | null; + removeNamedItem(qualifiedName: string): Attr; + removeNamedItemNS(namespace: string | null, localName: string): Attr; + setNamedItem(attr: Attr): Attr | null; + setNamedItemNS(attr: Attr): Attr | null; [index: number]: Attr; } @@ -8382,39 +9303,13 @@ declare var 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 { +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage { + readonly activeVRDisplays: ReadonlyArray; readonly authentication: WebAuthentication; readonly cookieEnabled: boolean; + readonly doNotTrack: string | null; gamepadInputEmulation: GamepadInputEmulationType; - readonly language: string; + readonly geolocation: Geolocation; readonly maxTouchPoints: number; readonly mimeTypes: MimeTypeArray; readonly msManipulationViewsEnabled: boolean; @@ -8424,10 +9319,8 @@ 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[]; + getGamepads(): (Gamepad | null)[]; + getVRDisplays(): Promise; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; @@ -8439,10 +9332,50 @@ declare var Navigator: { new(): Navigator; }; +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +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 NavigatorLanguage { + readonly language: string; + readonly languages: ReadonlyArray; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getDisplayMedia(constraints: MediaStreamConstraints): Promise; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + interface Node extends EventTarget { - readonly attributes: NamedNodeMap; readonly baseURI: string | null; - readonly childNodes: NodeList; + readonly childNodes: NodeListOf; readonly firstChild: Node | null; readonly lastChild: Node | null; readonly localName: string | null; @@ -8460,7 +9393,6 @@ interface Node extends EventTarget { 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; @@ -8515,7 +9447,7 @@ declare var Node: { }; interface NodeFilter { - acceptNode(n: Node): number; + acceptNode(node: Node): number; } declare var NodeFilter: { @@ -8538,13 +9470,14 @@ declare var NodeFilter: { }; interface NodeIterator { + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; detach(): void; - nextNode(): Node; - previousNode(): Node; + nextNode(): Node | null; + previousNode(): Node | null; } declare var NodeIterator: { @@ -8563,6 +9496,21 @@ declare var NodeList: { new(): NodeList; }; +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +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 NotificationEventMap { "click": Event; "close": Event; @@ -8571,16 +9519,17 @@ interface NotificationEventMap { } interface Notification extends EventTarget { - readonly body: string; + readonly body: string | null; + readonly data: any; 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 icon: string | null; + readonly lang: string | null; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; readonly permission: NotificationPermission; - readonly tag: string; + readonly tag: string | null; readonly title: string; close(): void; addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8647,6 +9596,14 @@ declare var OES_texture_half_float_linear: { new(): OES_texture_half_float_linear; }; +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; +} + interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; } @@ -8662,7 +9619,7 @@ interface OfflineAudioContextEventMap extends AudioContextEventMap { interface OfflineAudioContext extends AudioContextBase { readonly length: number; - oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; + oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null; startRendering(): Promise; suspend(suspendTime: number): Promise; addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8677,13 +9634,13 @@ declare var OfflineAudioContext: { }; interface OscillatorNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface OscillatorNode extends AudioNode { readonly detune: AudioParam; readonly frequency: AudioParam; - onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: OscillatorNode, ev: Event) => any) | null; type: OscillatorType; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; @@ -8734,8 +9691,11 @@ interface PannerNode extends AudioNode { panningModel: PanningModelType; refDistance: number; rolloffFactor: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -8744,12 +9704,28 @@ declare var PannerNode: { new(): PannerNode; }; -interface Path2D extends Object, CanvasPathMethods { +interface ParentNode { + readonly children: HTMLCollection; + 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 ParentNode { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; +} + +interface Path2D extends CanvasPathMethods { } declare var Path2D: { prototype: Path2D; - new(path?: Path2D): Path2D; + new(d?: Path2D | string): Path2D; }; interface PaymentAddress { @@ -8778,12 +9754,14 @@ interface PaymentRequestEventMap { } interface PaymentRequest extends EventTarget { - onshippingaddresschange: (this: PaymentRequest, ev: Event) => any; - onshippingoptionchange: (this: PaymentRequest, ev: Event) => any; + readonly id: string; + onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; + onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; readonly shippingType: PaymentShippingType | null; abort(): Promise; + canMakePayment(): 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; @@ -8793,11 +9771,11 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; - new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; }; interface PaymentRequestUpdateEvent extends Event { - updateWith(d: Promise): void; + updateWith(detailsPromise: Promise): void; } declare var PaymentRequestUpdateEvent: { @@ -8811,6 +9789,7 @@ interface PaymentResponse { readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; + readonly requestId: string; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; @@ -8822,16 +9801,50 @@ declare var PaymentResponse: { new(): PaymentResponse; }; +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 Performance { + /** @deprecated */ readonly navigation: PerformanceNavigation; + readonly timeOrigin: number; + /** @deprecated */ 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; + getEntriesByName(name: string, type?: string): any; + getEntriesByType(type: string): any; + /** @deprecated */ getMarks(markName?: string): any; + /** @deprecated */ getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; @@ -8850,6 +9863,7 @@ interface PerformanceEntry { readonly entryType: string; readonly name: string; readonly startTime: number; + toJSON(): any; } declare var PerformanceEntry: { @@ -8893,28 +9907,41 @@ declare var PerformanceNavigation: { }; interface PerformanceNavigationTiming extends PerformanceEntry { + /** @deprecated */ readonly connectEnd: number; + /** @deprecated */ readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; + /** @deprecated */ readonly domLoading: number; + /** @deprecated */ + readonly domainLookupEnd: number; + /** @deprecated */ + readonly domainLookupStart: number; + /** @deprecated */ readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; + /** @deprecated */ readonly navigationStart: number; readonly redirectCount: number; + /** @deprecated */ readonly redirectEnd: number; + /** @deprecated */ readonly redirectStart: number; + /** @deprecated */ readonly requestStart: number; + /** @deprecated */ readonly responseEnd: number; + /** @deprecated */ readonly responseStart: number; readonly type: NavigationType; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly workerStart: number; } declare var PerformanceNavigationTiming: { @@ -8934,6 +9961,7 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly workerStart: number; } declare var PerformanceResourceTiming: { @@ -8944,13 +9972,13 @@ declare var 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 domainLookupEnd: number; + readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -8961,9 +9989,9 @@ interface PerformanceTiming { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly secureConnectionStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; - readonly secureConnectionStart: number; toJSON(): any; } @@ -8972,35 +10000,6 @@ declare var 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 { } @@ -9082,12 +10081,11 @@ declare var 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; + new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent; }; interface Position { @@ -9135,10 +10133,21 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; + new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent; }; +interface PromiseRejectionEvent extends Event { + readonly promise: PromiseLike; + readonly reason: any; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: PromiseLike; + reason?: any; +} + interface PushManager { + readonly supportedContentEncodings: ReadonlyArray; getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; subscribe(options?: PushSubscriptionOptionsInit): Promise; @@ -9150,7 +10159,8 @@ declare var PushManager: { }; interface PushSubscription { - readonly endpoint: USVString; + readonly endpoint: string; + readonly expirationTime: number | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): any; @@ -9172,112 +10182,13 @@ declare var 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 | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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; +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } -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; - readonly signal: AbortSignal; - 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; +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDtlsTransportEventMap { @@ -9323,7 +10234,7 @@ interface RTCDtmfSender extends EventTarget { readonly canInsertDTMF: boolean; readonly duration: number; readonly interToneGap: number; - ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null; readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; @@ -9338,19 +10249,10 @@ declare var 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; + sdpMid: string | null; toJSON(): any; } @@ -9455,28 +10357,28 @@ interface RTCPeerConnection extends EventTarget { 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; + onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null; + oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; + onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; readonly remoteDescription: RTCSessionDescription | null; readonly signalingState: RTCSignalingState; - addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise; addStream(stream: MediaStream): void; close(): void; - createAnswer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - createOffer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, options?: RTCOfferOptions): Promise; + createAnswer(options?: RTCOfferOptions): Promise; + createOffer(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; + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit): 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; @@ -9499,10 +10401,14 @@ declare var RTCPeerConnectionIceEvent: { interface RTCRtpReceiverEventMap { "error": Event; + "msdecodercapacitychange": Event; + "msdsh": Event; } interface RTCRtpReceiver extends RTCStatsProvider { onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9599,433 +10505,122 @@ declare var RTCStatsProvider: { new(): RTCStatsProvider; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; +interface RandomSource { + getRandomValues(array: T): T; } -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; +declare var RandomSource: { + prototype: RandomSource; + new(): RandomSource; }; -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; - lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; - unlockOrientation(): 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; +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 | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + insertNode(node: Node): void; + isPointInRange(node: Node, offset: number): boolean; + selectNode(node: Node): void; + selectNodeContents(node: Node): void; + setEnd(node: Node, offset: number): void; + setEndAfter(node: Node): void; + setEndBefore(node: Node): void; + setStart(node: Node, offset: number): void; + setStartAfter(node: Node): void; + setStartBefore(node: 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 Selection: { - prototype: Selection; - new(): Selection; +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 ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -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; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; }; -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } -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; +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; }; -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 { +interface Request extends 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 signal: AbortSignal | null; + readonly type: RequestType; readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; + clone(): Request; } -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; }; -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; +interface Response extends Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; } -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; +declare var Response: { + prototype: Response; + new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; }; interface SVGAElement extends SVGGraphicsElement, SVGURIReference { @@ -10145,6 +10740,11 @@ declare var SVGAnimatedNumberList: { new(): SVGAnimatedNumberList; }; +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; readonly baseVal: SVGPreserveAspectRatio; @@ -10281,21 +10881,21 @@ interface SVGElementEventMap extends ElementEventMap { "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; +interface SVGElement extends Element, ElementCSSInlineStyle { + readonly className: any; + onclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null; + onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null; + onload: ((this: SVGElement, ev: Event) => any) | null; + onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null; + readonly ownerSVGElement: SVGSVGElement | null; + readonly viewportElement: SVGElement | null; + /** @deprecated */ 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; @@ -10325,7 +10925,9 @@ declare var SVGElementInstance: { }; interface SVGElementInstanceList { + /** @deprecated */ readonly length: number; + /** @deprecated */ item(index: number): SVGElementInstance; } @@ -10808,7 +11410,9 @@ declare var SVGFETurbulenceElement: { }; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { + /** @deprecated */ readonly filterResX: SVGAnimatedInteger; + /** @deprecated */ readonly filterResY: SVGAnimatedInteger; readonly filterUnits: SVGAnimatedEnumeration; readonly height: SVGAnimatedLength; @@ -10816,6 +11420,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + /** @deprecated */ 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; @@ -10828,6 +11433,19 @@ declare var SVGFilterElement: { new(): SVGFilterElement; }; +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 SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; readonly width: SVGAnimatedLength; @@ -10880,12 +11498,15 @@ declare var SVGGradientElement: { }; interface SVGGraphicsElement extends SVGElement, SVGTests { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; + /** @deprecated */ + readonly farthestViewportElement: SVGElement | null; + /** @deprecated */ + readonly nearestViewportElement: SVGElement | null; readonly transform: SVGAnimatedTransformList; getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; + getCTM(): SVGMatrix | null; + getScreenCTM(): SVGMatrix | null; + /** @deprecated */ 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; @@ -10967,22 +11588,6 @@ declare var 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; @@ -10999,6 +11604,22 @@ declare var SVGLineElement: { new(): SVGLineElement; }; +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 SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -11009,12 +11630,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: 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; @@ -11024,12 +11645,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; }; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { @@ -11113,26 +11734,47 @@ declare var SVGNumberList: { }; interface SVGPathElement extends SVGGraphicsElement { + /** @deprecated */ readonly pathSegList: SVGPathSegList; + /** @deprecated */ createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + /** @deprecated */ createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + /** @deprecated */ createSVGPathSegClosePath(): SVGPathSegClosePath; + /** @deprecated */ createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + /** @deprecated */ createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + /** @deprecated */ createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + /** @deprecated */ createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + /** @deprecated */ createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + /** @deprecated */ createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + /** @deprecated */ createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + /** @deprecated */ getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; @@ -11578,6 +12220,84 @@ declare var SVGRectElement: { new(): SVGRectElement; }; +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + contentScriptType: string; + /** @deprecated */ + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: ((this: SVGSVGElement, ev: Event) => any) | null; + onerror: ((this: SVGSVGElement, ev: Event) => any) | null; + onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onunload: ((this: SVGSVGElement, ev: Event) => any) | null; + onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; + /** @deprecated */ + readonly pixelUnitToMillimeterX: number; + /** @deprecated */ + readonly pixelUnitToMillimeterY: number; + /** @deprecated */ + readonly screenPixelToMillimeterX: number; + /** @deprecated */ + readonly screenPixelToMillimeterY: number; + /** @deprecated */ + 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; + /** @deprecated */ + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + /** @deprecated */ + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + /** @deprecated */ + pauseAnimations(): void; + /** @deprecated */ + setCurrentTime(seconds: number): void; + /** @deprecated */ + suspendRedraw(maxWaitMilliseconds: number): number; + /** @deprecated */ + unpauseAnimations(): void; + /** @deprecated */ + unsuspendRedraw(suspendHandleID: number): void; + /** @deprecated */ + 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 SVGScriptElement extends SVGElement, SVGURIReference { type: string; addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -11620,6 +12340,15 @@ declare var SVGStringList: { new(): SVGStringList; }; +interface SVGStylable { + className: any; +} + +declare var SVGStylable: { + prototype: SVGStylable; + new(): SVGStylable; +}; + interface SVGStyleElement extends SVGElement { disabled: boolean; media: string; @@ -11636,69 +12365,6 @@ declare var 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; @@ -11723,6 +12389,27 @@ declare var SVGSymbolElement: { new(): SVGSymbolElement; }; +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 SVGTests { + readonly requiredExtensions: SVGStringList; + /** @deprecated */ + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + /** @deprecated */ + hasExtension(extension: string): boolean; +} + interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; readonly textLength: SVGAnimatedLength; @@ -11869,18 +12556,10 @@ declare var 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; +interface SVGURIReference { + readonly href: SVGAnimatedString; } -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -}; - interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11889,9 +12568,9 @@ interface SVGUnitTypes { declare var SVGUnitTypes: SVGUnitTypes; interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; + readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; + readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -11906,7 +12585,8 @@ declare var SVGUseElement: { new(): SVGUseElement; }; -interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { +interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ 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; @@ -11942,6 +12622,477 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; +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; + /** @deprecated */ + 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) | null; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + unlockOrientation(): 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 ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + /** @deprecated */ + readonly bufferSize: number; + /** @deprecated */ + onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null; + 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 ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEvent extends Event { + readonly blockedURI: string; + readonly columnNumber: number; + readonly documentURI: string; + readonly effectiveDirective: string; + readonly lineNumber: number; + readonly originalPolicy: string; + readonly referrer: string; + readonly sourceFile: string; + readonly statusCode: number; + readonly violatedDirective: string; +} + +declare var SecurityPolicyViolationEvent: { + prototype: SecurityPolicyViolationEvent; + new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent; +}; + +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 ServiceUIFrameContext { + getCachedFrameMessage(key: string): string; + postFrameMessage(key: string, data: string): void; +} +declare var ServiceUIFrameContext: ServiceUIFrameContext; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + 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; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): 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: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | 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) | null; + readonly pushManager: PushManager; + readonly scope: string; + 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 ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: "open" | "closed"; +} + +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 | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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) | null; + 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 charLength: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance; +} + +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) | null; + onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + 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(): 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, value: string): void; + [key: string]: any; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + readonly key: string | null; + readonly newValue: string | null; + readonly oldValue: string | null; + readonly storageArea: Storage | null; + readonly url: string; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StorageEventInit extends EventInit { + key?: string; + newValue?: string; + oldValue?: string; + storageArea?: Storage; + url: string; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string | null; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet | null; + readonly title: string | null; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index: number): StyleSheet | null; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SyncManager { getTags(): Promise; register(tag: string): Promise; @@ -11953,8 +13104,8 @@ declare var SyncManager: { }; interface Text extends CharacterData { - readonly wholeText: string; readonly assignedSlot: HTMLSlotElement | null; + readonly wholeText: string; splitText(offset: number): Text; } @@ -11963,10 +13114,30 @@ declare var Text: { new(data?: string): Text; }; +interface TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + 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; @@ -12017,10 +13188,10 @@ interface TextTrack extends EventTarget { 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; + mode: TextTrackMode | number; + oncuechange: ((this: TextTrack, ev: Event) => any) | null; + onerror: ((this: TextTrack, ev: Event) => any) | null; + onload: ((this: TextTrack, ev: Event) => any) | null; readonly readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; @@ -12057,8 +13228,8 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { endTime: number; id: string; - onenter: (this: TextTrackCue, ev: Event) => any; - onexit: (this: TextTrackCue, ev: Event) => any; + onenter: ((this: TextTrackCue, ev: Event) => any) | null; + onexit: ((this: TextTrackCue, ev: Event) => any) | null; pauseOnExit: boolean; startTime: number; text: string; @@ -12144,6 +13315,7 @@ interface TouchEvent extends UIEvent { readonly shiftKey: boolean; readonly targetTouches: TouchList; readonly touches: TouchList; + /** @deprecated */ readonly which: number; } @@ -12152,6 +13324,12 @@ declare var TouchEvent: { new(type: string, touchEventInit?: TouchEventInit): TouchEvent; }; +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + interface TouchList { readonly length: number; item(index: number): Touch | null; @@ -12185,17 +13363,18 @@ declare var TransitionEvent: { interface TreeWalker { currentNode: Node; + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; + firstChild(): Node | null; + lastChild(): Node | null; + nextNode(): Node | null; + nextSibling(): Node | null; + parentNode(): Node | null; + previousNode(): Node | null; + previousSibling(): Node | null; } declare var TreeWalker: { @@ -12214,15 +13393,6 @@ declare var 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; @@ -12234,8 +13404,8 @@ interface URL { port: string; protocol: string; search: string; - username: string; readonly searchParams: URLSearchParams; + username: string; toString(): string; } @@ -12246,6 +13416,142 @@ declare var URL: { revokeObjectURL(url: string): 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; + new (init?: string | URLSearchParams): URLSearchParams; +}; + +interface VRDisplay extends EventTarget { + readonly capabilities: VRDisplayCapabilities; + depthFar: number; + depthNear: number; + readonly displayId: number; + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + readonly stageParameters: VRStageParameters | null; + cancelAnimationFrame(handle: number): void; + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + getFrameData(frameData: VRFrameData): boolean; + getLayers(): VRLayer[]; + /** @deprecated */ + getPose(): VRPose; + requestAnimationFrame(callback: FrameRequestCallback): number; + requestPresent(layers: VRLayer[]): Promise; + resetPose(): void; + submitFrame(pose?: VRPose): void; +} + +declare var VRDisplay: { + prototype: VRDisplay; + new(): VRDisplay; +}; + +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} + +declare var VRDisplayCapabilities: { + prototype: VRDisplayCapabilities; + new(): VRDisplayCapabilities; +}; + +interface VRDisplayEvent extends Event { + readonly display: VRDisplay; + readonly reason: VRDisplayEventReason | null; +} + +declare var VRDisplayEvent: { + prototype: VRDisplayEvent; + new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent; +}; + +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} + +declare var VREyeParameters: { + prototype: VREyeParameters; + new(): VREyeParameters; +}; + +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} + +declare var VRFieldOfView: { + prototype: VRFieldOfView; + new(): VRFieldOfView; +}; + +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} + +declare var VRFrameData: { + prototype: VRFrameData; + new(): VRFrameData; +}; + +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} + +declare var VRPose: { + prototype: VRPose; + new(): VRPose; +}; + interface ValidityState { readonly badInput: boolean; readonly customError: boolean; @@ -12254,10 +13560,10 @@ interface ValidityState { readonly rangeUnderflow: boolean; readonly stepMismatch: boolean; readonly tooLong: boolean; + readonly tooShort: boolean; readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; - readonly tooShort: boolean; } declare var ValidityState: { @@ -12300,9 +13606,9 @@ interface VideoTrackListEventMap { 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; + onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: VideoTrackList, ev: Event) => any) | null; + onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; @@ -12318,6 +13624,137 @@ declare var VideoTrackList: { new(): VideoTrackList; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly RGB32F_EXT: number; + readonly RGBA32F_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + 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_SRGB8_ALPHA8_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_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; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +}; + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_SRGB_S3TC_DXT1_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_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +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 WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_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 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 DRAW_BUFFER0_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 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 MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + interface WaveShaperNode extends AudioNode { curve: Float32Array | null; oversample: OverSampleType; @@ -12329,8 +13766,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -12350,44 +13787,6 @@ declare var 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; @@ -12464,8 +13863,8 @@ interface WebGLRenderingContext { 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; + bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void; + bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void; checkFramebufferStatus(target: number): number; clear(mask: number): void; clearColor(red: number, green: number, blue: number, alpha: number): void; @@ -12473,8 +13872,8 @@ interface WebGLRenderingContext { 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; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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; @@ -12564,7 +13963,7 @@ interface WebGLRenderingContext { 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; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | 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; @@ -12729,13 +14128,13 @@ interface WebGLRenderingContext { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12760,9 +14159,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12792,18 +14191,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -12837,20 +14236,6 @@ interface WebGLRenderingContext { 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; @@ -12883,9 +14268,23 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13031,13 +14430,13 @@ declare var WebGLRenderingContext: { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -13062,9 +14461,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -13094,18 +14493,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -13139,20 +14538,6 @@ declare var WebGLRenderingContext: { 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; @@ -13185,9 +14570,23 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13248,6 +14647,9 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; +interface WebGLVertexArrayObjectOES { +} + interface WebKitCSSMatrix { a: number; b: number; @@ -13348,18 +14750,6 @@ declare var 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; @@ -13368,18 +14758,18 @@ interface WebSocketEventMap { } interface WebSocket extends EventTarget { - binaryType: string; + binaryType: BinaryType; 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; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; readonly protocol: string; readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: USVString | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; @@ -13424,8 +14814,6 @@ declare var WheelEvent: { interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "afterprint": Event; - "beforeprint": Event; "beforeunload": BeforeUnloadEvent; "blur": FocusEvent; "canplay": Event; @@ -13447,7 +14835,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; @@ -13469,21 +14857,21 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "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; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -13513,19 +14901,32 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "touchstart": TouchEvent; "unload": Event; "volumechange": Event; + "vrdisplayactivate": Event; + "vrdisplayblur": Event; + "vrdisplayconnect": Event; + "vrdisplaydeactivate": Event; + "vrdisplaydisconnect": Event; + "vrdisplayfocus": Event; + "vrdisplaypointerrestricted": Event; + "vrdisplaypointerunrestricted": Event; + "vrdisplaypresentchange": Event; "waiting": Event; } interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { + Blob: typeof Blob; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; readonly applicationCache: ApplicationCache; readonly caches: CacheStorage; readonly clientInformation: Navigator; readonly closed: boolean; readonly crypto: Crypto; + customElements: CustomElementRegistry; defaultStatus: string; readonly devicePixelRatio: number; - readonly document: Document; readonly doNotTrack: string; + readonly document: Document; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13535,7 +14936,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly innerWidth: number; readonly isSecureContext: boolean; readonly length: number; - readonly location: Location; + location: Location; readonly locationbar: BarProp; readonly menubar: BarProp; readonly msContentScript: ExtensionScriptApis; @@ -13543,99 +14944,106 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + onabort: ((this: Window, ev: UIEvent) => any) | null; + onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; + onblur: ((this: Window, ev: FocusEvent) => any) | null; + oncanplay: ((this: Window, ev: Event) => any) | null; + oncanplaythrough: ((this: Window, ev: Event) => any) | null; + onchange: ((this: Window, ev: Event) => any) | null; + onclick: ((this: Window, ev: MouseEvent) => any) | null; + oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; + oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; + ondblclick: ((this: Window, ev: MouseEvent) => any) | null; + ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; + ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; + ondrag: ((this: Window, ev: DragEvent) => any) | null; + ondragend: ((this: Window, ev: DragEvent) => any) | null; + ondragenter: ((this: Window, ev: DragEvent) => any) | null; + ondragleave: ((this: Window, ev: DragEvent) => any) | null; + ondragover: ((this: Window, ev: DragEvent) => any) | null; + ondragstart: ((this: Window, ev: DragEvent) => any) | null; + ondrop: ((this: Window, ev: DragEvent) => any) | null; + ondurationchange: ((this: Window, ev: Event) => any) | null; + onemptied: ((this: Window, ev: Event) => any) | null; + onended: ((this: Window, ev: Event) => any) | null; 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; + onfocus: ((this: Window, ev: FocusEvent) => any) | null; + onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; + oninput: ((this: Window, ev: Event) => any) | null; + oninvalid: ((this: Window, ev: Event) => any) | null; + onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; + onload: ((this: Window, ev: Event) => any) | null; + onloadeddata: ((this: Window, ev: Event) => any) | null; + onloadedmetadata: ((this: Window, ev: Event) => any) | null; + onloadstart: ((this: Window, ev: Event) => any) | null; + onmessage: ((this: Window, ev: MessageEvent) => any) | null; + onmousedown: ((this: Window, ev: MouseEvent) => any) | null; + onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; + onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; + onmousemove: ((this: Window, ev: MouseEvent) => any) | null; + onmouseout: ((this: Window, ev: MouseEvent) => any) | null; + onmouseover: ((this: Window, ev: MouseEvent) => any) | null; + onmouseup: ((this: Window, ev: MouseEvent) => any) | null; + onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; + onmsgesturechange: ((this: Window, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; + onmsgestureend: ((this: Window, ev: Event) => any) | null; + onmsgesturehold: ((this: Window, ev: Event) => any) | null; + onmsgesturestart: ((this: Window, ev: Event) => any) | null; + onmsgesturetap: ((this: Window, ev: Event) => any) | null; + onmsinertiastart: ((this: Window, ev: Event) => any) | null; + onmspointercancel: ((this: Window, ev: Event) => any) | null; + onmspointerdown: ((this: Window, ev: Event) => any) | null; + onmspointerenter: ((this: Window, ev: Event) => any) | null; + onmspointerleave: ((this: Window, ev: Event) => any) | null; + onmspointermove: ((this: Window, ev: Event) => any) | null; + onmspointerout: ((this: Window, ev: Event) => any) | null; + onmspointerover: ((this: Window, ev: Event) => any) | null; + onmspointerup: ((this: Window, ev: Event) => any) | null; + onoffline: ((this: Window, ev: Event) => any) | null; + ononline: ((this: Window, ev: Event) => any) | null; + onorientationchange: ((this: Window, ev: Event) => any) | null; + onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpause: ((this: Window, ev: Event) => any) | null; + onplay: ((this: Window, ev: Event) => any) | null; + onplaying: ((this: Window, ev: Event) => any) | null; + onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; + onprogress: ((this: Window, ev: ProgressEvent) => any) | null; + onratechange: ((this: Window, ev: Event) => any) | null; + onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; + onreset: ((this: Window, ev: Event) => any) | null; + onresize: ((this: Window, ev: UIEvent) => any) | null; + onscroll: ((this: Window, ev: UIEvent) => any) | null; + onseeked: ((this: Window, ev: Event) => any) | null; + onseeking: ((this: Window, ev: Event) => any) | null; + onselect: ((this: Window, ev: UIEvent) => any) | null; + onstalled: ((this: Window, ev: Event) => any) | null; + onstorage: ((this: Window, ev: StorageEvent) => any) | null; + onsubmit: ((this: Window, ev: Event) => any) | null; + onsuspend: ((this: Window, ev: Event) => any) | null; + ontimeupdate: ((this: Window, ev: Event) => any) | null; 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; + onunload: ((this: Window, ev: Event) => any) | null; + onvolumechange: ((this: Window, ev: Event) => any) | null; + onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplayblur: ((this: Window, ev: Event) => any) | null; + onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + onwaiting: ((this: Window, ev: Event) => any) | null; + readonly opener: any; + readonly orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; readonly pageXOffset: number; @@ -13648,9 +15056,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; - readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; + readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13659,20 +15067,18 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + 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; departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; getSelection(): Selection; matchMedia(mediaQuery: string): MediaQueryList; moveBy(x?: number, y?: number): void; @@ -13686,19 +15092,17 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window requestAnimationFrame(callback: FrameRequestCallback): number; resizeBy(x?: number, y?: number): void; resizeTo(x?: number, y?: number): void; + scroll(options?: ScrollToOptions): void; scroll(x?: number, y?: number): void; + scrollBy(options?: ScrollToOptions): void; scrollBy(x?: number, y?: number): void; + scrollTo(options?: ScrollToOptions): 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; @@ -13710,12 +15114,79 @@ declare var Window: { new(): Window; }; +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowEventHandlersEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "hashchange": HashChangeEvent; + "message": MessageEvent; + "offline": Event; + "online": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface WindowEventHandlers { + onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; + onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; + ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; + onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers extends 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 WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; } interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: Worker, ev: MessageEvent) => any; + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** @deprecated */ postMessage(message: any, transfer?: any[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -13729,6 +15200,41 @@ declare var Worker: { new(stringUrl: string): Worker; }; +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +declare var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; +}; + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: any): Promise; +} + +declare var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(): WritableStreamDefaultWriter; +}; + 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; @@ -13746,7 +15252,8 @@ interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -13758,15 +15265,12 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { 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; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): 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; @@ -13790,6 +15294,30 @@ declare var XMLHttpRequest: { readonly UNSENT: 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) | null; + onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + 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 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; @@ -13893,1070 +15421,16 @@ declare var 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; +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: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[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 ElementCreationOptions { - is?: 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 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; -} - -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 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; - 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; -} - -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; -} - -interface AnimationKeyFrame { - offset?: number | null | (number | null)[]; - easing?: string | string[]; - [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; -} - -interface AnimationOptions { - id?: string; - delay?: number; - direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; - duration?: number; - easing?: string; - endDelay?: number; - fill?: "none" | "forwards" | "backwards" | "both"| "auto"; - iterationStart?: number; - iterations?: number; -} - -interface AnimationTimeline { - readonly currentTime: number | null; -} - -interface ComputedTimingProperties { - endTime: number; - activeDuration: number; - localTime: number | null; - progress: number | null; - currentIteration: number | null; -} - -interface AnimationEffectReadOnly { - readonly timing: number; - getComputedTiming(): ComputedTimingProperties; -} - -interface AnimationPlaybackEventInit extends EventInit { - currentTime?: number | null; - timelineTime?: number | null; -} - -interface AnimationPlaybackEvent extends Event { - readonly currentTime: number | null; - readonly timelineTime: number | null; -} - -declare var AnimationPlaybackEvent: { - prototype: AnimationPlaybackEvent; - new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; -}; - -interface Animation { - currentTime: number | null; - effect: AnimationEffectReadOnly; - readonly finished: Promise; - id: string; - readonly pending: boolean; - readonly playState: "idle" | "running" | "paused" | "finished"; - playbackRate: number; - readonly ready: Promise; - startTime: number; - timeline: AnimationTimeline; - oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; - onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; - cancel(): void; - finish(): void; - pause(): void; - play(): void; - reverse(): void; -} - -declare var Animation: { - prototype: Animation; - new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; }; declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; @@ -14964,66 +15438,95 @@ declare type EventListenerOrEventListenerObject = EventListener | EventListenerO interface DecodeErrorCallback { (error: DOMException): void; } + interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } + interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; } + +interface EventHandlerNonNull { + (event: Event): any; +} + interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, 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 MediaQueryListListener { + (mql: MediaQueryList): void; } + 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 WritableStreamChunkCallback { + (chunk: any, controller: WritableStreamDefaultController): void; +} + +interface WritableStreamDefaultControllerCallback { + (controller: WritableStreamDefaultController): void; +} + +interface WritableStreamErrorCallback { + (reason: string): void; +} + interface HTMLElementTagNameMap { "a": HTMLAnchorElement; "abbr": HTMLElement; @@ -15150,7 +15653,6 @@ interface HTMLElementTagNameMap { "var": HTMLElement; "video": HTMLVideoElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } @@ -15213,18 +15715,28 @@ interface SVGElementTagNameMap { /** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ 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 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 Blob: typeof Blob; +declare var URL: typeof URL; +declare var URLSearchParams: typeof URLSearchParams; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; declare var closed: boolean; declare var crypto: Crypto; +declare var customElements: CustomElementRegistry; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var document: Document; declare var doNotTrack: string; +declare var document: Document; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -15242,97 +15754,104 @@ 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 onabort: ((this: Window, ev: UIEvent) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +declare var onchange: ((this: Window, ev: Event) => any) | null; +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; +declare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; +declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +declare var onemptied: ((this: Window, ev: Event) => any) | null; +declare var onended: ((this: Window, ev: Event) => any) | null; 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 onfocus: ((this: Window, ev: FocusEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onload: ((this: Window, ev: Event) => any) | null; +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadstart: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; +declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; +declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; +declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; +declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; +declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; +declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; +declare var onmspointermove: ((this: Window, ev: Event) => any) | null; +declare var onmspointerout: ((this: Window, ev: Event) => any) | null; +declare var onmspointerover: ((this: Window, ev: Event) => any) | null; +declare var onmspointerup: ((this: Window, ev: Event) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onorientationchange: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpause: ((this: Window, ev: Event) => any) | null; +declare var onplay: ((this: Window, ev: Event) => any) | null; +declare var onplaying: ((this: Window, ev: Event) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onratechange: ((this: Window, ev: Event) => any) | null; +declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onseeked: ((this: Window, ev: Event) => any) | null; +declare var onseeking: ((this: Window, ev: Event) => any) | null; +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; 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 onunload: ((this: Window, ev: Event) => any) | null; +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; +declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; @@ -15347,9 +15866,9 @@ 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 scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -15358,17 +15877,18 @@ 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 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 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 getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; declare function getSelection(): Selection; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; @@ -15382,23 +15902,21 @@ 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(options?: ScrollToOptions): void; declare function scroll(x?: number, y?: number): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(options?: ScrollToOptions): 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 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; @@ -15409,26 +15927,36 @@ 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 onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; 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 fetch(input?: Request | string, 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 ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type IDBValidKey = number | string | Date | IDBArrayKey; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = Blob | BufferSource | FormData | string; +type MutationRecordType = "attributes" | "characterData" | "childList"; +type AAGUID = string; +type BodyInit = any; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; @@ -15450,9 +15978,6 @@ 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; @@ -15461,35 +15986,32 @@ 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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type AppendMode = "segments" | "sequence"; +type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "suspended" | "running" | "closed"; +type BinaryType = "blob" | "arraybuffer"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanPlayTypeResult = "" | "maybe" | "probably"; type CanvasFillRule = "nonzero" | "evenodd"; type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; +type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; +type EndOfStreamError = "network" | "decode"; type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; +type GamepadHand = "" | "left" | "right"; +type GamepadHapticActuatorType = "vibration"; type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type GamepadMappingType = "" | "standard"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; 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"; @@ -15497,25 +16019,23 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaStreamTrackState = "live" | "ended"; 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 PanningModelType = "equalpower" | "HRTF"; +type PaymentComplete = "success" | "fail" | "unknown"; 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"; @@ -15523,9 +16043,9 @@ 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 RTCIceGatherPolicy = "all" | "nohost" | "relay"; 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"; @@ -15536,9 +16056,22 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " 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 ReadyState = "closed" | "open" | "ended"; +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 ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; +type TextTrackMode = "disabled" | "hidden" | "showing"; type Transport = "usb" | "nfc" | "ble"; +type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; +type VREye = "left" | "right"; type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index 6904f7e78a4..1208629b219 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -26,7 +26,6 @@ and limitations under the License. /// - ///////////////////////////// /// DOM APIs ///////////////////////////// @@ -39,10 +38,49 @@ interface Account { rpDisplayName: string; } +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + interface Algorithm { name: string; } +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + interface AnimationEventInit extends EventInit { animationName?: string; elapsedTime?: number; @@ -51,10 +89,71 @@ interface AnimationEventInit extends EventInit { interface AssertionOptions { allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioContextInfo { + currentTime?: number; + sampleRate?: number; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioParamDescriptor { + defaultValue?: number; + maxValue?: number; + minValue?: number; + name?: string; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: number; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface ByteLengthChunk { + byteLength?: number; +} + interface CacheQueryOptions { cacheName?: string; ignoreMethod?: boolean; @@ -62,6 +161,14 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + interface ClientData { challenge: string; extensions?: WebAuthnExtensions; @@ -71,6 +178,12 @@ interface ClientData { tokenBinding?: string; } +interface ClientQueryOptions { + includeReserved?: boolean; + includeUncontrolled?: boolean; + type?: ClientTypes; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; @@ -85,6 +198,10 @@ interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation arrayOfDomainStrings?: string[]; } +interface ConstantSourceOptions { + offset?: number; +} + interface ConstrainBooleanParameters { exact?: boolean; ideal?: boolean; @@ -110,10 +227,27 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + interface CustomEventInit extends EventInit { detail?: T; } +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + interface DeviceAccelerationDict { x?: number | null; y?: number | null; @@ -144,18 +278,39 @@ interface DeviceRotationRateDict { gamma?: number | null; } -interface DOMRectInit { - height?: number; - width?: number; - x?: number; - y?: number; -} - interface DoubleRange { max?: number; min?: number; } +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: string; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: string | Algorithm; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -165,9 +320,13 @@ interface ErrorEventInit extends EventInit { } interface EventInit { - scoped?: boolean; bubbles?: boolean; cancelable?: boolean; + scoped?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; } interface EventModifierInit extends UIEventInit { @@ -192,6 +351,24 @@ interface ExceptionInformation { domain?: string | null; } +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: object | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + request: Request; + reservedClientId?: string; + targetClientId?: string; +} + interface FocusEventInit extends UIEventInit { relatedTarget?: EventTarget | null; } @@ -211,8 +388,12 @@ interface FocusNavigationOrigin { originWidth?: number; } +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + interface GamepadEventInit extends EventInit { - gamepad?: Gamepad | null; + gamepad?: Gamepad; } interface GetNotificationOptions { @@ -220,8 +401,29 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string | null; - oldURL?: string | null; + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: string | Algorithm; + info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface HmacImportParams extends Algorithm { + hash: string | Algorithm; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: string | Algorithm; + length?: number; } interface IDBIndexParameters { @@ -234,10 +436,15 @@ interface IDBObjectStoreParameters { keyPath?: string | string[]; } +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + interface IntersectionObserverEntryInit { - isIntersecting: boolean; boundingClientRect: DOMRectInit; intersectionRect: DOMRectInit; + isIntersecting: boolean; rootBounds: DOMRectInit; target: Element; time: number; @@ -249,8 +456,29 @@ interface IntersectionObserverInit { threshold?: number | number[]; } +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + interface KeyAlgorithm { - name?: string; + name: string; } interface KeyboardEventInit extends EventModifierInit { @@ -265,125 +493,6 @@ interface LongRange { 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; @@ -474,6 +583,16 @@ interface MSCredentialSpec { type: MSCredentialType; } +interface MSDCCEventInit extends EventInit { + maxFr?: number; + maxFs?: number; +} + +interface MSDSHEventInit extends EventInit { + sources?: number[]; + timestamp?: number; +} + interface MSDelay { roundTrip?: number; roundTripMax?: number; @@ -491,7 +610,13 @@ interface MSDescription extends RTCStats { interface MSFIDOCredentialParameters extends MSCredentialParameters { algorithm?: string | Algorithm; - authenticators?: AAGUID[]; + authenticators?: string[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSIceWarningFlags { @@ -519,12 +644,6 @@ interface MSIceWarningFlags { useCandidateChecksFailed?: boolean; } -interface MSIPAddressInfo { - ipAddr?: string; - manufacturerMacAddrMask?: string; - port?: number; -} - interface MSJitter { interArrival?: number; interArrivalMax?: number; @@ -553,8 +672,8 @@ interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; - interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; + interfaceTypeWireless?: boolean; } interface MSOutboundNetwork extends MSNetwork { @@ -591,8 +710,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { iceRole?: RTCIceRole; iceWarningFlags?: MSIceWarningFlags; interfaces?: MSNetworkInterfaceType; - localAddress?: string; localAddrType?: MSIceAddrType; + localAddress?: string; localInterface?: MSNetworkInterfaceType; localMR?: string; localMRTCPPort?: number; @@ -606,8 +725,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { portRangeMax?: number; portRangeMin?: number; protocol?: RTCIceProtocol; - remoteAddress?: string; remoteAddrType?: MSIceAddrType; + remoteAddress?: string; remoteMR?: string; remoteMRTCPPort?: number; remoteSite?: string; @@ -676,6 +795,133 @@ interface MSVideoSendPayload extends MSVideoPayload { sendVideoStreamsMax?: number; } +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +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 MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + channelCount?: number | ConstrainLongRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + displaySurface?: string | string[] | ConstrainDOMStringParameters; + echoCancellation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + latency?: number | ConstrainDoubleRange; + logicalSurface?: boolean | ConstrainBooleanParameters; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +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 { + channel?: string; + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: Window | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + interface MsZoomToOptions { animate?: string; contentX?: number; @@ -695,8 +941,14 @@ interface MutationObserverInit { subtree?: boolean; } +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; +} + interface NotificationOptions { body?: string; + data?: any; dir?: NotificationDirection; icon?: string; lang?: string; @@ -707,18 +959,49 @@ interface ObjectURLOptions { oneTimeOnly?: boolean; } +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + interface PaymentCurrencyAmount { currency: string; currencySystem?: string; value: string; } -interface PaymentDetails { +interface PaymentDetailsBase { displayItems?: PaymentItem[]; - error?: string; modifiers?: PaymentDetailsModifier[]; shippingOptions?: PaymentShippingOption[]; - total?: PaymentItem; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; } interface PaymentDetailsModifier { @@ -728,6 +1011,11 @@ interface PaymentDetailsModifier { total?: PaymentItem; } +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + total?: PaymentItem; +} + interface PaymentItem { amount: PaymentCurrencyAmount; label: string; @@ -757,10 +1045,21 @@ interface PaymentShippingOption { selected?: boolean; } +interface Pbkdf2Params extends Algorithm { + hash: string | Algorithm; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + interface PeriodicWaveConstraints { disableNormalization?: boolean; } +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[]; + real?: number[]; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -788,35 +1087,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface PushEventInit extends ExtendableEventInit { + data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | null; + applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; userVisibleOnly?: boolean; } -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - signal?: AbortSignal; - body?: Blob | BufferSource | FormData | string | null; - 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 QueuingStrategy { + highWaterMark?: number; + size?: WritableStreamChunkCallback; } interface RTCConfiguration { @@ -826,6 +1113,10 @@ interface RTCConfiguration { peerIdentity?: string; } +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + interface RTCDtlsFingerprint { algorithm?: string; value?: string; @@ -836,10 +1127,6 @@ interface RTCDtlsParameters { role?: RTCDtlsRole; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCIceCandidateAttributes extends RTCStats { addressSourceUrl?: string; candidateType?: RTCStatsIceCandidateType; @@ -867,8 +1154,8 @@ interface RTCIceCandidateDictionary { interface RTCIceCandidateInit { candidate?: string; - sdpMid?: string; sdpMLineIndex?: number; + sdpMid?: string; } interface RTCIceCandidatePair { @@ -923,13 +1210,13 @@ interface RTCMediaStreamTrackStats extends RTCStats { echoReturnLoss?: number; echoReturnLossEnhancement?: number; frameHeight?: number; + frameWidth?: number; framesCorrupted?: number; framesDecoded?: number; framesDropped?: number; framesPerSecond?: number; framesReceived?: number; framesSent?: number; - frameWidth?: number; remoteSource?: boolean; ssrcIds?: string[]; trackIdentifier?: string; @@ -953,6 +1240,20 @@ interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + mediaType?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtcpFeedback { parameter?: string; type?: string; @@ -974,9 +1275,9 @@ interface RTCRtpCapabilities { interface RTCRtpCodecCapability { clockRate?: number; kind?: string; - maxptime?: number; maxSpatialLayers?: number; maxTemporalLayers?: number; + maxptime?: number; name?: string; numChannels?: number; options?: any; @@ -993,7 +1294,7 @@ interface RTCRtpCodecParameters { name?: string; numChannels?: number; parameters?: any; - payloadType?: any; + payloadType?: number; ptime?: number; rtcpFeedback?: RTCRtcpFeedback[]; } @@ -1052,19 +1353,6 @@ 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; @@ -1116,8 +1404,70 @@ interface RTCTransportStats extends RTCStats { selectedCandidatePairId?: string; } +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: string | Algorithm; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: string | Algorithm; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + interface ScopedCredentialDescriptor { - id: BufferSource; + id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; transports?: Transport[]; type: ScopedCredentialType; } @@ -1125,7 +1475,7 @@ interface ScopedCredentialDescriptor { interface ScopedCredentialOptions { excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } @@ -1134,6 +1484,19 @@ interface ScopedCredentialParameters { type: ScopedCredentialType; } +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; @@ -1144,11 +1507,16 @@ interface ServiceWorkerMessageEventInit extends EventInit { interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; + charLength?: number; elapsedTime?: number; name?: string; utterance?: SpeechSynthesisUtterance | null; } +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + interface StoreExceptionsInformation extends ExceptionInformation { detailURI?: string | null; explanationString?: string | null; @@ -1159,6 +1527,20 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat arrayOfDomainStrings?: string[]; } +interface SyncEventInit extends ExtendableEventInit { + lastChance?: boolean; + tag: string; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } @@ -1173,14 +1555,43 @@ interface UIEventInit extends EventInit { view?: Window | null; } +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCallback; + start: WritableStreamDefaultControllerCallback; + write?: WritableStreamChunkCallback; +} + +interface VRDisplayEventInit extends EventInit { + display: VRDisplay; + reason?: VRDisplayEventReason; +} + +interface VRLayer { + leftBounds?: number[] | null; + rightBounds?: number[] | null; + source?: HTMLCanvasElement | null; +} + +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[]; + oversample?: OverSampleType; +} + interface WebAuthnExtensions { } interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; antialias?: boolean; depth?: boolean; + failIfMajorPerformanceCaveat?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; stencil?: boolean; @@ -1207,6 +1618,67 @@ type WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMErr type WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; }; +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 AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + 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 AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1224,23 +1696,39 @@ declare var 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; +interface Animation { + currentTime: number | null; + effect: AnimationEffectReadOnly; + readonly finished: Promise; + id: string; + readonly pending: boolean; + readonly playState: "idle" | "running" | "paused" | "finished"; + playbackRate: number; + readonly ready: Promise; + startTime: number; + timeline: AnimationTimeline; + cancel(): void; + finish(): void; + oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; + onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; + pause(): void; + play(): void; + reverse(): void; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; }; +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + 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: { @@ -1248,6 +1736,43 @@ declare var AnimationEvent: { new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; }; +interface AnimationKeyFrame { + easing?: string | string[]; + offset?: number | null | (number | null)[]; + [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; +} + +interface AnimationOptions { + delay?: number; + direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; + duration?: number; + easing?: string; + endDelay?: number; + fill?: "none" | "forwards" | "backwards" | "both"| "auto"; + id?: string; + iterationStart?: number; + iterations?: number; +} + +interface AnimationPlaybackEvent extends Event { + readonly currentTime: number | null; + readonly timelineTime: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +interface AnimationTimeline { + readonly currentTime: number | null; +} + interface ApplicationCacheEventMap { "cached": Event; "checking": Event; @@ -1260,14 +1785,14 @@ interface ApplicationCacheEventMap { } 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; + oncached: ((this: ApplicationCache, ev: Event) => any) | null; + onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + onerror: ((this: ApplicationCache, ev: Event) => any) | null; + onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; readonly status: number; abort(): void; swapCache(): void; @@ -1295,9 +1820,13 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; +interface AssignedNodesOptions { + flatten?: boolean; +} + interface Attr extends Node { readonly name: string; - readonly ownerElement: Element; + readonly ownerElement: Element | null; readonly prefix: string | null; readonly specified: boolean; value: string; @@ -1324,7 +1853,7 @@ declare var AudioBuffer: { }; interface AudioBufferSourceNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface AudioBufferSourceNode extends AudioNode { @@ -1333,7 +1862,7 @@ interface AudioBufferSourceNode extends AudioNode { loop: boolean; loopEnd: number; loopStart: number; - onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null; readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; @@ -1356,7 +1885,7 @@ interface AudioContextBase extends EventTarget { readonly currentTime: number; readonly destination: AudioDestinationNode; readonly listener: AudioListener; - onstatechange: (this: AudioContext, ev: Event) => any; + onstatechange: ((this: AudioContext, ev: Event) => any) | null; readonly sampleRate: number; readonly state: AudioContextState; close(): Promise; @@ -1406,10 +1935,15 @@ declare var AudioDestinationNode: { }; interface AudioListener { + /** @deprecated */ dopplerFactor: number; + /** @deprecated */ speedOfSound: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -1427,9 +1961,13 @@ interface AudioNode extends EventTarget { 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; + disconnect(): void; + disconnect(output: number): void; + disconnect(destination: AudioNode): void; + disconnect(destination: AudioNode, output: number): void; + disconnect(destination: AudioNode, output: number, input: number): void; + disconnect(destination: AudioParam): void; + disconnect(destination: AudioParam, output: number): void; } declare var AudioNode: { @@ -1440,12 +1978,12 @@ declare var AudioNode: { interface AudioParam { readonly defaultValue: number; value: number; - cancelScheduledValues(startTime: number): AudioParam; + cancelScheduledValues(cancelTime: 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; + setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam; } declare var AudioParam: { @@ -1486,9 +2024,9 @@ interface AudioTrackListEventMap { 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; + onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: AudioTrackList, ev: Event) => any) | null; + onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -1521,11 +2059,33 @@ declare var BeforeUnloadEvent: { new(): BeforeUnloadEvent; }; +interface BhxBrowser { + readonly lastError: DOMException; + checkMatchesGlobExpression(pattern: string, value: string): boolean; + checkMatchesUriExpression(pattern: string, value: string): boolean; + clearLastError(): void; + currentWindowId(): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + getThisAddress(): any; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericListenerHandler(eventHandler: Function): void; + setLastError(parameters: string): void; + webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void; +} + +declare var BhxBrowser: { + prototype: BhxBrowser; + new(): BhxBrowser; +}; + interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; - readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1548,113 +2108,50 @@ declare var 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; +interface BlobPropertyBag { + endings?: string; + type?: string; } -declare var Cache: { - prototype: Cache; - new(): Cache; +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + close(): void; + postMessage(message: any): 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 CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): Promise; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; } -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -}; - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; +interface ByteLengthQueuingStrategy { + highWaterMark: number; + size(chunk?: any): number; } -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; +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -1665,190 +2162,8 @@ declare var 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 { + escape(value: string): string; supports(property: string, value?: string): boolean; } declare var CSS: CSS; @@ -1908,7 +2223,7 @@ interface CSSKeyframesRule extends CSSRule { name: string; appendRule(rule: string): void; deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; + findRule(rule: string): CSSKeyframeRule | null; } declare var CSSKeyframesRule: { @@ -1949,14 +2264,14 @@ declare var CSSPageRule: { interface CSSRule { cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; + readonly parentRule: CSSRule | null; + readonly parentStyleSheet: CSSStyleSheet | null; 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 KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1972,8 +2287,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAME_RULE: number; readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1985,7 +2300,7 @@ declare var CSSRule: { interface CSSRuleList { readonly length: number; - item(index: number): CSSRule; + item(index: number): CSSRule | null; [index: number]: CSSRule; } @@ -1997,8 +2312,8 @@ declare var CSSRuleList: { interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignmentBaseline: string | null; alignSelf: string | null; + alignmentBaseline: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -2074,9 +2389,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; - columns: string | null; columnSpan: string | null; columnWidth: any; + columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -2110,11 +2425,32 @@ interface CSSStyleDeclaration { fontStyle: string | null; fontVariant: string | null; fontWeight: string | null; + gap: string | null; glyphOrientationHorizontal: string | null; glyphOrientationVertical: string | null; + grid: string | null; + gridArea: string | null; + gridAutoColumns: string | null; + gridAutoFlow: string | null; + gridAutoRows: string | null; + gridColumn: string | null; + gridColumnEnd: string | null; + gridColumnGap: string | null; + gridColumnStart: string | null; + gridGap: string | null; + gridRow: string | null; + gridRowEnd: string | null; + gridRowGap: string | null; + gridRowStart: string | null; + gridTemplate: string | null; + gridTemplateAreas: string | null; + gridTemplateColumns: string | null; + gridTemplateRows: string | null; height: string | null; imeMode: string | null; justifyContent: string | null; + justifyItems: string | null; + justifySelf: string | null; kerning: string | null; layoutGrid: string | null; layoutGridChar: string | null; @@ -2141,29 +2477,30 @@ interface CSSStyleDeclaration { markerMid: string | null; markerStart: string | null; mask: string | null; + maskImage: 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; + msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumns: string | null; msGridColumnSpan: any; + msGridColumns: string | null; msGridRow: any; msGridRowAlign: string | null; - msGridRows: string | null; msGridRowSpan: any; + msGridRows: string | null; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -2192,6 +2529,8 @@ interface CSSStyleDeclaration { msWrapFlow: string; msWrapMargin: any; msWrapThrough: string; + objectFit: string | null; + objectPosition: string | null; opacity: string | null; order: string | null; orphans: string | null; @@ -2212,13 +2551,16 @@ interface CSSStyleDeclaration { pageBreakBefore: string | null; pageBreakInside: string | null; readonly parentRule: CSSRule; + penAction: string | null; perspective: string | null; perspectiveOrigin: string | null; pointerEvents: string | null; position: string | null; quotes: string | null; + resize: string | null; right: string | null; rotate: string | null; + rowGap: string | null; rubyAlign: string | null; rubyOverhang: string | null; rubyPosition: string | null; @@ -2237,6 +2579,7 @@ interface CSSStyleDeclaration { textAlign: string | null; textAlignLast: string | null; textAnchor: string | null; + textCombineUpright: string | null; textDecoration: string | null; textIndent: string | null; textJustify: string | null; @@ -2258,6 +2601,7 @@ interface CSSStyleDeclaration { transitionTimingFunction: string | null; translate: string | null; unicodeBidi: string | null; + userSelect: string | null; verticalAlign: string | null; visibility: string | null; webkitAlignContent: string | null; @@ -2299,9 +2643,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; - webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; + webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2340,13 +2684,11 @@ interface CSSStyleDeclaration { 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; + setProperty(propertyName: string, value: string | null, priority?: string | null): void; [index: number]: string; } @@ -2356,7 +2698,6 @@ declare var CSSStyleDeclaration: { }; interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; selectorText: string; readonly style: CSSStyleDeclaration; } @@ -2368,21 +2709,32 @@ declare var CSSStyleRule: { interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; + /** @deprecated */ cssText: string; + /** @deprecated */ readonly id: string; + /** @deprecated */ readonly imports: StyleSheetList; + /** @deprecated */ readonly isAlternate: boolean; + /** @deprecated */ readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; + readonly ownerRule: CSSRule | null; + /** @deprecated */ readonly owningElement: Element; - readonly pages: StyleSheetPageList; + /** @deprecated */ + readonly pages: any; + /** @deprecated */ readonly readOnly: boolean; readonly rules: CSSRuleList; + /** @deprecated */ addImport(bstrURL: string, lIndex?: number): number; + /** @deprecated */ 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; + /** @deprecated */ removeImport(lIndex: number): void; removeRule(lIndex: number): void; } @@ -2400,6 +2752,380 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; +interface Cache { + add(request: Request | string): Promise; + addAll(requests: (Request | string)[]): Promise; + delete(request: Request | string, options?: CacheQueryOptions): Promise; + keys(request?: Request | string, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + matchAll(request?: Request | string, options?: CacheQueryOptions): Promise; + put(request: Request | string, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface Canvas2DContextAttributes { + alpha?: boolean; + storage?: boolean; + willReadFrequently?: boolean; + [attribute: string]: boolean | string | undefined; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +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; + arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: 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 CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends 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; + mozImageSmoothingEnabled: boolean; + msFillRule: CanvasFillRule; + oImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + webkitImageSmoothingEnabled: 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; + drawFocusIfNeeded(path: Path2D, 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; + isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(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 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 ChildNode { + remove(): void; +} + +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 ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(data?: string): 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 ComputedTimingProperties { + activeDuration: number; + currentIteration: number | null; + endTime: number; + localTime: number | null; + progress: number | null; +} + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: 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; + markTimeline(label?: string): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ContentScriptGlobalScope extends EventTarget { + readonly msContentScript: ExtensionScriptApis; + readonly window: Window; +} + +declare var ContentScriptGlobalScope: { + prototype: ContentScriptGlobalScope; + new(): ContentScriptGlobalScope; +}; + +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 CountQueuingStrategy { + highWaterMark: number; + size(): number; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(strategy: QueuingStrategy): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null; +} + +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 CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + whenDefined(name: string): PromiseLike; +} + interface CustomEvent extends Event { readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; @@ -2410,6 +3136,194 @@ declare var CustomEvent: { new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; +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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +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 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 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(...tokens: string[]): void; + contains(token: string): boolean; + item(index: number): string | null; + remove(...tokens: string[]): void; + replace(oldToken: string, newToken: string): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DataCue extends TextTrackCue { data: ArrayBuffer; addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -2456,10 +3370,11 @@ declare var DataTransferItem: { interface DataTransferItemList { readonly length: number; add(data: File): DataTransferItem | null; + add(data: string, type: string): DataTransferItem | null; clear(): void; item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: DataTransferItem; + [name: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -2546,11 +3461,30 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; }; +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforedeactivate": UIEvent; + "activate": Event; + "beforeactivate": Event; + "beforedeactivate": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -2558,7 +3492,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "click": MouseEvent; "contextmenu": PointerEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -2568,7 +3502,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "fullscreenchange": Event; @@ -2588,25 +3522,25 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "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; + "MSContentZoom": Event; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSManipulationStateChanged": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "mssitemodejumplistitemremoved": Event; + "msthumbnailclick": Event; "pause": Event; "play": Event; "playing": Event; @@ -2637,7 +3571,15 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "webkitfullscreenerror": Event; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { +interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent { + /** + * 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; /** * Gets the object that has the focus when the parent document has focus. */ @@ -2653,11 +3595,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * 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; + readonly anchors: HTMLCollectionOf; /** * Retrieves a collection of all applet objects in the document. */ - applets: HTMLCollectionOf; + readonly applets: HTMLCollectionOf; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ @@ -2693,7 +3635,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Gets a reference to the root node of the document. */ - documentElement: HTMLElement; + readonly documentElement: HTMLElement; /** * Sets or gets the security domain of the document. */ @@ -2701,7 +3643,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all embed objects in the document. */ - embeds: HTMLCollectionOf; + readonly embeds: HTMLCollectionOf; /** * Sets or gets the foreground (text) color of the document. */ @@ -2709,7 +3651,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of all form objects in the document. */ - forms: HTMLCollectionOf; + readonly forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; @@ -2717,7 +3659,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of img objects in the document. */ - images: HTMLCollectionOf; + readonly images: HTMLCollectionOf; /** * Gets the implementation object of the current document. */ @@ -2737,322 +3679,323 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. */ - links: HTMLCollectionOf; + readonly links: HTMLCollectionOf; /** * Contains information about the current URL. */ - readonly location: Location; - msCapsLockWarningOff: boolean; + location: Location; msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; /** * Fires when the user aborts the download. * @param ev The event. */ - onabort: (this: Document, ev: UIEvent) => any; + onabort: ((this: Document, ev: UIEvent) => any) | null; /** * Fires when the object is set as the active element. * @param ev The event. */ - onactivate: (this: Document, ev: UIEvent) => any; + onactivate: ((this: Document, ev: Event) => any) | null; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ - onbeforeactivate: (this: Document, ev: UIEvent) => any; + onbeforeactivate: ((this: Document, ev: Event) => any) | null; /** * 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; + onbeforedeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ - onblur: (this: Document, ev: FocusEvent) => any; + onblur: ((this: Document, ev: FocusEvent) => any) | null; /** * 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; + oncanplay: ((this: Document, ev: Event) => any) | null; + oncanplaythrough: ((this: Document, ev: Event) => any) | null; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ - onchange: (this: Document, ev: Event) => any; + onchange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ - onclick: (this: Document, ev: MouseEvent) => any; + onclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ - ondblclick: (this: Document, ev: MouseEvent) => any; + ondblclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + ondeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ - ondrag: (this: Document, ev: DragEvent) => any; + ondrag: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragend: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragenter: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragleave: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragover: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragstart: ((this: Document, ev: DragEvent) => any) | null; + ondrop: ((this: Document, ev: DragEvent) => any) | null; /** * Occurs when the duration attribute is updated. * @param ev The event. */ - ondurationchange: (this: Document, ev: Event) => any; + ondurationchange: ((this: Document, ev: Event) => any) | null; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ - onemptied: (this: Document, ev: Event) => any; + onemptied: ((this: Document, ev: Event) => any) | null; /** * Occurs when the end of playback is reached. * @param ev The event */ - onended: (this: Document, ev: MediaStreamErrorEvent) => any; + onended: ((this: Document, ev: Event) => any) | null; /** * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (this: Document, ev: ErrorEvent) => any; + onerror: ((this: Document, ev: ErrorEvent) => any) | null; /** * 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; + onfocus: ((this: Document, ev: FocusEvent) => any) | null; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + oninput: ((this: Document, ev: Event) => any) | null; + oninvalid: ((this: Document, ev: Event) => any) | null; /** * Fires when the user presses a key. * @param ev The keyboard event */ - onkeydown: (this: Document, ev: KeyboardEvent) => any; + onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ - onkeypress: (this: Document, ev: KeyboardEvent) => any; + onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user releases a key. * @param ev The keyboard event */ - onkeyup: (this: Document, ev: KeyboardEvent) => any; + onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires immediately after the browser loads the object. * @param ev The event. */ - onload: (this: Document, ev: Event) => any; + onload: ((this: Document, ev: Event) => any) | null; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ - onloadeddata: (this: Document, ev: Event) => any; + onloadeddata: ((this: Document, ev: Event) => any) | null; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ - onloadedmetadata: (this: Document, ev: Event) => any; + onloadedmetadata: ((this: Document, ev: Event) => any) | null; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ - onloadstart: (this: Document, ev: Event) => any; + onloadstart: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ - onmousedown: (this: Document, ev: MouseEvent) => any; + onmousedown: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ - onmousemove: (this: Document, ev: MouseEvent) => any; + onmousemove: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseout: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ - onmouseover: (this: Document, ev: MouseEvent) => any; + onmouseover: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseup: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmousewheel: ((this: Document, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: Document, ev: Event) => any) | null; + onmsgesturechange: ((this: Document, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null; + onmsgestureend: ((this: Document, ev: Event) => any) | null; + onmsgesturehold: ((this: Document, ev: Event) => any) | null; + onmsgesturestart: ((this: Document, ev: Event) => any) | null; + onmsgesturetap: ((this: Document, ev: Event) => any) | null; + onmsinertiastart: ((this: Document, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null; + onmspointercancel: ((this: Document, ev: Event) => any) | null; + onmspointerdown: ((this: Document, ev: Event) => any) | null; + onmspointerenter: ((this: Document, ev: Event) => any) | null; + onmspointerleave: ((this: Document, ev: Event) => any) | null; + onmspointermove: ((this: Document, ev: Event) => any) | null; + onmspointerout: ((this: Document, ev: Event) => any) | null; + onmspointerover: ((this: Document, ev: Event) => any) | null; + onmspointerup: ((this: Document, ev: Event) => any) | null; /** * 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; + onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null; /** * 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; + onmsthumbnailclick: ((this: Document, ev: Event) => any) | null; /** * Occurs when playback is paused. * @param ev The event. */ - onpause: (this: Document, ev: Event) => any; + onpause: ((this: Document, ev: Event) => any) | null; /** * Occurs when the play method is requested. * @param ev The event. */ - onplay: (this: Document, ev: Event) => any; + onplay: ((this: Document, ev: Event) => any) | null; /** * 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; + onplaying: ((this: Document, ev: Event) => any) | null; + onpointerlockchange: ((this: Document, ev: Event) => any) | null; + onpointerlockerror: ((this: Document, ev: Event) => any) | null; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ - onprogress: (this: Document, ev: ProgressEvent) => any; + onprogress: ((this: Document, ev: ProgressEvent) => any) | null; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ - onratechange: (this: Document, ev: Event) => any; + onratechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the state of the object has changed. * @param ev The event */ - onreadystatechange: (this: Document, ev: Event) => any; + onreadystatechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user resets a form. * @param ev The event. */ - onreset: (this: Document, ev: Event) => any; + onreset: ((this: Document, ev: Event) => any) | null; /** * 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; + onscroll: ((this: Document, ev: UIEvent) => any) | null; /** * Occurs when the seek operation ends. * @param ev The event. */ - onseeked: (this: Document, ev: Event) => any; + onseeked: ((this: Document, ev: Event) => any) | null; /** * Occurs when the current playback position is moved. * @param ev The event. */ - onseeking: (this: Document, ev: Event) => any; + onseeking: ((this: Document, ev: Event) => any) | null; /** * Fires when the current selection changes. * @param ev The event. */ - onselect: (this: Document, ev: UIEvent) => any; + onselect: ((this: Document, ev: UIEvent) => any) | null; /** * 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; + onselectionchange: ((this: Document, ev: Event) => any) | null; + onselectstart: ((this: Document, ev: Event) => any) | null; /** * Occurs when the download has stopped. * @param ev The event. */ - onstalled: (this: Document, ev: Event) => any; + onstalled: ((this: Document, ev: Event) => any) | null; /** * 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; + onstop: ((this: Document, ev: Event) => any) | null; + onsubmit: ((this: Document, ev: Event) => any) | null; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ - onsuspend: (this: Document, ev: Event) => any; + onsuspend: ((this: Document, ev: Event) => any) | null; /** * 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; + ontimeupdate: ((this: Document, ev: Event) => any) | null; + ontouchcancel: ((this: Document, ev: TouchEvent) => any) | null; + ontouchend: ((this: Document, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Document, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Document, ev: TouchEvent) => any) | null; + onvisibilitychange: (this: Document, ev: Event) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ - onvolumechange: (this: Document, ev: Event) => any; + onvolumechange: ((this: Document, ev: Event) => any) | null; /** * 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; + onwaiting: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null; + readonly plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** * Retrieves a value that indicates the current state of the object. @@ -3069,7 +4012,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all script objects in the document. */ - scripts: HTMLCollectionOf; + readonly 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. @@ -3079,14 +4022,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * 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. @@ -3102,7 +4037,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string | null; - onvisibilitychange: (this: Document, ev: Event) => any; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; @@ -3198,6 +4132,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver: Node): XPathNSResolver; /** * 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. @@ -3206,7 +4141,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @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. @@ -3233,6 +4167,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; + elementsFromPoint(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. @@ -3251,6 +4186,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Causes the element to receive the focus and executes the code specified by the onfocus event. */ + /** @deprecated */ focus(): void; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. @@ -3323,10 +4259,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ queryCommandValue(commandId: string): string; releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** @@ -3350,7 +4282,79 @@ declare var Document: { new(): Document; }; -interface DocumentFragment extends Node, NodeSelector, ParentNode { +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + 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: "MSDCCEvent"): MSDCCEvent; + createEvent(eventInterface: "MSDSHEvent"): MSDSHEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + 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: "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: "PromiseRejectionEvent"): PromiseRejectionEvent; + 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: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + 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: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DocumentFragment extends Node, ParentNode { getElementById(elementId: string): HTMLElement | null; } @@ -3359,6 +4363,14 @@ declare var DocumentFragment: { new(): DocumentFragment; }; +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly styleSheets: StyleSheetList; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + getSelection(): Selection | null; +} + interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; readonly internalSubset: string | null; @@ -3373,149 +4385,6 @@ declare var 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; @@ -3541,209 +4410,23 @@ declare var 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 EXT_blend_minmax { + readonly MAX_EXT: number; + readonly MIN_EXT: number; } -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 | null; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB_EXT: number; +} + +interface EXT_shader_texture_lod { +} interface EXT_texture_filter_anisotropic { readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; @@ -3757,14 +4440,262 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; }; +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": Event; + "command": Event; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSGotPointerCapture": Event; + "MSInertiaStart": Event; + "MSLostPointerCapture": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode { + readonly assignedSlot: HTMLSlotElement | null; + readonly attributes: NamedNodeMap; + 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) | null; + oncommand: ((this: Element, ev: Event) => any) | null; + ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onmsgesturechange: ((this: Element, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null; + onmsgestureend: ((this: Element, ev: Event) => any) | null; + onmsgesturehold: ((this: Element, ev: Event) => any) | null; + onmsgesturestart: ((this: Element, ev: Event) => any) | null; + onmsgesturetap: ((this: Element, ev: Event) => any) | null; + onmsgotpointercapture: ((this: Element, ev: Event) => any) | null; + onmsinertiastart: ((this: Element, ev: Event) => any) | null; + onmslostpointercapture: ((this: Element, ev: Event) => any) | null; + onmspointercancel: ((this: Element, ev: Event) => any) | null; + onmspointerdown: ((this: Element, ev: Event) => any) | null; + onmspointerenter: ((this: Element, ev: Event) => any) | null; + onmspointerleave: ((this: Element, ev: Event) => any) | null; + onmspointermove: ((this: Element, ev: Event) => any) | null; + onmspointerout: ((this: Element, ev: Event) => any) | null; + onmspointerover: ((this: Element, ev: Event) => any) | null; + onmspointerup: ((this: Element, ev: Event) => any) | null; + ontouchcancel: ((this: Element, ev: TouchEvent) => any) | null; + ontouchend: ((this: Element, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Element, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Element, ev: TouchEvent) => any) | null; + onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; + outerHTML: string; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly shadowRoot: ShadowRoot | null; + slot: string; + readonly tagName: string; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + getAttribute(qualifiedName: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + getElementsByClassName(classNames: string): NodeListOf; + 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; + hasAttributes(): boolean; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + matches(selectors: string): boolean; + msGetRegionContent(): any; + 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; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + setAttribute(qualifiedName: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): 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: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + readonly style: CSSStyleDeclaration; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ElementDefinitionOptions { + extends: string; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly nextElementSibling: Element | null; + readonly previousElementSibling: Element | null; +} + +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(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly scoped: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget | null; + readonly timeStamp: number; + readonly type: string; + deepPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(typeArg: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; - fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; genericSynchronousFunction(functionId: number, parameters?: string): string; + genericWebRuntimeCallout(to: any, from: any, payload: string): void; getExtensionId(): string; - registerGenericFunctionCallbackHandler(callbackHandler: any): void; - registerGenericPersistentCallbackHandler(callbackHandler: any): void; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericPersistentCallbackHandler(callbackHandler: Function): void; + registerWebRuntimeCallbackHandler(handler: Function): any; } declare var ExtensionScriptApis: { @@ -3781,10 +4712,11 @@ declare var External: { }; interface File extends Blob { + readonly lastModified: number; + /** @deprecated */ readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; - readonly lastModified: number; } declare var File: { @@ -3794,7 +4726,7 @@ declare var File: { interface FileList { readonly length: number; - item(index: number): File; + item(index: number): File | null; [index: number]: File; } @@ -3803,21 +4735,49 @@ declare var FileList: { new(): FileList; }; -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; 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; + readAsText(blob: Blob, label?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[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: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface FocusEvent extends UIEvent { @@ -3855,7 +4815,8 @@ interface FormData { declare var FormData: { prototype: FormData; - new (form?: HTMLFormElement): FormData; + new(): FormData; + new(form: HTMLFormElement): FormData; }; interface GainNode extends AudioNode { @@ -3871,9 +4832,13 @@ interface Gamepad { readonly axes: number[]; readonly buttons: GamepadButton[]; readonly connected: boolean; + readonly displayId: number; + readonly hand: GamepadHand; + readonly hapticActuators: GamepadHapticActuator[]; readonly id: string; readonly index: number; - readonly mapping: string; + readonly mapping: GamepadMappingType; + readonly pose: GamepadPose | null; readonly timestamp: number; } @@ -3884,6 +4849,7 @@ declare var Gamepad: { interface GamepadButton { readonly pressed: boolean; + readonly touched: boolean; readonly value: number; } @@ -3901,6 +4867,32 @@ declare var GamepadEvent: { new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; }; +interface GamepadHapticActuator { + readonly type: GamepadHapticActuatorType; + pulse(value: number, duration: number): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GamepadPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; +} + +declare var GamepadPose: { + prototype: GamepadPose; + new(): GamepadPose; +}; + interface Geolocation { clearWatch(watchId: number): void; getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; @@ -3912,45 +4904,41 @@ declare var Geolocation: { new(): Geolocation; }; -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; +interface GetSVGDocument { + getSVGDocument(): Document; } -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; +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; } -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; +interface GlobalEventHandlers { + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + 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; } -declare var History: { - prototype: History; - new(): History; -}; +interface GlobalFetch { + fetch(input?: Request | string, init?: RequestInit): Promise; +} interface HTMLAllCollection { readonly length: number; @@ -3964,55 +4952,30 @@ declare var HTMLAllCollection: { new(): HTMLAllCollection; }; -interface HTMLAnchorElement extends HTMLElement { +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + Methods: string; /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Sets or retrieves the coordinates of the object. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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. @@ -4021,14 +4984,12 @@ interface HTMLAnchorElement extends HTMLElement { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ 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. */ + /** @deprecated */ shape: string; /** * Sets or retrieves the window or frame at which to target content. @@ -4040,10 +5001,6 @@ interface HTMLAnchorElement extends HTMLElement { 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; @@ -4056,70 +5013,44 @@ declare var HTMLAnchorElement: { }; interface HTMLAppletElement extends HTMLElement { + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ 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. */ + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; /** * Sets or retrieves the shape of the object. */ + /** @deprecated */ 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; + /** @deprecated */ + object: string; + /** @deprecated */ vspace: number; - width: number; + /** @deprecated */ + width: string; 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; @@ -4131,7 +5062,7 @@ declare var HTMLAppletElement: { new(): HTMLAppletElement; }; -interface HTMLAreaElement extends HTMLElement { +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { /** * Sets or retrieves a text alternative to the graphic. */ @@ -4141,43 +5072,12 @@ interface HTMLAreaElement extends HTMLElement { */ 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. */ + /** @deprecated */ 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. */ @@ -4186,10 +5086,6 @@ interface HTMLAreaElement extends HTMLElement { * 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; @@ -4221,6 +5117,23 @@ declare var HTMLAudioElement: { new(): HTMLAudioElement; }; +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. + */ + /** @deprecated */ + 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 HTMLBaseElement extends HTMLElement { /** * Gets or sets the baseline URL on which relative links are based. @@ -4245,10 +5158,12 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ face: string; /** * Sets or retrieves the font size of the object. */ + /** @deprecated */ 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; @@ -4261,51 +5176,34 @@ declare var HTMLBaseFontElement: { new(): HTMLBaseFontElement; }; -interface HTMLBodyElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { + /** @deprecated */ + aLink: string; + /** @deprecated */ background: string; - bgColor: any; + /** @deprecated */ + bgColor: string; bgProperties: string; - link: any; + /** @deprecated */ + link: string; + /** @deprecated */ 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; + onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; + onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null; + /** @deprecated */ + text: string; + /** @deprecated */ + vLink: string; 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; @@ -4317,22 +5215,6 @@ declare var 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. @@ -4358,7 +5240,7 @@ interface HTMLButtonElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -4428,12 +5310,12 @@ interface HTMLCanvasElement extends HTMLElement { * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ msToBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; /** * 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; @@ -4469,6 +5351,26 @@ declare var HTMLCollection: { new(): HTMLCollection; }; +interface HTMLCollectionOf extends HTMLCollectionBase { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface HTMLDListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLDataElement extends HTMLElement { value: string; addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4483,7 +5385,7 @@ declare var HTMLDataElement: { }; interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; + readonly 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; @@ -4495,6 +5397,36 @@ declare var HTMLDataListElement: { new(): HTMLDataListElement; }; +interface HTMLDetailsElement extends HTMLElement { + open: boolean; + addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; + addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + interface HTMLDirectoryElement extends HTMLElement { compact: boolean; addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4512,6 +5444,7 @@ interface HTMLDivElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. @@ -4528,19 +5461,6 @@ declare var 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; @@ -4555,12 +5475,12 @@ declare var HTMLDocument: { interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforecopy": ClipboardEvent; - "beforecut": ClipboardEvent; - "beforedeactivate": UIEvent; - "beforepaste": ClipboardEvent; + "activate": Event; + "beforeactivate": Event; + "beforecopy": Event; + "beforecut": Event; + "beforedeactivate": Event; + "beforepaste": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -4571,7 +5491,7 @@ interface HTMLElementEventMap extends ElementEventMap { "cuechange": Event; "cut": ClipboardEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -4581,7 +5501,7 @@ interface HTMLElementEventMap extends ElementEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "input": Event; @@ -4601,8 +5521,8 @@ interface HTMLElementEventMap extends ElementEventMap { "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": WheelEvent; - "MSContentZoom": UIEvent; - "MSManipulationStateChanged": MSManipulationEvent; + "MSContentZoom": Event; + "MSManipulationStateChanged": Event; "paste": ClipboardEvent; "pause": Event; "play": Event; @@ -4623,9 +5543,8 @@ interface HTMLElementEventMap extends ElementEventMap { "waiting": Event; } -interface HTMLElement extends Element { +interface HTMLElement extends Element, ElementCSSInlineStyle { accessKey: string; - readonly children: HTMLCollection; contentEditable: string; readonly dataset: DOMStringMap; dir: string; @@ -4640,84 +5559,83 @@ interface HTMLElement extends Element { 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; + onabort: ((this: HTMLElement, ev: UIEvent) => any) | null; + onactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecut: ((this: HTMLElement, ev: Event) => any) | null; + onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null; + onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oncanplay: ((this: HTMLElement, ev: Event) => any) | null; + oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null; + onchange: ((this: HTMLElement, ev: Event) => any) | null; + onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null; + oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + oncuechange: ((this: HTMLElement, ev: Event) => any) | null; + oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + ondeactivate: ((this: HTMLElement, ev: Event) => any) | null; + ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondurationchange: ((this: HTMLElement, ev: Event) => any) | null; + onemptied: ((this: HTMLElement, ev: Event) => any) | null; + onended: ((this: HTMLElement, ev: Event) => any) | null; + onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null; + onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oninput: ((this: HTMLElement, ev: Event) => any) | null; + oninvalid: ((this: HTMLElement, ev: Event) => any) | null; + onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onload: ((this: HTMLElement, ev: Event) => any) | null; + onloadeddata: ((this: HTMLElement, ev: Event) => any) | null; + onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null; + onloadstart: ((this: HTMLElement, ev: Event) => any) | null; + onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null; + onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + onpause: ((this: HTMLElement, ev: Event) => any) | null; + onplay: ((this: HTMLElement, ev: Event) => any) | null; + onplaying: ((this: HTMLElement, ev: Event) => any) | null; + onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null; + onratechange: ((this: HTMLElement, ev: Event) => any) | null; + onreset: ((this: HTMLElement, ev: Event) => any) | null; + onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null; + onseeked: ((this: HTMLElement, ev: Event) => any) | null; + onseeking: ((this: HTMLElement, ev: Event) => any) | null; + onselect: ((this: HTMLElement, ev: UIEvent) => any) | null; + onselectstart: ((this: HTMLElement, ev: Event) => any) | null; + onstalled: ((this: HTMLElement, ev: Event) => any) | null; + onsubmit: ((this: HTMLElement, ev: Event) => any) | null; + onsuspend: ((this: HTMLElement, ev: Event) => any) | null; + ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null; + onvolumechange: ((this: HTMLElement, ev: Event) => any) | null; + onwaiting: ((this: HTMLElement, ev: Event) => any) | null; outerText: string; spellcheck: boolean; - readonly style: CSSStyleDeclaration; tabIndex: number; title: string; + animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; blur(): void; click(): void; dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; 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; @@ -4754,6 +5672,7 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * Retrieves the palette used for the embedded document. @@ -4834,6 +5753,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ 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; @@ -4914,6 +5834,7 @@ interface HTMLFormElement extends HTMLElement { * Retrieves a form object or an object from an elements collection. */ namedItem(name: string): any; + reportValidity(): boolean; /** * Fires when the user resets a form. */ @@ -4922,8 +5843,6 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ 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; @@ -4952,14 +5871,17 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + /** @deprecated */ + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + /** @deprecated */ + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. @@ -4972,30 +5894,37 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a URI to a long description of the object. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ marginWidth: string; /** * Sets or retrieves the frame name. */ + /** @deprecated */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ + /** @deprecated */ noResize: boolean; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ + /** @deprecated */ src: string; /** * Sets or retrieves the width of the object. @@ -5012,64 +5941,29 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; }; -interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { /** * Sets or retrieves the frame widths of the object. */ + /** @deprecated */ 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; + onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null; + onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null; /** * Sets or retrieves the frame heights of the object. */ + /** @deprecated */ 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; @@ -5082,7 +5976,35 @@ declare var HTMLFrameSetElement: { new(): HTMLFrameSetElement; }; +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + /** @deprecated */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + 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 HTMLHeadElement extends HTMLElement { + /** @deprecated */ 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; @@ -5099,6 +6021,7 @@ interface HTMLHeadingElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ 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; @@ -5111,34 +6034,11 @@ declare var 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. */ + /** @deprecated */ 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; @@ -5151,6 +6051,19 @@ declare var HTMLHtmlElement: { new(): HTMLHtmlElement; }; +interface HTMLHyperlinkElementUtils { + hash: string; + host: string; + hostname: string; + href: string; + origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + toString(): string; +} + interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; } @@ -5159,78 +6072,64 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ 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; + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ 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. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ 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; + readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** - * Sets or retrieves the vertical margin for the object. + * Sets or retrives the content of the page that is to contain. */ - vspace: number; + srcdoc: string; /** * 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; @@ -5246,6 +6145,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5254,6 +6154,7 @@ interface HTMLImageElement extends HTMLElement { /** * Specifies the properties of a border drawn around an object. */ + /** @deprecated */ border: string; /** * Retrieves whether the object is fully loaded. @@ -5261,6 +6162,7 @@ interface HTMLImageElement extends HTMLElement { readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; /** * Sets or retrieves the height of the object. */ @@ -5268,6 +6170,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ hspace: number; /** * Sets or retrieves whether the image is a server-side image map. @@ -5277,6 +6180,7 @@ interface HTMLImageElement extends HTMLElement { * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. */ longDesc: string; + /** @deprecated */ lowsrc: string; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5294,6 +6198,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * The original height of the image resource before sizing. @@ -5316,6 +6221,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the vertical margin for the object. */ + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -5343,6 +6249,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5356,18 +6263,10 @@ interface HTMLInputElement 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 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. */ @@ -5400,7 +6299,7 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -5408,16 +6307,12 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + height: number; indeterminate: boolean; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ - readonly list: HTMLElement; + readonly list: HTMLElement | null; /** * 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. */ @@ -5430,6 +6325,7 @@ interface HTMLInputElement extends HTMLElement { * 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; + minLength: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ @@ -5451,21 +6347,20 @@ interface HTMLInputElement extends HTMLElement { * When present, marks an element that can't be submitted without a value. */ required: boolean; - selectionDirection: string; + selectionDirection: string | null; /** * Gets or sets the end position or offset of a text selection. */ - selectionEnd: number; + selectionEnd: number | null; /** * Gets or sets the starting position or offset of a text selection. */ - selectionStart: number; + selectionStart: number | null; 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. */ @@ -5477,6 +6372,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ + /** @deprecated */ 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. @@ -5490,25 +6386,20 @@ interface HTMLInputElement extends HTMLElement { * Returns the value of the data at the cursor's current position. */ value: string; - valueAsDate: Date; + valueAsDate: any; /** * 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; + width: number; /** * 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. */ @@ -5550,48 +6441,8 @@ declare var 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 { + /** @deprecated */ type: string; /** * Sets or retrieves the value of a list item. @@ -5608,11 +6459,56 @@ declare var HTMLLIElement: { new(): HTMLLIElement; }; +interface HTMLLabelElement extends HTMLElement { + readonly control: HTMLInputElement | null; + /** + * 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; + 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. + */ + /** @deprecated */ + 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 HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; + crossOrigin: string | null; + /** @deprecated */ disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. @@ -5622,6 +6518,8 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { * Sets or retrieves the language code of the object. */ hreflang: string; + import?: Document; + integrity: string; /** * Sets or retrieves the media type. */ @@ -5633,17 +6531,17 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ rev: string; /** * Sets or retrieves the window or frame at which to target content. */ + /** @deprecated */ 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; @@ -5655,6 +6553,18 @@ declare var HTMLLinkElement: { new(): HTMLLinkElement; }; +interface HTMLMainElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. @@ -5682,21 +6592,37 @@ interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { } interface HTMLMarqueeElement extends HTMLElement { + /** @deprecated */ behavior: string; - bgColor: any; + /** @deprecated */ + bgColor: string; + /** @deprecated */ direction: string; + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; + /** @deprecated */ loop: number; - onbounce: (this: HTMLMarqueeElement, ev: Event) => any; - onfinish: (this: HTMLMarqueeElement, ev: Event) => any; - onstart: (this: HTMLMarqueeElement, ev: Event) => any; + /** @deprecated */ + onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ scrollAmount: number; + /** @deprecated */ scrollDelay: number; + /** @deprecated */ trueSpeed: boolean; + /** @deprecated */ vspace: number; + /** @deprecated */ width: string; + /** @deprecated */ start(): void; + /** @deprecated */ 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; @@ -5711,7 +6637,7 @@ declare var HTMLMarqueeElement: { interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; - "msneedkey": MSMediaKeyNeededEvent; + "msneedkey": Event; } interface HTMLMediaElement extends HTMLElement { @@ -5756,7 +6682,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Returns an object representing the current error state of the audio or video element. */ - readonly error: MediaError; + readonly error: MediaError | null; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ @@ -5774,6 +6700,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ + /** @deprecated */ readonly msKeys: MSMediaKeys; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5803,8 +6730,9 @@ interface HTMLMediaElement extends HTMLElement { * Gets the current network activity for the element. */ readonly networkState: number; - onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null; + /** @deprecated */ + onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null; /** * Gets a flag that specifies whether playback is paused. */ @@ -5821,7 +6749,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: number; + readonly readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -5834,18 +6762,18 @@ interface HTMLMediaElement extends HTMLElement { * The address or URL of the a media resource that is to be considered. */ src: string; - srcObject: MediaStream | null; + srcObject: MediaStream | MediaSource | Blob | 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; + addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack; /** * Returns a string that specifies whether the client can play a given media resource type. */ - canPlayType(type: string): string; + canPlayType(type: string): CanPlayTypeResult; /** * Resets the audio or video object and loads a new media resource. */ @@ -5859,6 +6787,7 @@ interface HTMLMediaElement extends HTMLElement { * Inserts the specified audio effect into media pipeline. */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + /** @deprecated */ msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Specifies the media protection manager for a given media pipeline. @@ -5903,6 +6832,7 @@ declare var HTMLMediaElement: { }; interface HTMLMenuElement extends HTMLElement { + /** @deprecated */ compact: boolean; type: string; addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -5920,6 +6850,7 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. @@ -5936,10 +6867,12 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ + /** @deprecated */ scheme: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ + /** @deprecated */ 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; @@ -5990,41 +6923,63 @@ declare var HTMLModElement: { new(): HTMLModElement; }; +interface HTMLOListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLObjectElement extends HTMLElement, GetSVGDocument { - align: 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; + /** @deprecated */ + align: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ border: string; /** * Sets or retrieves the URL of the file containing the compiled Java class. */ + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ + /** @deprecated */ codeType: string; /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + readonly contentDocument: Document | null; /** * Sets or retrieves the URL that references the data of the object. */ data: string; + /** @deprecated */ declare: boolean; /** * Retrieves a reference to the form that the object is embedded in. @@ -6034,6 +6989,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the height of the object. */ height: string; + /** @deprecated */ hspace: number; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -6059,11 +7015,13 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a message to be displayed while an object is loading. */ + /** @deprecated */ standby: string; /** * Sets or retrieves the MIME type of the object. */ type: string; + typemustmatch: boolean; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ @@ -6076,6 +7034,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -6085,7 +7044,6 @@ 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. */ @@ -6106,54 +7064,16 @@ declare var 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; @@ -6209,7 +7129,7 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; remove(index: number): void; } @@ -6221,7 +7141,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; readonly form: HTMLFormElement | null; - readonly htmlFor: DOMSettableTokenList; + readonly htmlFor: DOMTokenList; name: string; readonly type: string; readonly validationMessage: string; @@ -6246,6 +7166,7 @@ interface HTMLParagraphElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -6267,6 +7188,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the content type of the resource designated by the value attribute. */ + /** @deprecated */ type: string; /** * Sets or retrieves the value of an input parameter for an element. @@ -6275,6 +7197,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the data type of the value attribute. */ + /** @deprecated */ 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; @@ -6303,6 +7226,7 @@ interface HTMLPreElement extends HTMLElement { /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ + /** @deprecated */ 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; @@ -6373,11 +7297,15 @@ interface HTMLScriptElement extends HTMLElement { /** * Sets or retrieves the event for which the script is written. */ + /** @deprecated */ event: string; /** * Sets or retrieves the object that is bound to the event script. */ + /** @deprecated */ htmlFor: string; + integrity: string; + noModule: boolean; /** * Retrieves the URL to an external file that contains the source code or data. */ @@ -6390,7 +7318,6 @@ interface HTMLScriptElement extends HTMLElement { * 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; @@ -6433,7 +7360,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the index of the selected option in a select object. */ selectedIndex: number; - selectedOptions: HTMLCollectionOf; + readonly selectedOptions: HTMLCollectionOf; /** * Sets or retrieves the number of rows in the list box. */ @@ -6463,7 +7390,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6473,7 +7400,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + item(name?: any, index?: any): Element | null; /** * 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. @@ -6501,11 +7428,21 @@ declare var HTMLSelectElement: { new(): HTMLSelectElement; }; +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; + addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; + /** @deprecated */ msKeySystem: string; sizes: string; /** @@ -6541,6 +7478,7 @@ declare var HTMLSpanElement: { }; interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** @deprecated */ disabled: boolean; /** * Sets or retrieves the media type. @@ -6561,15 +7499,24 @@ declare var HTMLStyleElement: { new(): HTMLStyleElement; }; +interface HTMLSummaryElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. */ + /** @deprecated */ 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; @@ -6581,7 +7528,7 @@ declare var HTMLTableCaptionElement: { new(): HTMLTableCaptionElement; }; -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableCellElement extends HTMLElement { /** * Sets or retrieves abbreviated text for the object. */ @@ -6589,16 +7536,23 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. */ + /** @deprecated */ axis: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves the position of the object in the cells collection of a row. */ readonly cellIndex: number; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number columns in the table that the object should span. */ @@ -6610,10 +7564,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves the height of the object. */ - height: any; + /** @deprecated */ + height: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ + /** @deprecated */ noWrap: boolean; /** * Sets or retrieves how many rows in a table the cell should span. @@ -6623,9 +7579,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ 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; @@ -6638,19 +7597,27 @@ declare var HTMLTableCellElement: { new(): HTMLTableCellElement; }; -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableColElement extends HTMLElement { /** * Sets or retrieves the alignment of the object relative to the display or table. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of columns in the group. */ span: number; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ - width: any; + /** @deprecated */ + width: string; 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; @@ -6678,67 +7645,64 @@ interface HTMLTableElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; /** * Retrieves the caption object of a table. */ - caption: HTMLTableCaptionElement; + caption: HTMLTableCaptionElement | null; /** * Sets or retrieves the amount of space between the border of the cell and the content of the cell. */ + /** @deprecated */ cellPadding: string; /** * Sets or retrieves the amount of space between cells in a table. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + readonly rows: HTMLCollectionOf; /** * Sets or retrieves which dividing lines (inner borders) are displayed. */ + /** @deprecated */ rules: string; /** * Sets or retrieves a description and/or structure of the object. */ + /** @deprecated */ summary: string; /** * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. */ - tBodies: HTMLCollectionOf; + readonly tBodies: HTMLCollectionOf; /** * Retrieves the tFoot object of the table. */ - tFoot: HTMLTableSectionElement; + tFoot: HTMLTableSectionElement | null; /** * Retrieves the tHead object of the table. */ - tHead: HTMLTableSectionElement; + tHead: HTMLTableSectionElement | null; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ width: string; /** * Creates an empty caption element in the table. @@ -6790,9 +7754,6 @@ declare var 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; @@ -6805,20 +7766,22 @@ declare var HTMLTableHeaderCellElement: { new(): HTMLTableHeaderCellElement; }; -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableRowElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves a collection of all cells in the table row. */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; + readonly cells: HTMLCollectionOf; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Retrieves the position of the object in the rows collection for the table. */ @@ -6827,6 +7790,8 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Retrieves the position of the object in the collection. */ readonly sectionRowIndex: number; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6848,15 +7813,22 @@ declare var HTMLTableRowElement: { new(): HTMLTableRowElement; }; -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableSectionElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of horizontal rows contained in the object. */ - rows: HTMLCollectionOf; + readonly rows: HTMLCollectionOf; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6913,6 +7885,7 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; + minLength: number; /** * Sets or retrieves the name of the object. */ @@ -6941,10 +7914,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -6969,7 +7938,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -7058,7 +8026,9 @@ declare var HTMLTrackElement: { }; interface HTMLUListElement extends HTMLElement { + /** @deprecated */ compact: boolean; + /** @deprecated */ 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; @@ -7100,9 +8070,9 @@ interface HTMLVideoElement extends HTMLMediaElement { msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; - onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; /** * 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. */ @@ -7125,10 +8095,10 @@ interface HTMLVideoElement extends HTMLMediaElement { 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; + 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; @@ -7140,13 +8110,71 @@ declare var HTMLVideoElement: { new(): HTMLVideoElement; }; +interface HTMLegendElement { + readonly form: HTMLFormElement | null; +} + +declare var HTMLegendElement: { + prototype: HTMLegendElement; + new(): HTMLegendElement; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string; + readonly oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: Function, thisArg?: any): 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; + scrollRestoration: ScrollRestoration; + readonly state: any; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): 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 HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + interface IDBCursor { readonly direction: IDBCursorDirection; - key: IDBKeyRange | IDBValidKey; + readonly key: IDBKeyRange | number | string | Date | IDBArrayKey; readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; + readonly source: IDBObjectStore | IDBIndex; advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; + continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void; delete(): IDBRequest; update(value: any): IDBRequest; readonly NEXT: string; @@ -7181,16 +8209,14 @@ interface IDBDatabaseEventMap { 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; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: Event) => any) | null; + readonly version: number; 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; @@ -7202,6 +8228,10 @@ declare var IDBDatabase: { new(): IDBDatabase; }; +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + interface IDBFactory { cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; @@ -7214,16 +8244,16 @@ declare var IDBFactory: { }; interface IDBIndex { - keyPath: string | string[]; + readonly keyPath: string | string[]; + multiEntry: boolean; 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; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -7248,21 +8278,21 @@ declare var IDBKeyRange: { }; interface IDBObjectStore { + autoIncrement: boolean; readonly indexNames: DOMStringList; - keyPath: string | string[]; + readonly keyPath: string | string[] | null; readonly name: string; readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): 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; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; } declare var IDBObjectStore: { @@ -7276,8 +8306,8 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { } interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: IDBOpenDBRequest, ev: Event) => any; - onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; 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; @@ -7296,11 +8326,11 @@ interface IDBRequestEventMap { interface IDBRequest extends EventTarget { readonly error: DOMException; - onerror: (this: IDBRequest, ev: Event) => any; - onsuccess: (this: IDBRequest, ev: Event) => any; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; readonly readyState: IDBRequestReadyState; readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; + readonly 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; @@ -7323,9 +8353,9 @@ 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; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -7364,8 +8394,23 @@ declare var IIRFilterNode: { new(): IIRFilterNode; }; +interface ImageBitmap { + readonly height: number; + readonly width: number; + close(): void; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + interface ImageData { - data: Uint8ClampedArray; + readonly data: Uint8ClampedArray; readonly height: number; readonly width: number; } @@ -7395,10 +8440,10 @@ interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; readonly intersectionRect: ClientRect | DOMRect; + readonly isIntersecting: boolean; readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; - readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -7408,19 +8453,23 @@ declare var IntersectionObserverEntry: { interface KeyboardEvent extends UIEvent { readonly altKey: boolean; - readonly char: string | null; + /** @deprecated */ + char: string; + /** @deprecated */ readonly charCode: number; + readonly code: string; readonly ctrlKey: boolean; readonly key: string; + /** @deprecated */ readonly keyCode: number; - readonly locale: string; readonly location: number; readonly metaKey: boolean; readonly repeat: boolean; readonly shiftKey: boolean; + /** @deprecated */ readonly which: number; - readonly code: string; getModifierState(keyArg: string): boolean; + /** @deprecated */ 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; @@ -7441,6 +8490,10 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_STANDARD: number; }; +interface LinkStyle { + readonly sheet: StyleSheet | null; +} + interface ListeningStateChangedEvent extends Event { readonly label: string; readonly state: ListeningState; @@ -7472,14 +8525,327 @@ declare var Location: { new(): Location; }; -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; } -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; +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 MSDCCEvent extends Event { + readonly maxFr: number; + readonly maxFs: number; +} + +declare var MSDCCEvent: { + prototype: MSDCCEvent; + new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent; +}; + +interface MSDSHEvent extends Event { + readonly sources: number[]; + readonly timestamp: number; +} + +declare var MSDSHEvent: { + prototype: MSDSHEvent; + new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent; +}; + +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 MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +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 MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null; + 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 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 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 MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string | null): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string; +}; + +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 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 MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MSStreamReaderEventMap { + "abort": UIEvent; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSStreamReader extends EventTarget { + readonly error: DOMError; + onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null; + onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null; + onload: ((this: MSStreamReader, ev: Event) => any) | null; + onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: MSStreamReader, ev: Event) => any) | null; + onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; + 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; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface MediaDeviceInfo { @@ -7499,7 +8865,7 @@ interface MediaDevicesEventMap { } interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; + ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; @@ -7562,26 +8928,16 @@ declare var MediaKeyMessageEvent: { new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; }; -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: BufferSource): 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: BufferSource): Promise; + generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: BufferSource): Promise; + update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; } declare var MediaKeySession: { @@ -7591,9 +8947,9 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: BufferSource): MediaKeyStatus; - has(keyId: BufferSource): boolean; + forEach(callback: Function, thisArg?: any): void; + get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus; + has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean; } declare var MediaKeyStatusMap: { @@ -7612,13 +8968,23 @@ declare var MediaKeySystemAccess: { new(): MediaKeySystemAccess; }; +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + interface MediaList { readonly length: number; mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; + appendMedium(medium: string): void; + deleteMedium(medium: string): void; + item(index: number): string | null; + toString(): number; [index: number]: string; } @@ -7665,10 +9031,10 @@ interface MediaStreamEventMap { 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; + onactive: ((this: MediaStream, ev: Event) => any) | null; + onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + oninactive: ((this: MediaStream, ev: Event) => any) | null; + onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; addTrack(track: MediaStreamTrack): void; clone(): MediaStream; getAudioTracks(): MediaStreamTrack[]; @@ -7685,7 +9051,9 @@ interface MediaStream extends EventTarget { declare var MediaStream: { prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; + new(): MediaStream; + new(stream: MediaStream): MediaStream; + new(tracks: MediaStreamTrack[]): MediaStream; }; interface MediaStreamAudioSourceNode extends AudioNode { @@ -7738,10 +9106,10 @@ interface MediaStreamTrack extends EventTarget { 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; + onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readonly: boolean; readonly readyState: MediaStreamTrackState; readonly remote: boolean; @@ -7784,9 +9152,9 @@ declare var 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; + readonly ports: ReadonlyArray; + readonly source: Window | null; + initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void; } declare var MessageEvent: { @@ -7799,7 +9167,7 @@ interface MessagePortEventMap { } interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; @@ -7845,6 +9213,7 @@ interface MouseEvent extends UIEvent { readonly clientX: number; readonly clientY: number; readonly ctrlKey: boolean; + /** @deprecated */ readonly fromElement: Element; readonly layerX: number; readonly layerY: number; @@ -7859,7 +9228,9 @@ interface MouseEvent extends UIEvent { readonly screenX: number; readonly screenY: number; readonly shiftKey: boolean; + /** @deprecated */ readonly toElement: Element; + /** @deprecated */ readonly which: number; readonly x: number; readonly y: number; @@ -7872,456 +9243,6 @@ declare var 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; @@ -8362,7 +9283,7 @@ interface MutationRecord { readonly previousSibling: Node | null; readonly removedNodes: NodeList; readonly target: Node; - readonly type: string; + readonly type: MutationRecordType; } declare var MutationRecord: { @@ -8372,13 +9293,13 @@ declare var 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; + getNamedItem(qualifiedName: string): Attr | null; + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + item(index: number): Attr | null; + removeNamedItem(qualifiedName: string): Attr; + removeNamedItemNS(namespace: string | null, localName: string): Attr; + setNamedItem(attr: Attr): Attr | null; + setNamedItemNS(attr: Attr): Attr | null; [index: number]: Attr; } @@ -8387,39 +9308,13 @@ declare var 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 { +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage { + readonly activeVRDisplays: ReadonlyArray; readonly authentication: WebAuthentication; readonly cookieEnabled: boolean; + readonly doNotTrack: string | null; gamepadInputEmulation: GamepadInputEmulationType; - readonly language: string; + readonly geolocation: Geolocation; readonly maxTouchPoints: number; readonly mimeTypes: MimeTypeArray; readonly msManipulationViewsEnabled: boolean; @@ -8429,10 +9324,8 @@ 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[]; + getGamepads(): (Gamepad | null)[]; + getVRDisplays(): Promise; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; @@ -8444,10 +9337,50 @@ declare var Navigator: { new(): Navigator; }; +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +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 NavigatorLanguage { + readonly language: string; + readonly languages: ReadonlyArray; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getDisplayMedia(constraints: MediaStreamConstraints): Promise; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + interface Node extends EventTarget { - readonly attributes: NamedNodeMap; readonly baseURI: string | null; - readonly childNodes: NodeList; + readonly childNodes: NodeListOf; readonly firstChild: Node | null; readonly lastChild: Node | null; readonly localName: string | null; @@ -8465,7 +9398,6 @@ interface Node extends EventTarget { 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; @@ -8520,7 +9452,7 @@ declare var Node: { }; interface NodeFilter { - acceptNode(n: Node): number; + acceptNode(node: Node): number; } declare var NodeFilter: { @@ -8543,13 +9475,14 @@ declare var NodeFilter: { }; interface NodeIterator { + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; detach(): void; - nextNode(): Node; - previousNode(): Node; + nextNode(): Node | null; + previousNode(): Node | null; } declare var NodeIterator: { @@ -8568,6 +9501,21 @@ declare var NodeList: { new(): NodeList; }; +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +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 NotificationEventMap { "click": Event; "close": Event; @@ -8576,16 +9524,17 @@ interface NotificationEventMap { } interface Notification extends EventTarget { - readonly body: string; + readonly body: string | null; + readonly data: any; 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 icon: string | null; + readonly lang: string | null; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; readonly permission: NotificationPermission; - readonly tag: string; + readonly tag: string | null; readonly title: string; close(): void; addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8652,6 +9601,14 @@ declare var OES_texture_half_float_linear: { new(): OES_texture_half_float_linear; }; +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; +} + interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; } @@ -8667,7 +9624,7 @@ interface OfflineAudioContextEventMap extends AudioContextEventMap { interface OfflineAudioContext extends AudioContextBase { readonly length: number; - oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; + oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null; startRendering(): Promise; suspend(suspendTime: number): Promise; addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8682,13 +9639,13 @@ declare var OfflineAudioContext: { }; interface OscillatorNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface OscillatorNode extends AudioNode { readonly detune: AudioParam; readonly frequency: AudioParam; - onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: OscillatorNode, ev: Event) => any) | null; type: OscillatorType; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; @@ -8739,8 +9696,11 @@ interface PannerNode extends AudioNode { panningModel: PanningModelType; refDistance: number; rolloffFactor: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -8749,12 +9709,28 @@ declare var PannerNode: { new(): PannerNode; }; -interface Path2D extends Object, CanvasPathMethods { +interface ParentNode { + readonly children: HTMLCollection; + 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 ParentNode { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; +} + +interface Path2D extends CanvasPathMethods { } declare var Path2D: { prototype: Path2D; - new(path?: Path2D): Path2D; + new(d?: Path2D | string): Path2D; }; interface PaymentAddress { @@ -8783,12 +9759,14 @@ interface PaymentRequestEventMap { } interface PaymentRequest extends EventTarget { - onshippingaddresschange: (this: PaymentRequest, ev: Event) => any; - onshippingoptionchange: (this: PaymentRequest, ev: Event) => any; + readonly id: string; + onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; + onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; readonly shippingType: PaymentShippingType | null; abort(): Promise; + canMakePayment(): 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; @@ -8798,11 +9776,11 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; - new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; }; interface PaymentRequestUpdateEvent extends Event { - updateWith(d: Promise): void; + updateWith(detailsPromise: Promise): void; } declare var PaymentRequestUpdateEvent: { @@ -8816,6 +9794,7 @@ interface PaymentResponse { readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; + readonly requestId: string; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; @@ -8827,16 +9806,50 @@ declare var PaymentResponse: { new(): PaymentResponse; }; +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 Performance { + /** @deprecated */ readonly navigation: PerformanceNavigation; + readonly timeOrigin: number; + /** @deprecated */ 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; + getEntriesByName(name: string, type?: string): any; + getEntriesByType(type: string): any; + /** @deprecated */ getMarks(markName?: string): any; + /** @deprecated */ getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; @@ -8855,6 +9868,7 @@ interface PerformanceEntry { readonly entryType: string; readonly name: string; readonly startTime: number; + toJSON(): any; } declare var PerformanceEntry: { @@ -8898,28 +9912,41 @@ declare var PerformanceNavigation: { }; interface PerformanceNavigationTiming extends PerformanceEntry { + /** @deprecated */ readonly connectEnd: number; + /** @deprecated */ readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; + /** @deprecated */ readonly domLoading: number; + /** @deprecated */ + readonly domainLookupEnd: number; + /** @deprecated */ + readonly domainLookupStart: number; + /** @deprecated */ readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; + /** @deprecated */ readonly navigationStart: number; readonly redirectCount: number; + /** @deprecated */ readonly redirectEnd: number; + /** @deprecated */ readonly redirectStart: number; + /** @deprecated */ readonly requestStart: number; + /** @deprecated */ readonly responseEnd: number; + /** @deprecated */ readonly responseStart: number; readonly type: NavigationType; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly workerStart: number; } declare var PerformanceNavigationTiming: { @@ -8939,6 +9966,7 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly workerStart: number; } declare var PerformanceResourceTiming: { @@ -8949,13 +9977,13 @@ declare var 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 domainLookupEnd: number; + readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -8966,9 +9994,9 @@ interface PerformanceTiming { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly secureConnectionStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; - readonly secureConnectionStart: number; toJSON(): any; } @@ -8977,35 +10005,6 @@ declare var 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 { } @@ -9087,12 +10086,11 @@ declare var 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; + new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent; }; interface Position { @@ -9140,10 +10138,21 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; + new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent; }; +interface PromiseRejectionEvent extends Event { + readonly promise: PromiseLike; + readonly reason: any; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: PromiseLike; + reason?: any; +} + interface PushManager { + readonly supportedContentEncodings: ReadonlyArray; getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; subscribe(options?: PushSubscriptionOptionsInit): Promise; @@ -9155,7 +10164,8 @@ declare var PushManager: { }; interface PushSubscription { - readonly endpoint: USVString; + readonly endpoint: string; + readonly expirationTime: number | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): any; @@ -9177,112 +10187,13 @@ declare var 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 | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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; +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } -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; - readonly signal: AbortSignal; - 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; +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDtlsTransportEventMap { @@ -9328,7 +10239,7 @@ interface RTCDtmfSender extends EventTarget { readonly canInsertDTMF: boolean; readonly duration: number; readonly interToneGap: number; - ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null; readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; @@ -9343,19 +10254,10 @@ declare var 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; + sdpMid: string | null; toJSON(): any; } @@ -9460,28 +10362,28 @@ interface RTCPeerConnection extends EventTarget { 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; + onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null; + oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; + onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; readonly remoteDescription: RTCSessionDescription | null; readonly signalingState: RTCSignalingState; - addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise; addStream(stream: MediaStream): void; close(): void; - createAnswer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - createOffer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, options?: RTCOfferOptions): Promise; + createAnswer(options?: RTCOfferOptions): Promise; + createOffer(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; + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit): 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; @@ -9504,10 +10406,14 @@ declare var RTCPeerConnectionIceEvent: { interface RTCRtpReceiverEventMap { "error": Event; + "msdecodercapacitychange": Event; + "msdsh": Event; } interface RTCRtpReceiver extends RTCStatsProvider { onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9604,433 +10510,122 @@ declare var RTCStatsProvider: { new(): RTCStatsProvider; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; +interface RandomSource { + getRandomValues(array: T): T; } -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; +declare var RandomSource: { + prototype: RandomSource; + new(): RandomSource; }; -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; - lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; - unlockOrientation(): 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; +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 | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + insertNode(node: Node): void; + isPointInRange(node: Node, offset: number): boolean; + selectNode(node: Node): void; + selectNodeContents(node: Node): void; + setEnd(node: Node, offset: number): void; + setEndAfter(node: Node): void; + setEndBefore(node: Node): void; + setStart(node: Node, offset: number): void; + setStartAfter(node: Node): void; + setStartBefore(node: 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 Selection: { - prototype: Selection; - new(): Selection; +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 ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -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; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; }; -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } -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; +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; }; -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 { +interface Request extends 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 signal: AbortSignal | null; + readonly type: RequestType; readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; + clone(): Request; } -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; }; -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; +interface Response extends Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; } -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; +declare var Response: { + prototype: Response; + new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; }; interface SVGAElement extends SVGGraphicsElement, SVGURIReference { @@ -10150,6 +10745,11 @@ declare var SVGAnimatedNumberList: { new(): SVGAnimatedNumberList; }; +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; readonly baseVal: SVGPreserveAspectRatio; @@ -10286,21 +10886,21 @@ interface SVGElementEventMap extends ElementEventMap { "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; +interface SVGElement extends Element, ElementCSSInlineStyle { + readonly className: any; + onclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null; + onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null; + onload: ((this: SVGElement, ev: Event) => any) | null; + onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null; + readonly ownerSVGElement: SVGSVGElement | null; + readonly viewportElement: SVGElement | null; + /** @deprecated */ 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; @@ -10330,7 +10930,9 @@ declare var SVGElementInstance: { }; interface SVGElementInstanceList { + /** @deprecated */ readonly length: number; + /** @deprecated */ item(index: number): SVGElementInstance; } @@ -10813,7 +11415,9 @@ declare var SVGFETurbulenceElement: { }; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { + /** @deprecated */ readonly filterResX: SVGAnimatedInteger; + /** @deprecated */ readonly filterResY: SVGAnimatedInteger; readonly filterUnits: SVGAnimatedEnumeration; readonly height: SVGAnimatedLength; @@ -10821,6 +11425,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + /** @deprecated */ 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; @@ -10833,6 +11438,19 @@ declare var SVGFilterElement: { new(): SVGFilterElement; }; +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 SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; readonly width: SVGAnimatedLength; @@ -10885,12 +11503,15 @@ declare var SVGGradientElement: { }; interface SVGGraphicsElement extends SVGElement, SVGTests { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; + /** @deprecated */ + readonly farthestViewportElement: SVGElement | null; + /** @deprecated */ + readonly nearestViewportElement: SVGElement | null; readonly transform: SVGAnimatedTransformList; getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; + getCTM(): SVGMatrix | null; + getScreenCTM(): SVGMatrix | null; + /** @deprecated */ 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; @@ -10972,22 +11593,6 @@ declare var 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; @@ -11004,6 +11609,22 @@ declare var SVGLineElement: { new(): SVGLineElement; }; +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 SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -11014,12 +11635,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: 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; @@ -11029,12 +11650,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; }; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { @@ -11118,26 +11739,47 @@ declare var SVGNumberList: { }; interface SVGPathElement extends SVGGraphicsElement { + /** @deprecated */ readonly pathSegList: SVGPathSegList; + /** @deprecated */ createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + /** @deprecated */ createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + /** @deprecated */ createSVGPathSegClosePath(): SVGPathSegClosePath; + /** @deprecated */ createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + /** @deprecated */ createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + /** @deprecated */ createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + /** @deprecated */ createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + /** @deprecated */ createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + /** @deprecated */ createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + /** @deprecated */ createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + /** @deprecated */ getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; @@ -11583,6 +12225,84 @@ declare var SVGRectElement: { new(): SVGRectElement; }; +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + contentScriptType: string; + /** @deprecated */ + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: ((this: SVGSVGElement, ev: Event) => any) | null; + onerror: ((this: SVGSVGElement, ev: Event) => any) | null; + onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onunload: ((this: SVGSVGElement, ev: Event) => any) | null; + onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; + /** @deprecated */ + readonly pixelUnitToMillimeterX: number; + /** @deprecated */ + readonly pixelUnitToMillimeterY: number; + /** @deprecated */ + readonly screenPixelToMillimeterX: number; + /** @deprecated */ + readonly screenPixelToMillimeterY: number; + /** @deprecated */ + 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; + /** @deprecated */ + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + /** @deprecated */ + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + /** @deprecated */ + pauseAnimations(): void; + /** @deprecated */ + setCurrentTime(seconds: number): void; + /** @deprecated */ + suspendRedraw(maxWaitMilliseconds: number): number; + /** @deprecated */ + unpauseAnimations(): void; + /** @deprecated */ + unsuspendRedraw(suspendHandleID: number): void; + /** @deprecated */ + 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 SVGScriptElement extends SVGElement, SVGURIReference { type: string; addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -11625,6 +12345,15 @@ declare var SVGStringList: { new(): SVGStringList; }; +interface SVGStylable { + className: any; +} + +declare var SVGStylable: { + prototype: SVGStylable; + new(): SVGStylable; +}; + interface SVGStyleElement extends SVGElement { disabled: boolean; media: string; @@ -11641,69 +12370,6 @@ declare var 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; @@ -11728,6 +12394,27 @@ declare var SVGSymbolElement: { new(): SVGSymbolElement; }; +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 SVGTests { + readonly requiredExtensions: SVGStringList; + /** @deprecated */ + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + /** @deprecated */ + hasExtension(extension: string): boolean; +} + interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; readonly textLength: SVGAnimatedLength; @@ -11874,18 +12561,10 @@ declare var 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; +interface SVGURIReference { + readonly href: SVGAnimatedString; } -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -}; - interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11894,9 +12573,9 @@ interface SVGUnitTypes { declare var SVGUnitTypes: SVGUnitTypes; interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; + readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; + readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -11911,7 +12590,8 @@ declare var SVGUseElement: { new(): SVGUseElement; }; -interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { +interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ 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; @@ -11947,6 +12627,477 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; +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; + /** @deprecated */ + 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) | null; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + unlockOrientation(): 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 ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + /** @deprecated */ + readonly bufferSize: number; + /** @deprecated */ + onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null; + 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 ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEvent extends Event { + readonly blockedURI: string; + readonly columnNumber: number; + readonly documentURI: string; + readonly effectiveDirective: string; + readonly lineNumber: number; + readonly originalPolicy: string; + readonly referrer: string; + readonly sourceFile: string; + readonly statusCode: number; + readonly violatedDirective: string; +} + +declare var SecurityPolicyViolationEvent: { + prototype: SecurityPolicyViolationEvent; + new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent; +}; + +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 ServiceUIFrameContext { + getCachedFrameMessage(key: string): string; + postFrameMessage(key: string, data: string): void; +} +declare var ServiceUIFrameContext: ServiceUIFrameContext; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + 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; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): 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: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | 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) | null; + readonly pushManager: PushManager; + readonly scope: string; + 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 ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: "open" | "closed"; +} + +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 | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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) | null; + 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 charLength: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance; +} + +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) | null; + onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + 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(): 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, value: string): void; + [key: string]: any; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + readonly key: string | null; + readonly newValue: string | null; + readonly oldValue: string | null; + readonly storageArea: Storage | null; + readonly url: string; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StorageEventInit extends EventInit { + key?: string; + newValue?: string; + oldValue?: string; + storageArea?: Storage; + url: string; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string | null; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet | null; + readonly title: string | null; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index: number): StyleSheet | null; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SyncManager { getTags(): Promise; register(tag: string): Promise; @@ -11958,8 +13109,8 @@ declare var SyncManager: { }; interface Text extends CharacterData { - readonly wholeText: string; readonly assignedSlot: HTMLSlotElement | null; + readonly wholeText: string; splitText(offset: number): Text; } @@ -11968,10 +13119,30 @@ declare var Text: { new(data?: string): Text; }; +interface TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + 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; @@ -12022,10 +13193,10 @@ interface TextTrack extends EventTarget { 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; + mode: TextTrackMode | number; + oncuechange: ((this: TextTrack, ev: Event) => any) | null; + onerror: ((this: TextTrack, ev: Event) => any) | null; + onload: ((this: TextTrack, ev: Event) => any) | null; readonly readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; @@ -12062,8 +13233,8 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { endTime: number; id: string; - onenter: (this: TextTrackCue, ev: Event) => any; - onexit: (this: TextTrackCue, ev: Event) => any; + onenter: ((this: TextTrackCue, ev: Event) => any) | null; + onexit: ((this: TextTrackCue, ev: Event) => any) | null; pauseOnExit: boolean; startTime: number; text: string; @@ -12149,6 +13320,7 @@ interface TouchEvent extends UIEvent { readonly shiftKey: boolean; readonly targetTouches: TouchList; readonly touches: TouchList; + /** @deprecated */ readonly which: number; } @@ -12157,6 +13329,12 @@ declare var TouchEvent: { new(type: string, touchEventInit?: TouchEventInit): TouchEvent; }; +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + interface TouchList { readonly length: number; item(index: number): Touch | null; @@ -12190,17 +13368,18 @@ declare var TransitionEvent: { interface TreeWalker { currentNode: Node; + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; + firstChild(): Node | null; + lastChild(): Node | null; + nextNode(): Node | null; + nextSibling(): Node | null; + parentNode(): Node | null; + previousNode(): Node | null; + previousSibling(): Node | null; } declare var TreeWalker: { @@ -12219,15 +13398,6 @@ declare var 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; @@ -12239,8 +13409,8 @@ interface URL { port: string; protocol: string; search: string; - username: string; readonly searchParams: URLSearchParams; + username: string; toString(): string; } @@ -12251,6 +13421,142 @@ declare var URL: { revokeObjectURL(url: string): 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; + new (init?: string | URLSearchParams): URLSearchParams; +}; + +interface VRDisplay extends EventTarget { + readonly capabilities: VRDisplayCapabilities; + depthFar: number; + depthNear: number; + readonly displayId: number; + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + readonly stageParameters: VRStageParameters | null; + cancelAnimationFrame(handle: number): void; + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + getFrameData(frameData: VRFrameData): boolean; + getLayers(): VRLayer[]; + /** @deprecated */ + getPose(): VRPose; + requestAnimationFrame(callback: FrameRequestCallback): number; + requestPresent(layers: VRLayer[]): Promise; + resetPose(): void; + submitFrame(pose?: VRPose): void; +} + +declare var VRDisplay: { + prototype: VRDisplay; + new(): VRDisplay; +}; + +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} + +declare var VRDisplayCapabilities: { + prototype: VRDisplayCapabilities; + new(): VRDisplayCapabilities; +}; + +interface VRDisplayEvent extends Event { + readonly display: VRDisplay; + readonly reason: VRDisplayEventReason | null; +} + +declare var VRDisplayEvent: { + prototype: VRDisplayEvent; + new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent; +}; + +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} + +declare var VREyeParameters: { + prototype: VREyeParameters; + new(): VREyeParameters; +}; + +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} + +declare var VRFieldOfView: { + prototype: VRFieldOfView; + new(): VRFieldOfView; +}; + +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} + +declare var VRFrameData: { + prototype: VRFrameData; + new(): VRFrameData; +}; + +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} + +declare var VRPose: { + prototype: VRPose; + new(): VRPose; +}; + interface ValidityState { readonly badInput: boolean; readonly customError: boolean; @@ -12259,10 +13565,10 @@ interface ValidityState { readonly rangeUnderflow: boolean; readonly stepMismatch: boolean; readonly tooLong: boolean; + readonly tooShort: boolean; readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; - readonly tooShort: boolean; } declare var ValidityState: { @@ -12305,9 +13611,9 @@ interface VideoTrackListEventMap { 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; + onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: VideoTrackList, ev: Event) => any) | null; + onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; @@ -12323,6 +13629,137 @@ declare var VideoTrackList: { new(): VideoTrackList; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly RGB32F_EXT: number; + readonly RGBA32F_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + 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_SRGB8_ALPHA8_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_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; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +}; + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_SRGB_S3TC_DXT1_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_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +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 WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_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 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 DRAW_BUFFER0_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 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 MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + interface WaveShaperNode extends AudioNode { curve: Float32Array | null; oversample: OverSampleType; @@ -12334,8 +13771,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -12355,44 +13792,6 @@ declare var 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; @@ -12469,8 +13868,8 @@ interface WebGLRenderingContext { 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; + bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void; + bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void; checkFramebufferStatus(target: number): number; clear(mask: number): void; clearColor(red: number, green: number, blue: number, alpha: number): void; @@ -12478,8 +13877,8 @@ interface WebGLRenderingContext { 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; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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; @@ -12569,7 +13968,7 @@ interface WebGLRenderingContext { 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; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | 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; @@ -12734,13 +14133,13 @@ interface WebGLRenderingContext { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12765,9 +14164,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12797,18 +14196,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -12842,20 +14241,6 @@ interface WebGLRenderingContext { 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; @@ -12888,9 +14273,23 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13036,13 +14435,13 @@ declare var WebGLRenderingContext: { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -13067,9 +14466,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -13099,18 +14498,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -13144,20 +14543,6 @@ declare var WebGLRenderingContext: { 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; @@ -13190,9 +14575,23 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13253,6 +14652,9 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; +interface WebGLVertexArrayObjectOES { +} + interface WebKitCSSMatrix { a: number; b: number; @@ -13353,18 +14755,6 @@ declare var 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; @@ -13373,18 +14763,18 @@ interface WebSocketEventMap { } interface WebSocket extends EventTarget { - binaryType: string; + binaryType: BinaryType; 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; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; readonly protocol: string; readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: USVString | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; @@ -13429,8 +14819,6 @@ declare var WheelEvent: { interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "afterprint": Event; - "beforeprint": Event; "beforeunload": BeforeUnloadEvent; "blur": FocusEvent; "canplay": Event; @@ -13452,7 +14840,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; @@ -13474,21 +14862,21 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "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; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -13518,19 +14906,32 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "touchstart": TouchEvent; "unload": Event; "volumechange": Event; + "vrdisplayactivate": Event; + "vrdisplayblur": Event; + "vrdisplayconnect": Event; + "vrdisplaydeactivate": Event; + "vrdisplaydisconnect": Event; + "vrdisplayfocus": Event; + "vrdisplaypointerrestricted": Event; + "vrdisplaypointerunrestricted": Event; + "vrdisplaypresentchange": Event; "waiting": Event; } interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { + Blob: typeof Blob; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; readonly applicationCache: ApplicationCache; readonly caches: CacheStorage; readonly clientInformation: Navigator; readonly closed: boolean; readonly crypto: Crypto; + customElements: CustomElementRegistry; defaultStatus: string; readonly devicePixelRatio: number; - readonly document: Document; readonly doNotTrack: string; + readonly document: Document; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13540,7 +14941,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly innerWidth: number; readonly isSecureContext: boolean; readonly length: number; - readonly location: Location; + location: Location; readonly locationbar: BarProp; readonly menubar: BarProp; readonly msContentScript: ExtensionScriptApis; @@ -13548,99 +14949,106 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + onabort: ((this: Window, ev: UIEvent) => any) | null; + onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; + onblur: ((this: Window, ev: FocusEvent) => any) | null; + oncanplay: ((this: Window, ev: Event) => any) | null; + oncanplaythrough: ((this: Window, ev: Event) => any) | null; + onchange: ((this: Window, ev: Event) => any) | null; + onclick: ((this: Window, ev: MouseEvent) => any) | null; + oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; + oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; + ondblclick: ((this: Window, ev: MouseEvent) => any) | null; + ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; + ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; + ondrag: ((this: Window, ev: DragEvent) => any) | null; + ondragend: ((this: Window, ev: DragEvent) => any) | null; + ondragenter: ((this: Window, ev: DragEvent) => any) | null; + ondragleave: ((this: Window, ev: DragEvent) => any) | null; + ondragover: ((this: Window, ev: DragEvent) => any) | null; + ondragstart: ((this: Window, ev: DragEvent) => any) | null; + ondrop: ((this: Window, ev: DragEvent) => any) | null; + ondurationchange: ((this: Window, ev: Event) => any) | null; + onemptied: ((this: Window, ev: Event) => any) | null; + onended: ((this: Window, ev: Event) => any) | null; 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; + onfocus: ((this: Window, ev: FocusEvent) => any) | null; + onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; + oninput: ((this: Window, ev: Event) => any) | null; + oninvalid: ((this: Window, ev: Event) => any) | null; + onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; + onload: ((this: Window, ev: Event) => any) | null; + onloadeddata: ((this: Window, ev: Event) => any) | null; + onloadedmetadata: ((this: Window, ev: Event) => any) | null; + onloadstart: ((this: Window, ev: Event) => any) | null; + onmessage: ((this: Window, ev: MessageEvent) => any) | null; + onmousedown: ((this: Window, ev: MouseEvent) => any) | null; + onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; + onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; + onmousemove: ((this: Window, ev: MouseEvent) => any) | null; + onmouseout: ((this: Window, ev: MouseEvent) => any) | null; + onmouseover: ((this: Window, ev: MouseEvent) => any) | null; + onmouseup: ((this: Window, ev: MouseEvent) => any) | null; + onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; + onmsgesturechange: ((this: Window, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; + onmsgestureend: ((this: Window, ev: Event) => any) | null; + onmsgesturehold: ((this: Window, ev: Event) => any) | null; + onmsgesturestart: ((this: Window, ev: Event) => any) | null; + onmsgesturetap: ((this: Window, ev: Event) => any) | null; + onmsinertiastart: ((this: Window, ev: Event) => any) | null; + onmspointercancel: ((this: Window, ev: Event) => any) | null; + onmspointerdown: ((this: Window, ev: Event) => any) | null; + onmspointerenter: ((this: Window, ev: Event) => any) | null; + onmspointerleave: ((this: Window, ev: Event) => any) | null; + onmspointermove: ((this: Window, ev: Event) => any) | null; + onmspointerout: ((this: Window, ev: Event) => any) | null; + onmspointerover: ((this: Window, ev: Event) => any) | null; + onmspointerup: ((this: Window, ev: Event) => any) | null; + onoffline: ((this: Window, ev: Event) => any) | null; + ononline: ((this: Window, ev: Event) => any) | null; + onorientationchange: ((this: Window, ev: Event) => any) | null; + onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpause: ((this: Window, ev: Event) => any) | null; + onplay: ((this: Window, ev: Event) => any) | null; + onplaying: ((this: Window, ev: Event) => any) | null; + onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; + onprogress: ((this: Window, ev: ProgressEvent) => any) | null; + onratechange: ((this: Window, ev: Event) => any) | null; + onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; + onreset: ((this: Window, ev: Event) => any) | null; + onresize: ((this: Window, ev: UIEvent) => any) | null; + onscroll: ((this: Window, ev: UIEvent) => any) | null; + onseeked: ((this: Window, ev: Event) => any) | null; + onseeking: ((this: Window, ev: Event) => any) | null; + onselect: ((this: Window, ev: UIEvent) => any) | null; + onstalled: ((this: Window, ev: Event) => any) | null; + onstorage: ((this: Window, ev: StorageEvent) => any) | null; + onsubmit: ((this: Window, ev: Event) => any) | null; + onsuspend: ((this: Window, ev: Event) => any) | null; + ontimeupdate: ((this: Window, ev: Event) => any) | null; 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; + onunload: ((this: Window, ev: Event) => any) | null; + onvolumechange: ((this: Window, ev: Event) => any) | null; + onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplayblur: ((this: Window, ev: Event) => any) | null; + onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + onwaiting: ((this: Window, ev: Event) => any) | null; + readonly opener: any; + readonly orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; readonly pageXOffset: number; @@ -13653,9 +15061,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; - readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; + readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13664,20 +15072,18 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + 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; departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; getSelection(): Selection; matchMedia(mediaQuery: string): MediaQueryList; moveBy(x?: number, y?: number): void; @@ -13691,19 +15097,17 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window requestAnimationFrame(callback: FrameRequestCallback): number; resizeBy(x?: number, y?: number): void; resizeTo(x?: number, y?: number): void; + scroll(options?: ScrollToOptions): void; scroll(x?: number, y?: number): void; + scrollBy(options?: ScrollToOptions): void; scrollBy(x?: number, y?: number): void; + scrollTo(options?: ScrollToOptions): 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; @@ -13715,12 +15119,79 @@ declare var Window: { new(): Window; }; +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowEventHandlersEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "hashchange": HashChangeEvent; + "message": MessageEvent; + "offline": Event; + "online": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface WindowEventHandlers { + onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; + onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; + ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; + onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers extends 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 WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; } interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: Worker, ev: MessageEvent) => any; + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** @deprecated */ postMessage(message: any, transfer?: any[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -13734,6 +15205,41 @@ declare var Worker: { new(stringUrl: string): Worker; }; +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +declare var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; +}; + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: any): Promise; +} + +declare var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(): WritableStreamDefaultWriter; +}; + 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; @@ -13751,7 +15257,8 @@ interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -13763,15 +15270,12 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { 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; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): 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; @@ -13795,6 +15299,30 @@ declare var XMLHttpRequest: { readonly UNSENT: 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) | null; + onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + 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 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; @@ -13898,1070 +15426,16 @@ declare var 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; +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: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[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 ElementCreationOptions { - is?: 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 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; -} - -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 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; - 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; -} - -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; -} - -interface AnimationKeyFrame { - offset?: number | null | (number | null)[]; - easing?: string | string[]; - [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; -} - -interface AnimationOptions { - id?: string; - delay?: number; - direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; - duration?: number; - easing?: string; - endDelay?: number; - fill?: "none" | "forwards" | "backwards" | "both"| "auto"; - iterationStart?: number; - iterations?: number; -} - -interface AnimationTimeline { - readonly currentTime: number | null; -} - -interface ComputedTimingProperties { - endTime: number; - activeDuration: number; - localTime: number | null; - progress: number | null; - currentIteration: number | null; -} - -interface AnimationEffectReadOnly { - readonly timing: number; - getComputedTiming(): ComputedTimingProperties; -} - -interface AnimationPlaybackEventInit extends EventInit { - currentTime?: number | null; - timelineTime?: number | null; -} - -interface AnimationPlaybackEvent extends Event { - readonly currentTime: number | null; - readonly timelineTime: number | null; -} - -declare var AnimationPlaybackEvent: { - prototype: AnimationPlaybackEvent; - new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; -}; - -interface Animation { - currentTime: number | null; - effect: AnimationEffectReadOnly; - readonly finished: Promise; - id: string; - readonly pending: boolean; - readonly playState: "idle" | "running" | "paused" | "finished"; - playbackRate: number; - readonly ready: Promise; - startTime: number; - timeline: AnimationTimeline; - oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; - onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; - cancel(): void; - finish(): void; - pause(): void; - play(): void; - reverse(): void; -} - -declare var Animation: { - prototype: Animation; - new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; }; declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; @@ -14969,66 +15443,95 @@ declare type EventListenerOrEventListenerObject = EventListener | EventListenerO interface DecodeErrorCallback { (error: DOMException): void; } + interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } + interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; } + +interface EventHandlerNonNull { + (event: Event): any; +} + interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, 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 MediaQueryListListener { + (mql: MediaQueryList): void; } + 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 WritableStreamChunkCallback { + (chunk: any, controller: WritableStreamDefaultController): void; +} + +interface WritableStreamDefaultControllerCallback { + (controller: WritableStreamDefaultController): void; +} + +interface WritableStreamErrorCallback { + (reason: string): void; +} + interface HTMLElementTagNameMap { "a": HTMLAnchorElement; "abbr": HTMLElement; @@ -15155,7 +15658,6 @@ interface HTMLElementTagNameMap { "var": HTMLElement; "video": HTMLVideoElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } @@ -15218,18 +15720,28 @@ interface SVGElementTagNameMap { /** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ 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 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 Blob: typeof Blob; +declare var URL: typeof URL; +declare var URLSearchParams: typeof URLSearchParams; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; declare var closed: boolean; declare var crypto: Crypto; +declare var customElements: CustomElementRegistry; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var document: Document; declare var doNotTrack: string; +declare var document: Document; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -15247,97 +15759,104 @@ 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 onabort: ((this: Window, ev: UIEvent) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +declare var onchange: ((this: Window, ev: Event) => any) | null; +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; +declare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; +declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +declare var onemptied: ((this: Window, ev: Event) => any) | null; +declare var onended: ((this: Window, ev: Event) => any) | null; 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 onfocus: ((this: Window, ev: FocusEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onload: ((this: Window, ev: Event) => any) | null; +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadstart: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; +declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; +declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; +declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; +declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; +declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; +declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; +declare var onmspointermove: ((this: Window, ev: Event) => any) | null; +declare var onmspointerout: ((this: Window, ev: Event) => any) | null; +declare var onmspointerover: ((this: Window, ev: Event) => any) | null; +declare var onmspointerup: ((this: Window, ev: Event) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onorientationchange: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpause: ((this: Window, ev: Event) => any) | null; +declare var onplay: ((this: Window, ev: Event) => any) | null; +declare var onplaying: ((this: Window, ev: Event) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onratechange: ((this: Window, ev: Event) => any) | null; +declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onseeked: ((this: Window, ev: Event) => any) | null; +declare var onseeking: ((this: Window, ev: Event) => any) | null; +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; 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 onunload: ((this: Window, ev: Event) => any) | null; +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; +declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; @@ -15352,9 +15871,9 @@ 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 scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -15363,17 +15882,18 @@ 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 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 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 getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; declare function getSelection(): Selection; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; @@ -15387,23 +15907,21 @@ 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(options?: ScrollToOptions): void; declare function scroll(x?: number, y?: number): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(options?: ScrollToOptions): 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 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; @@ -15414,26 +15932,36 @@ 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 onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; 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 fetch(input?: Request | string, 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 ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type IDBValidKey = number | string | Date | IDBArrayKey; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = Blob | BufferSource | FormData | string; +type MutationRecordType = "attributes" | "characterData" | "childList"; +type AAGUID = string; +type BodyInit = any; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; @@ -15455,9 +15983,6 @@ 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; @@ -15466,35 +15991,32 @@ 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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type AppendMode = "segments" | "sequence"; +type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "suspended" | "running" | "closed"; +type BinaryType = "blob" | "arraybuffer"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanPlayTypeResult = "" | "maybe" | "probably"; type CanvasFillRule = "nonzero" | "evenodd"; type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; +type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; +type EndOfStreamError = "network" | "decode"; type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; +type GamepadHand = "" | "left" | "right"; +type GamepadHapticActuatorType = "vibration"; type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type GamepadMappingType = "" | "standard"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; 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"; @@ -15502,25 +16024,23 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaStreamTrackState = "live" | "ended"; 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 PanningModelType = "equalpower" | "HRTF"; +type PaymentComplete = "success" | "fail" | "unknown"; 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"; @@ -15528,9 +16048,9 @@ 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 RTCIceGatherPolicy = "all" | "nohost" | "relay"; 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"; @@ -15541,9 +16061,22 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " 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 ReadyState = "closed" | "open" | "ended"; +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 ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; +type TextTrackMode = "disabled" | "hidden" | "showing"; type Transport = "usb" | "nfc" | "ble"; +type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; +type VREye = "left" | "right"; type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/lib.es2018.d.ts b/lib/lib.es2018.d.ts index 820467445eb..cfd5d0d60b2 100644 --- a/lib/lib.es2018.d.ts +++ b/lib/lib.es2018.d.ts @@ -19,3 +19,5 @@ 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 index eef11659216..716d022c2ff 100644 --- a/lib/lib.es2018.full.d.ts +++ b/lib/lib.es2018.full.d.ts @@ -19,8 +19,8 @@ and limitations under the License. /// - - +/// +/// ///////////////////////////// /// DOM APIs @@ -34,10 +34,49 @@ interface Account { rpDisplayName: string; } +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + interface Algorithm { name: string; } +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + interface AnimationEventInit extends EventInit { animationName?: string; elapsedTime?: number; @@ -46,10 +85,71 @@ interface AnimationEventInit extends EventInit { interface AssertionOptions { allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioContextInfo { + currentTime?: number; + sampleRate?: number; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioParamDescriptor { + defaultValue?: number; + maxValue?: number; + minValue?: number; + name?: string; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: number; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface ByteLengthChunk { + byteLength?: number; +} + interface CacheQueryOptions { cacheName?: string; ignoreMethod?: boolean; @@ -57,6 +157,14 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + interface ClientData { challenge: string; extensions?: WebAuthnExtensions; @@ -66,6 +174,12 @@ interface ClientData { tokenBinding?: string; } +interface ClientQueryOptions { + includeReserved?: boolean; + includeUncontrolled?: boolean; + type?: ClientTypes; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; @@ -80,6 +194,10 @@ interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation arrayOfDomainStrings?: string[]; } +interface ConstantSourceOptions { + offset?: number; +} + interface ConstrainBooleanParameters { exact?: boolean; ideal?: boolean; @@ -105,10 +223,27 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + interface CustomEventInit extends EventInit { detail?: T; } +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + interface DeviceAccelerationDict { x?: number | null; y?: number | null; @@ -139,18 +274,39 @@ interface DeviceRotationRateDict { gamma?: number | null; } -interface DOMRectInit { - height?: number; - width?: number; - x?: number; - y?: number; -} - interface DoubleRange { max?: number; min?: number; } +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: string; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: string | Algorithm; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -160,9 +316,13 @@ interface ErrorEventInit extends EventInit { } interface EventInit { - scoped?: boolean; bubbles?: boolean; cancelable?: boolean; + scoped?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; } interface EventModifierInit extends UIEventInit { @@ -187,6 +347,24 @@ interface ExceptionInformation { domain?: string | null; } +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: object | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + request: Request; + reservedClientId?: string; + targetClientId?: string; +} + interface FocusEventInit extends UIEventInit { relatedTarget?: EventTarget | null; } @@ -206,8 +384,12 @@ interface FocusNavigationOrigin { originWidth?: number; } +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + interface GamepadEventInit extends EventInit { - gamepad?: Gamepad | null; + gamepad?: Gamepad; } interface GetNotificationOptions { @@ -215,8 +397,29 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string | null; - oldURL?: string | null; + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: string | Algorithm; + info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface HmacImportParams extends Algorithm { + hash: string | Algorithm; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: string | Algorithm; + length?: number; } interface IDBIndexParameters { @@ -229,10 +432,15 @@ interface IDBObjectStoreParameters { keyPath?: string | string[]; } +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + interface IntersectionObserverEntryInit { - isIntersecting: boolean; boundingClientRect: DOMRectInit; intersectionRect: DOMRectInit; + isIntersecting: boolean; rootBounds: DOMRectInit; target: Element; time: number; @@ -244,8 +452,29 @@ interface IntersectionObserverInit { threshold?: number | number[]; } +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + interface KeyAlgorithm { - name?: string; + name: string; } interface KeyboardEventInit extends EventModifierInit { @@ -260,125 +489,6 @@ interface LongRange { 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; @@ -469,6 +579,16 @@ interface MSCredentialSpec { type: MSCredentialType; } +interface MSDCCEventInit extends EventInit { + maxFr?: number; + maxFs?: number; +} + +interface MSDSHEventInit extends EventInit { + sources?: number[]; + timestamp?: number; +} + interface MSDelay { roundTrip?: number; roundTripMax?: number; @@ -486,7 +606,13 @@ interface MSDescription extends RTCStats { interface MSFIDOCredentialParameters extends MSCredentialParameters { algorithm?: string | Algorithm; - authenticators?: AAGUID[]; + authenticators?: string[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSIceWarningFlags { @@ -514,12 +640,6 @@ interface MSIceWarningFlags { useCandidateChecksFailed?: boolean; } -interface MSIPAddressInfo { - ipAddr?: string; - manufacturerMacAddrMask?: string; - port?: number; -} - interface MSJitter { interArrival?: number; interArrivalMax?: number; @@ -548,8 +668,8 @@ interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; - interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; + interfaceTypeWireless?: boolean; } interface MSOutboundNetwork extends MSNetwork { @@ -586,8 +706,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { iceRole?: RTCIceRole; iceWarningFlags?: MSIceWarningFlags; interfaces?: MSNetworkInterfaceType; - localAddress?: string; localAddrType?: MSIceAddrType; + localAddress?: string; localInterface?: MSNetworkInterfaceType; localMR?: string; localMRTCPPort?: number; @@ -601,8 +721,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { portRangeMax?: number; portRangeMin?: number; protocol?: RTCIceProtocol; - remoteAddress?: string; remoteAddrType?: MSIceAddrType; + remoteAddress?: string; remoteMR?: string; remoteMRTCPPort?: number; remoteSite?: string; @@ -671,6 +791,133 @@ interface MSVideoSendPayload extends MSVideoPayload { sendVideoStreamsMax?: number; } +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +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 MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + channelCount?: number | ConstrainLongRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + displaySurface?: string | string[] | ConstrainDOMStringParameters; + echoCancellation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + latency?: number | ConstrainDoubleRange; + logicalSurface?: boolean | ConstrainBooleanParameters; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +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 { + channel?: string; + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: Window | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + interface MsZoomToOptions { animate?: string; contentX?: number; @@ -690,8 +937,14 @@ interface MutationObserverInit { subtree?: boolean; } +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; +} + interface NotificationOptions { body?: string; + data?: any; dir?: NotificationDirection; icon?: string; lang?: string; @@ -702,18 +955,49 @@ interface ObjectURLOptions { oneTimeOnly?: boolean; } +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + interface PaymentCurrencyAmount { currency: string; currencySystem?: string; value: string; } -interface PaymentDetails { +interface PaymentDetailsBase { displayItems?: PaymentItem[]; - error?: string; modifiers?: PaymentDetailsModifier[]; shippingOptions?: PaymentShippingOption[]; - total?: PaymentItem; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; } interface PaymentDetailsModifier { @@ -723,6 +1007,11 @@ interface PaymentDetailsModifier { total?: PaymentItem; } +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + total?: PaymentItem; +} + interface PaymentItem { amount: PaymentCurrencyAmount; label: string; @@ -752,10 +1041,21 @@ interface PaymentShippingOption { selected?: boolean; } +interface Pbkdf2Params extends Algorithm { + hash: string | Algorithm; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + interface PeriodicWaveConstraints { disableNormalization?: boolean; } +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[]; + real?: number[]; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -783,35 +1083,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface PushEventInit extends ExtendableEventInit { + data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | null; + applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; userVisibleOnly?: boolean; } -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - signal?: AbortSignal; - body?: Blob | BufferSource | FormData | string | null; - 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 QueuingStrategy { + highWaterMark?: number; + size?: WritableStreamChunkCallback; } interface RTCConfiguration { @@ -821,6 +1109,10 @@ interface RTCConfiguration { peerIdentity?: string; } +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + interface RTCDtlsFingerprint { algorithm?: string; value?: string; @@ -831,10 +1123,6 @@ interface RTCDtlsParameters { role?: RTCDtlsRole; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCIceCandidateAttributes extends RTCStats { addressSourceUrl?: string; candidateType?: RTCStatsIceCandidateType; @@ -862,8 +1150,8 @@ interface RTCIceCandidateDictionary { interface RTCIceCandidateInit { candidate?: string; - sdpMid?: string; sdpMLineIndex?: number; + sdpMid?: string; } interface RTCIceCandidatePair { @@ -918,13 +1206,13 @@ interface RTCMediaStreamTrackStats extends RTCStats { echoReturnLoss?: number; echoReturnLossEnhancement?: number; frameHeight?: number; + frameWidth?: number; framesCorrupted?: number; framesDecoded?: number; framesDropped?: number; framesPerSecond?: number; framesReceived?: number; framesSent?: number; - frameWidth?: number; remoteSource?: boolean; ssrcIds?: string[]; trackIdentifier?: string; @@ -948,6 +1236,20 @@ interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + mediaType?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtcpFeedback { parameter?: string; type?: string; @@ -969,9 +1271,9 @@ interface RTCRtpCapabilities { interface RTCRtpCodecCapability { clockRate?: number; kind?: string; - maxptime?: number; maxSpatialLayers?: number; maxTemporalLayers?: number; + maxptime?: number; name?: string; numChannels?: number; options?: any; @@ -988,7 +1290,7 @@ interface RTCRtpCodecParameters { name?: string; numChannels?: number; parameters?: any; - payloadType?: any; + payloadType?: number; ptime?: number; rtcpFeedback?: RTCRtcpFeedback[]; } @@ -1047,19 +1349,6 @@ 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; @@ -1111,8 +1400,70 @@ interface RTCTransportStats extends RTCStats { selectedCandidatePairId?: string; } +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: string | Algorithm; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: string | Algorithm; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + interface ScopedCredentialDescriptor { - id: BufferSource; + id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; transports?: Transport[]; type: ScopedCredentialType; } @@ -1120,7 +1471,7 @@ interface ScopedCredentialDescriptor { interface ScopedCredentialOptions { excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } @@ -1129,6 +1480,19 @@ interface ScopedCredentialParameters { type: ScopedCredentialType; } +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; @@ -1139,11 +1503,16 @@ interface ServiceWorkerMessageEventInit extends EventInit { interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; + charLength?: number; elapsedTime?: number; name?: string; utterance?: SpeechSynthesisUtterance | null; } +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + interface StoreExceptionsInformation extends ExceptionInformation { detailURI?: string | null; explanationString?: string | null; @@ -1154,6 +1523,20 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat arrayOfDomainStrings?: string[]; } +interface SyncEventInit extends ExtendableEventInit { + lastChance?: boolean; + tag: string; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } @@ -1168,14 +1551,43 @@ interface UIEventInit extends EventInit { view?: Window | null; } +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCallback; + start: WritableStreamDefaultControllerCallback; + write?: WritableStreamChunkCallback; +} + +interface VRDisplayEventInit extends EventInit { + display: VRDisplay; + reason?: VRDisplayEventReason; +} + +interface VRLayer { + leftBounds?: number[] | null; + rightBounds?: number[] | null; + source?: HTMLCanvasElement | null; +} + +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[]; + oversample?: OverSampleType; +} + interface WebAuthnExtensions { } interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; antialias?: boolean; depth?: boolean; + failIfMajorPerformanceCaveat?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; stencil?: boolean; @@ -1202,6 +1614,67 @@ type WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMErr type WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; }; +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 AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + 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 AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1219,23 +1692,39 @@ declare var 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; +interface Animation { + currentTime: number | null; + effect: AnimationEffectReadOnly; + readonly finished: Promise; + id: string; + readonly pending: boolean; + readonly playState: "idle" | "running" | "paused" | "finished"; + playbackRate: number; + readonly ready: Promise; + startTime: number; + timeline: AnimationTimeline; + cancel(): void; + finish(): void; + oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; + onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; + pause(): void; + play(): void; + reverse(): void; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; }; +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + 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: { @@ -1243,6 +1732,43 @@ declare var AnimationEvent: { new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; }; +interface AnimationKeyFrame { + easing?: string | string[]; + offset?: number | null | (number | null)[]; + [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; +} + +interface AnimationOptions { + delay?: number; + direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; + duration?: number; + easing?: string; + endDelay?: number; + fill?: "none" | "forwards" | "backwards" | "both"| "auto"; + id?: string; + iterationStart?: number; + iterations?: number; +} + +interface AnimationPlaybackEvent extends Event { + readonly currentTime: number | null; + readonly timelineTime: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +interface AnimationTimeline { + readonly currentTime: number | null; +} + interface ApplicationCacheEventMap { "cached": Event; "checking": Event; @@ -1255,14 +1781,14 @@ interface ApplicationCacheEventMap { } 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; + oncached: ((this: ApplicationCache, ev: Event) => any) | null; + onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + onerror: ((this: ApplicationCache, ev: Event) => any) | null; + onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; readonly status: number; abort(): void; swapCache(): void; @@ -1290,9 +1816,13 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; +interface AssignedNodesOptions { + flatten?: boolean; +} + interface Attr extends Node { readonly name: string; - readonly ownerElement: Element; + readonly ownerElement: Element | null; readonly prefix: string | null; readonly specified: boolean; value: string; @@ -1319,7 +1849,7 @@ declare var AudioBuffer: { }; interface AudioBufferSourceNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface AudioBufferSourceNode extends AudioNode { @@ -1328,7 +1858,7 @@ interface AudioBufferSourceNode extends AudioNode { loop: boolean; loopEnd: number; loopStart: number; - onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null; readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; @@ -1351,7 +1881,7 @@ interface AudioContextBase extends EventTarget { readonly currentTime: number; readonly destination: AudioDestinationNode; readonly listener: AudioListener; - onstatechange: (this: AudioContext, ev: Event) => any; + onstatechange: ((this: AudioContext, ev: Event) => any) | null; readonly sampleRate: number; readonly state: AudioContextState; close(): Promise; @@ -1401,10 +1931,15 @@ declare var AudioDestinationNode: { }; interface AudioListener { + /** @deprecated */ dopplerFactor: number; + /** @deprecated */ speedOfSound: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -1422,9 +1957,13 @@ interface AudioNode extends EventTarget { 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; + disconnect(): void; + disconnect(output: number): void; + disconnect(destination: AudioNode): void; + disconnect(destination: AudioNode, output: number): void; + disconnect(destination: AudioNode, output: number, input: number): void; + disconnect(destination: AudioParam): void; + disconnect(destination: AudioParam, output: number): void; } declare var AudioNode: { @@ -1435,12 +1974,12 @@ declare var AudioNode: { interface AudioParam { readonly defaultValue: number; value: number; - cancelScheduledValues(startTime: number): AudioParam; + cancelScheduledValues(cancelTime: 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; + setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam; } declare var AudioParam: { @@ -1481,9 +2020,9 @@ interface AudioTrackListEventMap { 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; + onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: AudioTrackList, ev: Event) => any) | null; + onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -1516,11 +2055,33 @@ declare var BeforeUnloadEvent: { new(): BeforeUnloadEvent; }; +interface BhxBrowser { + readonly lastError: DOMException; + checkMatchesGlobExpression(pattern: string, value: string): boolean; + checkMatchesUriExpression(pattern: string, value: string): boolean; + clearLastError(): void; + currentWindowId(): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + getThisAddress(): any; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericListenerHandler(eventHandler: Function): void; + setLastError(parameters: string): void; + webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void; +} + +declare var BhxBrowser: { + prototype: BhxBrowser; + new(): BhxBrowser; +}; + interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; - readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1543,113 +2104,50 @@ declare var 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; +interface BlobPropertyBag { + endings?: string; + type?: string; } -declare var Cache: { - prototype: Cache; - new(): Cache; +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + close(): void; + postMessage(message: any): 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 CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): Promise; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; } -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -}; - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; +interface ByteLengthQueuingStrategy { + highWaterMark: number; + size(chunk?: any): number; } -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; +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -1660,190 +2158,8 @@ declare var 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 { + escape(value: string): string; supports(property: string, value?: string): boolean; } declare var CSS: CSS; @@ -1903,7 +2219,7 @@ interface CSSKeyframesRule extends CSSRule { name: string; appendRule(rule: string): void; deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; + findRule(rule: string): CSSKeyframeRule | null; } declare var CSSKeyframesRule: { @@ -1944,14 +2260,14 @@ declare var CSSPageRule: { interface CSSRule { cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; + readonly parentRule: CSSRule | null; + readonly parentStyleSheet: CSSStyleSheet | null; 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 KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1967,8 +2283,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAME_RULE: number; readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1980,7 +2296,7 @@ declare var CSSRule: { interface CSSRuleList { readonly length: number; - item(index: number): CSSRule; + item(index: number): CSSRule | null; [index: number]: CSSRule; } @@ -1992,8 +2308,8 @@ declare var CSSRuleList: { interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignmentBaseline: string | null; alignSelf: string | null; + alignmentBaseline: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -2069,9 +2385,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; - columns: string | null; columnSpan: string | null; columnWidth: any; + columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -2105,11 +2421,32 @@ interface CSSStyleDeclaration { fontStyle: string | null; fontVariant: string | null; fontWeight: string | null; + gap: string | null; glyphOrientationHorizontal: string | null; glyphOrientationVertical: string | null; + grid: string | null; + gridArea: string | null; + gridAutoColumns: string | null; + gridAutoFlow: string | null; + gridAutoRows: string | null; + gridColumn: string | null; + gridColumnEnd: string | null; + gridColumnGap: string | null; + gridColumnStart: string | null; + gridGap: string | null; + gridRow: string | null; + gridRowEnd: string | null; + gridRowGap: string | null; + gridRowStart: string | null; + gridTemplate: string | null; + gridTemplateAreas: string | null; + gridTemplateColumns: string | null; + gridTemplateRows: string | null; height: string | null; imeMode: string | null; justifyContent: string | null; + justifyItems: string | null; + justifySelf: string | null; kerning: string | null; layoutGrid: string | null; layoutGridChar: string | null; @@ -2136,29 +2473,30 @@ interface CSSStyleDeclaration { markerMid: string | null; markerStart: string | null; mask: string | null; + maskImage: 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; + msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumns: string | null; msGridColumnSpan: any; + msGridColumns: string | null; msGridRow: any; msGridRowAlign: string | null; - msGridRows: string | null; msGridRowSpan: any; + msGridRows: string | null; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -2187,6 +2525,8 @@ interface CSSStyleDeclaration { msWrapFlow: string; msWrapMargin: any; msWrapThrough: string; + objectFit: string | null; + objectPosition: string | null; opacity: string | null; order: string | null; orphans: string | null; @@ -2207,13 +2547,16 @@ interface CSSStyleDeclaration { pageBreakBefore: string | null; pageBreakInside: string | null; readonly parentRule: CSSRule; + penAction: string | null; perspective: string | null; perspectiveOrigin: string | null; pointerEvents: string | null; position: string | null; quotes: string | null; + resize: string | null; right: string | null; rotate: string | null; + rowGap: string | null; rubyAlign: string | null; rubyOverhang: string | null; rubyPosition: string | null; @@ -2232,6 +2575,7 @@ interface CSSStyleDeclaration { textAlign: string | null; textAlignLast: string | null; textAnchor: string | null; + textCombineUpright: string | null; textDecoration: string | null; textIndent: string | null; textJustify: string | null; @@ -2253,6 +2597,7 @@ interface CSSStyleDeclaration { transitionTimingFunction: string | null; translate: string | null; unicodeBidi: string | null; + userSelect: string | null; verticalAlign: string | null; visibility: string | null; webkitAlignContent: string | null; @@ -2294,9 +2639,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; - webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; + webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2335,13 +2680,11 @@ interface CSSStyleDeclaration { 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; + setProperty(propertyName: string, value: string | null, priority?: string | null): void; [index: number]: string; } @@ -2351,7 +2694,6 @@ declare var CSSStyleDeclaration: { }; interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; selectorText: string; readonly style: CSSStyleDeclaration; } @@ -2363,21 +2705,32 @@ declare var CSSStyleRule: { interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; + /** @deprecated */ cssText: string; + /** @deprecated */ readonly id: string; + /** @deprecated */ readonly imports: StyleSheetList; + /** @deprecated */ readonly isAlternate: boolean; + /** @deprecated */ readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; + readonly ownerRule: CSSRule | null; + /** @deprecated */ readonly owningElement: Element; - readonly pages: StyleSheetPageList; + /** @deprecated */ + readonly pages: any; + /** @deprecated */ readonly readOnly: boolean; readonly rules: CSSRuleList; + /** @deprecated */ addImport(bstrURL: string, lIndex?: number): number; + /** @deprecated */ 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; + /** @deprecated */ removeImport(lIndex: number): void; removeRule(lIndex: number): void; } @@ -2395,6 +2748,380 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; +interface Cache { + add(request: Request | string): Promise; + addAll(requests: (Request | string)[]): Promise; + delete(request: Request | string, options?: CacheQueryOptions): Promise; + keys(request?: Request | string, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + matchAll(request?: Request | string, options?: CacheQueryOptions): Promise; + put(request: Request | string, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface Canvas2DContextAttributes { + alpha?: boolean; + storage?: boolean; + willReadFrequently?: boolean; + [attribute: string]: boolean | string | undefined; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +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; + arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: 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 CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends 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; + mozImageSmoothingEnabled: boolean; + msFillRule: CanvasFillRule; + oImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + webkitImageSmoothingEnabled: 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; + drawFocusIfNeeded(path: Path2D, 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; + isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(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 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 ChildNode { + remove(): void; +} + +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 ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(data?: string): 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 ComputedTimingProperties { + activeDuration: number; + currentIteration: number | null; + endTime: number; + localTime: number | null; + progress: number | null; +} + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: 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; + markTimeline(label?: string): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ContentScriptGlobalScope extends EventTarget { + readonly msContentScript: ExtensionScriptApis; + readonly window: Window; +} + +declare var ContentScriptGlobalScope: { + prototype: ContentScriptGlobalScope; + new(): ContentScriptGlobalScope; +}; + +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 CountQueuingStrategy { + highWaterMark: number; + size(): number; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(strategy: QueuingStrategy): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null; +} + +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 CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + whenDefined(name: string): PromiseLike; +} + interface CustomEvent extends Event { readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; @@ -2405,6 +3132,194 @@ declare var CustomEvent: { new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; +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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +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 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 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(...tokens: string[]): void; + contains(token: string): boolean; + item(index: number): string | null; + remove(...tokens: string[]): void; + replace(oldToken: string, newToken: string): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DataCue extends TextTrackCue { data: ArrayBuffer; addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -2451,10 +3366,11 @@ declare var DataTransferItem: { interface DataTransferItemList { readonly length: number; add(data: File): DataTransferItem | null; + add(data: string, type: string): DataTransferItem | null; clear(): void; item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: DataTransferItem; + [name: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -2541,11 +3457,30 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; }; +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforedeactivate": UIEvent; + "activate": Event; + "beforeactivate": Event; + "beforedeactivate": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -2553,7 +3488,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "click": MouseEvent; "contextmenu": PointerEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -2563,7 +3498,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "fullscreenchange": Event; @@ -2583,25 +3518,25 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "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; + "MSContentZoom": Event; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSManipulationStateChanged": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "mssitemodejumplistitemremoved": Event; + "msthumbnailclick": Event; "pause": Event; "play": Event; "playing": Event; @@ -2632,7 +3567,15 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "webkitfullscreenerror": Event; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { +interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent { + /** + * 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; /** * Gets the object that has the focus when the parent document has focus. */ @@ -2648,11 +3591,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * 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; + readonly anchors: HTMLCollectionOf; /** * Retrieves a collection of all applet objects in the document. */ - applets: HTMLCollectionOf; + readonly applets: HTMLCollectionOf; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ @@ -2688,7 +3631,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Gets a reference to the root node of the document. */ - documentElement: HTMLElement; + readonly documentElement: HTMLElement; /** * Sets or gets the security domain of the document. */ @@ -2696,7 +3639,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all embed objects in the document. */ - embeds: HTMLCollectionOf; + readonly embeds: HTMLCollectionOf; /** * Sets or gets the foreground (text) color of the document. */ @@ -2704,7 +3647,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of all form objects in the document. */ - forms: HTMLCollectionOf; + readonly forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; @@ -2712,7 +3655,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of img objects in the document. */ - images: HTMLCollectionOf; + readonly images: HTMLCollectionOf; /** * Gets the implementation object of the current document. */ @@ -2732,322 +3675,323 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. */ - links: HTMLCollectionOf; + readonly links: HTMLCollectionOf; /** * Contains information about the current URL. */ - readonly location: Location; - msCapsLockWarningOff: boolean; + location: Location; msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; /** * Fires when the user aborts the download. * @param ev The event. */ - onabort: (this: Document, ev: UIEvent) => any; + onabort: ((this: Document, ev: UIEvent) => any) | null; /** * Fires when the object is set as the active element. * @param ev The event. */ - onactivate: (this: Document, ev: UIEvent) => any; + onactivate: ((this: Document, ev: Event) => any) | null; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ - onbeforeactivate: (this: Document, ev: UIEvent) => any; + onbeforeactivate: ((this: Document, ev: Event) => any) | null; /** * 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; + onbeforedeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ - onblur: (this: Document, ev: FocusEvent) => any; + onblur: ((this: Document, ev: FocusEvent) => any) | null; /** * 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; + oncanplay: ((this: Document, ev: Event) => any) | null; + oncanplaythrough: ((this: Document, ev: Event) => any) | null; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ - onchange: (this: Document, ev: Event) => any; + onchange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ - onclick: (this: Document, ev: MouseEvent) => any; + onclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ - ondblclick: (this: Document, ev: MouseEvent) => any; + ondblclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + ondeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ - ondrag: (this: Document, ev: DragEvent) => any; + ondrag: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragend: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragenter: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragleave: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragover: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragstart: ((this: Document, ev: DragEvent) => any) | null; + ondrop: ((this: Document, ev: DragEvent) => any) | null; /** * Occurs when the duration attribute is updated. * @param ev The event. */ - ondurationchange: (this: Document, ev: Event) => any; + ondurationchange: ((this: Document, ev: Event) => any) | null; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ - onemptied: (this: Document, ev: Event) => any; + onemptied: ((this: Document, ev: Event) => any) | null; /** * Occurs when the end of playback is reached. * @param ev The event */ - onended: (this: Document, ev: MediaStreamErrorEvent) => any; + onended: ((this: Document, ev: Event) => any) | null; /** * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (this: Document, ev: ErrorEvent) => any; + onerror: ((this: Document, ev: ErrorEvent) => any) | null; /** * 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; + onfocus: ((this: Document, ev: FocusEvent) => any) | null; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + oninput: ((this: Document, ev: Event) => any) | null; + oninvalid: ((this: Document, ev: Event) => any) | null; /** * Fires when the user presses a key. * @param ev The keyboard event */ - onkeydown: (this: Document, ev: KeyboardEvent) => any; + onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ - onkeypress: (this: Document, ev: KeyboardEvent) => any; + onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user releases a key. * @param ev The keyboard event */ - onkeyup: (this: Document, ev: KeyboardEvent) => any; + onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires immediately after the browser loads the object. * @param ev The event. */ - onload: (this: Document, ev: Event) => any; + onload: ((this: Document, ev: Event) => any) | null; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ - onloadeddata: (this: Document, ev: Event) => any; + onloadeddata: ((this: Document, ev: Event) => any) | null; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ - onloadedmetadata: (this: Document, ev: Event) => any; + onloadedmetadata: ((this: Document, ev: Event) => any) | null; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ - onloadstart: (this: Document, ev: Event) => any; + onloadstart: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ - onmousedown: (this: Document, ev: MouseEvent) => any; + onmousedown: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ - onmousemove: (this: Document, ev: MouseEvent) => any; + onmousemove: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseout: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ - onmouseover: (this: Document, ev: MouseEvent) => any; + onmouseover: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseup: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmousewheel: ((this: Document, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: Document, ev: Event) => any) | null; + onmsgesturechange: ((this: Document, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null; + onmsgestureend: ((this: Document, ev: Event) => any) | null; + onmsgesturehold: ((this: Document, ev: Event) => any) | null; + onmsgesturestart: ((this: Document, ev: Event) => any) | null; + onmsgesturetap: ((this: Document, ev: Event) => any) | null; + onmsinertiastart: ((this: Document, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null; + onmspointercancel: ((this: Document, ev: Event) => any) | null; + onmspointerdown: ((this: Document, ev: Event) => any) | null; + onmspointerenter: ((this: Document, ev: Event) => any) | null; + onmspointerleave: ((this: Document, ev: Event) => any) | null; + onmspointermove: ((this: Document, ev: Event) => any) | null; + onmspointerout: ((this: Document, ev: Event) => any) | null; + onmspointerover: ((this: Document, ev: Event) => any) | null; + onmspointerup: ((this: Document, ev: Event) => any) | null; /** * 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; + onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null; /** * 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; + onmsthumbnailclick: ((this: Document, ev: Event) => any) | null; /** * Occurs when playback is paused. * @param ev The event. */ - onpause: (this: Document, ev: Event) => any; + onpause: ((this: Document, ev: Event) => any) | null; /** * Occurs when the play method is requested. * @param ev The event. */ - onplay: (this: Document, ev: Event) => any; + onplay: ((this: Document, ev: Event) => any) | null; /** * 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; + onplaying: ((this: Document, ev: Event) => any) | null; + onpointerlockchange: ((this: Document, ev: Event) => any) | null; + onpointerlockerror: ((this: Document, ev: Event) => any) | null; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ - onprogress: (this: Document, ev: ProgressEvent) => any; + onprogress: ((this: Document, ev: ProgressEvent) => any) | null; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ - onratechange: (this: Document, ev: Event) => any; + onratechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the state of the object has changed. * @param ev The event */ - onreadystatechange: (this: Document, ev: Event) => any; + onreadystatechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user resets a form. * @param ev The event. */ - onreset: (this: Document, ev: Event) => any; + onreset: ((this: Document, ev: Event) => any) | null; /** * 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; + onscroll: ((this: Document, ev: UIEvent) => any) | null; /** * Occurs when the seek operation ends. * @param ev The event. */ - onseeked: (this: Document, ev: Event) => any; + onseeked: ((this: Document, ev: Event) => any) | null; /** * Occurs when the current playback position is moved. * @param ev The event. */ - onseeking: (this: Document, ev: Event) => any; + onseeking: ((this: Document, ev: Event) => any) | null; /** * Fires when the current selection changes. * @param ev The event. */ - onselect: (this: Document, ev: UIEvent) => any; + onselect: ((this: Document, ev: UIEvent) => any) | null; /** * 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; + onselectionchange: ((this: Document, ev: Event) => any) | null; + onselectstart: ((this: Document, ev: Event) => any) | null; /** * Occurs when the download has stopped. * @param ev The event. */ - onstalled: (this: Document, ev: Event) => any; + onstalled: ((this: Document, ev: Event) => any) | null; /** * 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; + onstop: ((this: Document, ev: Event) => any) | null; + onsubmit: ((this: Document, ev: Event) => any) | null; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ - onsuspend: (this: Document, ev: Event) => any; + onsuspend: ((this: Document, ev: Event) => any) | null; /** * 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; + ontimeupdate: ((this: Document, ev: Event) => any) | null; + ontouchcancel: ((this: Document, ev: TouchEvent) => any) | null; + ontouchend: ((this: Document, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Document, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Document, ev: TouchEvent) => any) | null; + onvisibilitychange: (this: Document, ev: Event) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ - onvolumechange: (this: Document, ev: Event) => any; + onvolumechange: ((this: Document, ev: Event) => any) | null; /** * 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; + onwaiting: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null; + readonly plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** * Retrieves a value that indicates the current state of the object. @@ -3064,7 +4008,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all script objects in the document. */ - scripts: HTMLCollectionOf; + readonly 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. @@ -3074,14 +4018,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * 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. @@ -3097,7 +4033,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string | null; - onvisibilitychange: (this: Document, ev: Event) => any; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; @@ -3193,6 +4128,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver: Node): XPathNSResolver; /** * 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. @@ -3201,7 +4137,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @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. @@ -3228,6 +4163,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; + elementsFromPoint(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. @@ -3246,6 +4182,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Causes the element to receive the focus and executes the code specified by the onfocus event. */ + /** @deprecated */ focus(): void; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. @@ -3318,10 +4255,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ queryCommandValue(commandId: string): string; releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** @@ -3345,7 +4278,79 @@ declare var Document: { new(): Document; }; -interface DocumentFragment extends Node, NodeSelector, ParentNode { +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + 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: "MSDCCEvent"): MSDCCEvent; + createEvent(eventInterface: "MSDSHEvent"): MSDSHEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + 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: "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: "PromiseRejectionEvent"): PromiseRejectionEvent; + 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: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + 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: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DocumentFragment extends Node, ParentNode { getElementById(elementId: string): HTMLElement | null; } @@ -3354,6 +4359,14 @@ declare var DocumentFragment: { new(): DocumentFragment; }; +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly styleSheets: StyleSheetList; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + getSelection(): Selection | null; +} + interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; readonly internalSubset: string | null; @@ -3368,149 +4381,6 @@ declare var 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; @@ -3536,209 +4406,23 @@ declare var 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 EXT_blend_minmax { + readonly MAX_EXT: number; + readonly MIN_EXT: number; } -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 | null; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB_EXT: number; +} + +interface EXT_shader_texture_lod { +} interface EXT_texture_filter_anisotropic { readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; @@ -3752,14 +4436,262 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; }; +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": Event; + "command": Event; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSGotPointerCapture": Event; + "MSInertiaStart": Event; + "MSLostPointerCapture": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode { + readonly assignedSlot: HTMLSlotElement | null; + readonly attributes: NamedNodeMap; + 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) | null; + oncommand: ((this: Element, ev: Event) => any) | null; + ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onmsgesturechange: ((this: Element, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null; + onmsgestureend: ((this: Element, ev: Event) => any) | null; + onmsgesturehold: ((this: Element, ev: Event) => any) | null; + onmsgesturestart: ((this: Element, ev: Event) => any) | null; + onmsgesturetap: ((this: Element, ev: Event) => any) | null; + onmsgotpointercapture: ((this: Element, ev: Event) => any) | null; + onmsinertiastart: ((this: Element, ev: Event) => any) | null; + onmslostpointercapture: ((this: Element, ev: Event) => any) | null; + onmspointercancel: ((this: Element, ev: Event) => any) | null; + onmspointerdown: ((this: Element, ev: Event) => any) | null; + onmspointerenter: ((this: Element, ev: Event) => any) | null; + onmspointerleave: ((this: Element, ev: Event) => any) | null; + onmspointermove: ((this: Element, ev: Event) => any) | null; + onmspointerout: ((this: Element, ev: Event) => any) | null; + onmspointerover: ((this: Element, ev: Event) => any) | null; + onmspointerup: ((this: Element, ev: Event) => any) | null; + ontouchcancel: ((this: Element, ev: TouchEvent) => any) | null; + ontouchend: ((this: Element, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Element, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Element, ev: TouchEvent) => any) | null; + onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; + outerHTML: string; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly shadowRoot: ShadowRoot | null; + slot: string; + readonly tagName: string; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + getAttribute(qualifiedName: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + getElementsByClassName(classNames: string): NodeListOf; + 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; + hasAttributes(): boolean; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + matches(selectors: string): boolean; + msGetRegionContent(): any; + 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; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + setAttribute(qualifiedName: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): 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: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + readonly style: CSSStyleDeclaration; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ElementDefinitionOptions { + extends: string; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly nextElementSibling: Element | null; + readonly previousElementSibling: Element | null; +} + +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(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly scoped: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget | null; + readonly timeStamp: number; + readonly type: string; + deepPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(typeArg: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; - fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; genericSynchronousFunction(functionId: number, parameters?: string): string; + genericWebRuntimeCallout(to: any, from: any, payload: string): void; getExtensionId(): string; - registerGenericFunctionCallbackHandler(callbackHandler: any): void; - registerGenericPersistentCallbackHandler(callbackHandler: any): void; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericPersistentCallbackHandler(callbackHandler: Function): void; + registerWebRuntimeCallbackHandler(handler: Function): any; } declare var ExtensionScriptApis: { @@ -3776,10 +4708,11 @@ declare var External: { }; interface File extends Blob { + readonly lastModified: number; + /** @deprecated */ readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; - readonly lastModified: number; } declare var File: { @@ -3789,7 +4722,7 @@ declare var File: { interface FileList { readonly length: number; - item(index: number): File; + item(index: number): File | null; [index: number]: File; } @@ -3798,21 +4731,49 @@ declare var FileList: { new(): FileList; }; -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; 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; + readAsText(blob: Blob, label?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[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: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface FocusEvent extends UIEvent { @@ -3850,7 +4811,8 @@ interface FormData { declare var FormData: { prototype: FormData; - new (form?: HTMLFormElement): FormData; + new(): FormData; + new(form: HTMLFormElement): FormData; }; interface GainNode extends AudioNode { @@ -3866,9 +4828,13 @@ interface Gamepad { readonly axes: number[]; readonly buttons: GamepadButton[]; readonly connected: boolean; + readonly displayId: number; + readonly hand: GamepadHand; + readonly hapticActuators: GamepadHapticActuator[]; readonly id: string; readonly index: number; - readonly mapping: string; + readonly mapping: GamepadMappingType; + readonly pose: GamepadPose | null; readonly timestamp: number; } @@ -3879,6 +4845,7 @@ declare var Gamepad: { interface GamepadButton { readonly pressed: boolean; + readonly touched: boolean; readonly value: number; } @@ -3896,6 +4863,32 @@ declare var GamepadEvent: { new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; }; +interface GamepadHapticActuator { + readonly type: GamepadHapticActuatorType; + pulse(value: number, duration: number): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GamepadPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; +} + +declare var GamepadPose: { + prototype: GamepadPose; + new(): GamepadPose; +}; + interface Geolocation { clearWatch(watchId: number): void; getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; @@ -3907,45 +4900,41 @@ declare var Geolocation: { new(): Geolocation; }; -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; +interface GetSVGDocument { + getSVGDocument(): Document; } -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; +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; } -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; +interface GlobalEventHandlers { + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + 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; } -declare var History: { - prototype: History; - new(): History; -}; +interface GlobalFetch { + fetch(input?: Request | string, init?: RequestInit): Promise; +} interface HTMLAllCollection { readonly length: number; @@ -3959,55 +4948,30 @@ declare var HTMLAllCollection: { new(): HTMLAllCollection; }; -interface HTMLAnchorElement extends HTMLElement { +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + Methods: string; /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Sets or retrieves the coordinates of the object. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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. @@ -4016,14 +4980,12 @@ interface HTMLAnchorElement extends HTMLElement { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ 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. */ + /** @deprecated */ shape: string; /** * Sets or retrieves the window or frame at which to target content. @@ -4035,10 +4997,6 @@ interface HTMLAnchorElement extends HTMLElement { 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; @@ -4051,70 +5009,44 @@ declare var HTMLAnchorElement: { }; interface HTMLAppletElement extends HTMLElement { + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ 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. */ + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; /** * Sets or retrieves the shape of the object. */ + /** @deprecated */ 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; + /** @deprecated */ + object: string; + /** @deprecated */ vspace: number; - width: number; + /** @deprecated */ + width: string; 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; @@ -4126,7 +5058,7 @@ declare var HTMLAppletElement: { new(): HTMLAppletElement; }; -interface HTMLAreaElement extends HTMLElement { +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { /** * Sets or retrieves a text alternative to the graphic. */ @@ -4136,43 +5068,12 @@ interface HTMLAreaElement extends HTMLElement { */ 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. */ + /** @deprecated */ 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. */ @@ -4181,10 +5082,6 @@ interface HTMLAreaElement extends HTMLElement { * 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; @@ -4216,6 +5113,23 @@ declare var HTMLAudioElement: { new(): HTMLAudioElement; }; +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. + */ + /** @deprecated */ + 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 HTMLBaseElement extends HTMLElement { /** * Gets or sets the baseline URL on which relative links are based. @@ -4240,10 +5154,12 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ face: string; /** * Sets or retrieves the font size of the object. */ + /** @deprecated */ 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; @@ -4256,51 +5172,34 @@ declare var HTMLBaseFontElement: { new(): HTMLBaseFontElement; }; -interface HTMLBodyElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { + /** @deprecated */ + aLink: string; + /** @deprecated */ background: string; - bgColor: any; + /** @deprecated */ + bgColor: string; bgProperties: string; - link: any; + /** @deprecated */ + link: string; + /** @deprecated */ 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; + onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; + onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null; + /** @deprecated */ + text: string; + /** @deprecated */ + vLink: string; 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; @@ -4312,22 +5211,6 @@ declare var 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. @@ -4353,7 +5236,7 @@ interface HTMLButtonElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -4423,12 +5306,12 @@ interface HTMLCanvasElement extends HTMLElement { * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ msToBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; /** * 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; @@ -4464,6 +5347,26 @@ declare var HTMLCollection: { new(): HTMLCollection; }; +interface HTMLCollectionOf extends HTMLCollectionBase { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface HTMLDListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLDataElement extends HTMLElement { value: string; addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4478,7 +5381,7 @@ declare var HTMLDataElement: { }; interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; + readonly 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; @@ -4490,6 +5393,36 @@ declare var HTMLDataListElement: { new(): HTMLDataListElement; }; +interface HTMLDetailsElement extends HTMLElement { + open: boolean; + addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; + addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + interface HTMLDirectoryElement extends HTMLElement { compact: boolean; addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4507,6 +5440,7 @@ interface HTMLDivElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. @@ -4523,19 +5457,6 @@ declare var 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; @@ -4550,12 +5471,12 @@ declare var HTMLDocument: { interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforecopy": ClipboardEvent; - "beforecut": ClipboardEvent; - "beforedeactivate": UIEvent; - "beforepaste": ClipboardEvent; + "activate": Event; + "beforeactivate": Event; + "beforecopy": Event; + "beforecut": Event; + "beforedeactivate": Event; + "beforepaste": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -4566,7 +5487,7 @@ interface HTMLElementEventMap extends ElementEventMap { "cuechange": Event; "cut": ClipboardEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -4576,7 +5497,7 @@ interface HTMLElementEventMap extends ElementEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "input": Event; @@ -4596,8 +5517,8 @@ interface HTMLElementEventMap extends ElementEventMap { "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": WheelEvent; - "MSContentZoom": UIEvent; - "MSManipulationStateChanged": MSManipulationEvent; + "MSContentZoom": Event; + "MSManipulationStateChanged": Event; "paste": ClipboardEvent; "pause": Event; "play": Event; @@ -4618,9 +5539,8 @@ interface HTMLElementEventMap extends ElementEventMap { "waiting": Event; } -interface HTMLElement extends Element { +interface HTMLElement extends Element, ElementCSSInlineStyle { accessKey: string; - readonly children: HTMLCollection; contentEditable: string; readonly dataset: DOMStringMap; dir: string; @@ -4635,84 +5555,83 @@ interface HTMLElement extends Element { 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; + onabort: ((this: HTMLElement, ev: UIEvent) => any) | null; + onactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecut: ((this: HTMLElement, ev: Event) => any) | null; + onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null; + onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oncanplay: ((this: HTMLElement, ev: Event) => any) | null; + oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null; + onchange: ((this: HTMLElement, ev: Event) => any) | null; + onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null; + oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + oncuechange: ((this: HTMLElement, ev: Event) => any) | null; + oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + ondeactivate: ((this: HTMLElement, ev: Event) => any) | null; + ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondurationchange: ((this: HTMLElement, ev: Event) => any) | null; + onemptied: ((this: HTMLElement, ev: Event) => any) | null; + onended: ((this: HTMLElement, ev: Event) => any) | null; + onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null; + onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oninput: ((this: HTMLElement, ev: Event) => any) | null; + oninvalid: ((this: HTMLElement, ev: Event) => any) | null; + onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onload: ((this: HTMLElement, ev: Event) => any) | null; + onloadeddata: ((this: HTMLElement, ev: Event) => any) | null; + onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null; + onloadstart: ((this: HTMLElement, ev: Event) => any) | null; + onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null; + onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + onpause: ((this: HTMLElement, ev: Event) => any) | null; + onplay: ((this: HTMLElement, ev: Event) => any) | null; + onplaying: ((this: HTMLElement, ev: Event) => any) | null; + onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null; + onratechange: ((this: HTMLElement, ev: Event) => any) | null; + onreset: ((this: HTMLElement, ev: Event) => any) | null; + onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null; + onseeked: ((this: HTMLElement, ev: Event) => any) | null; + onseeking: ((this: HTMLElement, ev: Event) => any) | null; + onselect: ((this: HTMLElement, ev: UIEvent) => any) | null; + onselectstart: ((this: HTMLElement, ev: Event) => any) | null; + onstalled: ((this: HTMLElement, ev: Event) => any) | null; + onsubmit: ((this: HTMLElement, ev: Event) => any) | null; + onsuspend: ((this: HTMLElement, ev: Event) => any) | null; + ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null; + onvolumechange: ((this: HTMLElement, ev: Event) => any) | null; + onwaiting: ((this: HTMLElement, ev: Event) => any) | null; outerText: string; spellcheck: boolean; - readonly style: CSSStyleDeclaration; tabIndex: number; title: string; + animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; blur(): void; click(): void; dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; 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; @@ -4749,6 +5668,7 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * Retrieves the palette used for the embedded document. @@ -4829,6 +5749,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ 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; @@ -4909,6 +5830,7 @@ interface HTMLFormElement extends HTMLElement { * Retrieves a form object or an object from an elements collection. */ namedItem(name: string): any; + reportValidity(): boolean; /** * Fires when the user resets a form. */ @@ -4917,8 +5839,6 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ 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; @@ -4947,14 +5867,17 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + /** @deprecated */ + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + /** @deprecated */ + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. @@ -4967,30 +5890,37 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a URI to a long description of the object. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ marginWidth: string; /** * Sets or retrieves the frame name. */ + /** @deprecated */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ + /** @deprecated */ noResize: boolean; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ + /** @deprecated */ src: string; /** * Sets or retrieves the width of the object. @@ -5007,64 +5937,29 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; }; -interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { /** * Sets or retrieves the frame widths of the object. */ + /** @deprecated */ 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; + onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null; + onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null; /** * Sets or retrieves the frame heights of the object. */ + /** @deprecated */ 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; @@ -5077,7 +5972,35 @@ declare var HTMLFrameSetElement: { new(): HTMLFrameSetElement; }; +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + /** @deprecated */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + 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 HTMLHeadElement extends HTMLElement { + /** @deprecated */ 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; @@ -5094,6 +6017,7 @@ interface HTMLHeadingElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ 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; @@ -5106,34 +6030,11 @@ declare var 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. */ + /** @deprecated */ 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; @@ -5146,6 +6047,19 @@ declare var HTMLHtmlElement: { new(): HTMLHtmlElement; }; +interface HTMLHyperlinkElementUtils { + hash: string; + host: string; + hostname: string; + href: string; + origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + toString(): string; +} + interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; } @@ -5154,78 +6068,64 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ 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; + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ 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. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ 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; + readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** - * Sets or retrieves the vertical margin for the object. + * Sets or retrives the content of the page that is to contain. */ - vspace: number; + srcdoc: string; /** * 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; @@ -5241,6 +6141,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5249,6 +6150,7 @@ interface HTMLImageElement extends HTMLElement { /** * Specifies the properties of a border drawn around an object. */ + /** @deprecated */ border: string; /** * Retrieves whether the object is fully loaded. @@ -5256,6 +6158,7 @@ interface HTMLImageElement extends HTMLElement { readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; /** * Sets or retrieves the height of the object. */ @@ -5263,6 +6166,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ hspace: number; /** * Sets or retrieves whether the image is a server-side image map. @@ -5272,6 +6176,7 @@ interface HTMLImageElement extends HTMLElement { * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. */ longDesc: string; + /** @deprecated */ lowsrc: string; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5289,6 +6194,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * The original height of the image resource before sizing. @@ -5311,6 +6217,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the vertical margin for the object. */ + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -5338,6 +6245,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5351,18 +6259,10 @@ interface HTMLInputElement 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 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. */ @@ -5395,7 +6295,7 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -5403,16 +6303,12 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + height: number; indeterminate: boolean; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ - readonly list: HTMLElement; + readonly list: HTMLElement | null; /** * 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. */ @@ -5425,6 +6321,7 @@ interface HTMLInputElement extends HTMLElement { * 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; + minLength: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ @@ -5446,21 +6343,20 @@ interface HTMLInputElement extends HTMLElement { * When present, marks an element that can't be submitted without a value. */ required: boolean; - selectionDirection: string; + selectionDirection: string | null; /** * Gets or sets the end position or offset of a text selection. */ - selectionEnd: number; + selectionEnd: number | null; /** * Gets or sets the starting position or offset of a text selection. */ - selectionStart: number; + selectionStart: number | null; 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. */ @@ -5472,6 +6368,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ + /** @deprecated */ 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. @@ -5485,25 +6382,20 @@ interface HTMLInputElement extends HTMLElement { * Returns the value of the data at the cursor's current position. */ value: string; - valueAsDate: Date; + valueAsDate: any; /** * 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; + width: number; /** * 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. */ @@ -5545,48 +6437,8 @@ declare var 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 { + /** @deprecated */ type: string; /** * Sets or retrieves the value of a list item. @@ -5603,11 +6455,56 @@ declare var HTMLLIElement: { new(): HTMLLIElement; }; +interface HTMLLabelElement extends HTMLElement { + readonly control: HTMLInputElement | null; + /** + * 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; + 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. + */ + /** @deprecated */ + 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 HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; + crossOrigin: string | null; + /** @deprecated */ disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. @@ -5617,6 +6514,8 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { * Sets or retrieves the language code of the object. */ hreflang: string; + import?: Document; + integrity: string; /** * Sets or retrieves the media type. */ @@ -5628,17 +6527,17 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ rev: string; /** * Sets or retrieves the window or frame at which to target content. */ + /** @deprecated */ 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; @@ -5650,6 +6549,18 @@ declare var HTMLLinkElement: { new(): HTMLLinkElement; }; +interface HTMLMainElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. @@ -5677,21 +6588,37 @@ interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { } interface HTMLMarqueeElement extends HTMLElement { + /** @deprecated */ behavior: string; - bgColor: any; + /** @deprecated */ + bgColor: string; + /** @deprecated */ direction: string; + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; + /** @deprecated */ loop: number; - onbounce: (this: HTMLMarqueeElement, ev: Event) => any; - onfinish: (this: HTMLMarqueeElement, ev: Event) => any; - onstart: (this: HTMLMarqueeElement, ev: Event) => any; + /** @deprecated */ + onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ scrollAmount: number; + /** @deprecated */ scrollDelay: number; + /** @deprecated */ trueSpeed: boolean; + /** @deprecated */ vspace: number; + /** @deprecated */ width: string; + /** @deprecated */ start(): void; + /** @deprecated */ 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; @@ -5706,7 +6633,7 @@ declare var HTMLMarqueeElement: { interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; - "msneedkey": MSMediaKeyNeededEvent; + "msneedkey": Event; } interface HTMLMediaElement extends HTMLElement { @@ -5751,7 +6678,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Returns an object representing the current error state of the audio or video element. */ - readonly error: MediaError; + readonly error: MediaError | null; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ @@ -5769,6 +6696,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ + /** @deprecated */ readonly msKeys: MSMediaKeys; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5798,8 +6726,9 @@ interface HTMLMediaElement extends HTMLElement { * Gets the current network activity for the element. */ readonly networkState: number; - onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null; + /** @deprecated */ + onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null; /** * Gets a flag that specifies whether playback is paused. */ @@ -5816,7 +6745,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: number; + readonly readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -5829,18 +6758,18 @@ interface HTMLMediaElement extends HTMLElement { * The address or URL of the a media resource that is to be considered. */ src: string; - srcObject: MediaStream | null; + srcObject: MediaStream | MediaSource | Blob | 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; + addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack; /** * Returns a string that specifies whether the client can play a given media resource type. */ - canPlayType(type: string): string; + canPlayType(type: string): CanPlayTypeResult; /** * Resets the audio or video object and loads a new media resource. */ @@ -5854,6 +6783,7 @@ interface HTMLMediaElement extends HTMLElement { * Inserts the specified audio effect into media pipeline. */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + /** @deprecated */ msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Specifies the media protection manager for a given media pipeline. @@ -5898,6 +6828,7 @@ declare var HTMLMediaElement: { }; interface HTMLMenuElement extends HTMLElement { + /** @deprecated */ compact: boolean; type: string; addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -5915,6 +6846,7 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. @@ -5931,10 +6863,12 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ + /** @deprecated */ scheme: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ + /** @deprecated */ 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; @@ -5985,41 +6919,63 @@ declare var HTMLModElement: { new(): HTMLModElement; }; +interface HTMLOListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLObjectElement extends HTMLElement, GetSVGDocument { - align: 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; + /** @deprecated */ + align: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ border: string; /** * Sets or retrieves the URL of the file containing the compiled Java class. */ + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ + /** @deprecated */ codeType: string; /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + readonly contentDocument: Document | null; /** * Sets or retrieves the URL that references the data of the object. */ data: string; + /** @deprecated */ declare: boolean; /** * Retrieves a reference to the form that the object is embedded in. @@ -6029,6 +6985,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the height of the object. */ height: string; + /** @deprecated */ hspace: number; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -6054,11 +7011,13 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a message to be displayed while an object is loading. */ + /** @deprecated */ standby: string; /** * Sets or retrieves the MIME type of the object. */ type: string; + typemustmatch: boolean; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ @@ -6071,6 +7030,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -6080,7 +7040,6 @@ 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. */ @@ -6101,54 +7060,16 @@ declare var 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; @@ -6204,7 +7125,7 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; remove(index: number): void; } @@ -6216,7 +7137,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; readonly form: HTMLFormElement | null; - readonly htmlFor: DOMSettableTokenList; + readonly htmlFor: DOMTokenList; name: string; readonly type: string; readonly validationMessage: string; @@ -6241,6 +7162,7 @@ interface HTMLParagraphElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -6262,6 +7184,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the content type of the resource designated by the value attribute. */ + /** @deprecated */ type: string; /** * Sets or retrieves the value of an input parameter for an element. @@ -6270,6 +7193,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the data type of the value attribute. */ + /** @deprecated */ 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; @@ -6298,6 +7222,7 @@ interface HTMLPreElement extends HTMLElement { /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ + /** @deprecated */ 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; @@ -6368,11 +7293,15 @@ interface HTMLScriptElement extends HTMLElement { /** * Sets or retrieves the event for which the script is written. */ + /** @deprecated */ event: string; /** * Sets or retrieves the object that is bound to the event script. */ + /** @deprecated */ htmlFor: string; + integrity: string; + noModule: boolean; /** * Retrieves the URL to an external file that contains the source code or data. */ @@ -6385,7 +7314,6 @@ interface HTMLScriptElement extends HTMLElement { * 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; @@ -6428,7 +7356,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the index of the selected option in a select object. */ selectedIndex: number; - selectedOptions: HTMLCollectionOf; + readonly selectedOptions: HTMLCollectionOf; /** * Sets or retrieves the number of rows in the list box. */ @@ -6458,7 +7386,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6468,7 +7396,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + item(name?: any, index?: any): Element | null; /** * 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. @@ -6496,11 +7424,21 @@ declare var HTMLSelectElement: { new(): HTMLSelectElement; }; +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; + addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; + /** @deprecated */ msKeySystem: string; sizes: string; /** @@ -6536,6 +7474,7 @@ declare var HTMLSpanElement: { }; interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** @deprecated */ disabled: boolean; /** * Sets or retrieves the media type. @@ -6556,15 +7495,24 @@ declare var HTMLStyleElement: { new(): HTMLStyleElement; }; +interface HTMLSummaryElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. */ + /** @deprecated */ 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; @@ -6576,7 +7524,7 @@ declare var HTMLTableCaptionElement: { new(): HTMLTableCaptionElement; }; -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableCellElement extends HTMLElement { /** * Sets or retrieves abbreviated text for the object. */ @@ -6584,16 +7532,23 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. */ + /** @deprecated */ axis: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves the position of the object in the cells collection of a row. */ readonly cellIndex: number; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number columns in the table that the object should span. */ @@ -6605,10 +7560,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves the height of the object. */ - height: any; + /** @deprecated */ + height: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ + /** @deprecated */ noWrap: boolean; /** * Sets or retrieves how many rows in a table the cell should span. @@ -6618,9 +7575,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ 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; @@ -6633,19 +7593,27 @@ declare var HTMLTableCellElement: { new(): HTMLTableCellElement; }; -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableColElement extends HTMLElement { /** * Sets or retrieves the alignment of the object relative to the display or table. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of columns in the group. */ span: number; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ - width: any; + /** @deprecated */ + width: string; 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; @@ -6673,67 +7641,64 @@ interface HTMLTableElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; /** * Retrieves the caption object of a table. */ - caption: HTMLTableCaptionElement; + caption: HTMLTableCaptionElement | null; /** * Sets or retrieves the amount of space between the border of the cell and the content of the cell. */ + /** @deprecated */ cellPadding: string; /** * Sets or retrieves the amount of space between cells in a table. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + readonly rows: HTMLCollectionOf; /** * Sets or retrieves which dividing lines (inner borders) are displayed. */ + /** @deprecated */ rules: string; /** * Sets or retrieves a description and/or structure of the object. */ + /** @deprecated */ summary: string; /** * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. */ - tBodies: HTMLCollectionOf; + readonly tBodies: HTMLCollectionOf; /** * Retrieves the tFoot object of the table. */ - tFoot: HTMLTableSectionElement; + tFoot: HTMLTableSectionElement | null; /** * Retrieves the tHead object of the table. */ - tHead: HTMLTableSectionElement; + tHead: HTMLTableSectionElement | null; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ width: string; /** * Creates an empty caption element in the table. @@ -6785,9 +7750,6 @@ declare var 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; @@ -6800,20 +7762,22 @@ declare var HTMLTableHeaderCellElement: { new(): HTMLTableHeaderCellElement; }; -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableRowElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves a collection of all cells in the table row. */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; + readonly cells: HTMLCollectionOf; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Retrieves the position of the object in the rows collection for the table. */ @@ -6822,6 +7786,8 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Retrieves the position of the object in the collection. */ readonly sectionRowIndex: number; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6843,15 +7809,22 @@ declare var HTMLTableRowElement: { new(): HTMLTableRowElement; }; -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableSectionElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of horizontal rows contained in the object. */ - rows: HTMLCollectionOf; + readonly rows: HTMLCollectionOf; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6908,6 +7881,7 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; + minLength: number; /** * Sets or retrieves the name of the object. */ @@ -6936,10 +7910,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -6964,7 +7934,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -7053,7 +8022,9 @@ declare var HTMLTrackElement: { }; interface HTMLUListElement extends HTMLElement { + /** @deprecated */ compact: boolean; + /** @deprecated */ 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; @@ -7095,9 +8066,9 @@ interface HTMLVideoElement extends HTMLMediaElement { msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; - onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; /** * 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. */ @@ -7120,10 +8091,10 @@ interface HTMLVideoElement extends HTMLMediaElement { 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; + 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; @@ -7135,13 +8106,71 @@ declare var HTMLVideoElement: { new(): HTMLVideoElement; }; +interface HTMLegendElement { + readonly form: HTMLFormElement | null; +} + +declare var HTMLegendElement: { + prototype: HTMLegendElement; + new(): HTMLegendElement; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string; + readonly oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: Function, thisArg?: any): 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; + scrollRestoration: ScrollRestoration; + readonly state: any; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): 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 HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + interface IDBCursor { readonly direction: IDBCursorDirection; - key: IDBKeyRange | IDBValidKey; + readonly key: IDBKeyRange | number | string | Date | IDBArrayKey; readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; + readonly source: IDBObjectStore | IDBIndex; advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; + continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void; delete(): IDBRequest; update(value: any): IDBRequest; readonly NEXT: string; @@ -7176,16 +8205,14 @@ interface IDBDatabaseEventMap { 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; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: Event) => any) | null; + readonly version: number; 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; @@ -7197,6 +8224,10 @@ declare var IDBDatabase: { new(): IDBDatabase; }; +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + interface IDBFactory { cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; @@ -7209,16 +8240,16 @@ declare var IDBFactory: { }; interface IDBIndex { - keyPath: string | string[]; + readonly keyPath: string | string[]; + multiEntry: boolean; 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; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -7243,21 +8274,21 @@ declare var IDBKeyRange: { }; interface IDBObjectStore { + autoIncrement: boolean; readonly indexNames: DOMStringList; - keyPath: string | string[]; + readonly keyPath: string | string[] | null; readonly name: string; readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): 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; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; } declare var IDBObjectStore: { @@ -7271,8 +8302,8 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { } interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: IDBOpenDBRequest, ev: Event) => any; - onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; 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; @@ -7291,11 +8322,11 @@ interface IDBRequestEventMap { interface IDBRequest extends EventTarget { readonly error: DOMException; - onerror: (this: IDBRequest, ev: Event) => any; - onsuccess: (this: IDBRequest, ev: Event) => any; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; readonly readyState: IDBRequestReadyState; readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; + readonly 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; @@ -7318,9 +8349,9 @@ 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; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -7359,8 +8390,23 @@ declare var IIRFilterNode: { new(): IIRFilterNode; }; +interface ImageBitmap { + readonly height: number; + readonly width: number; + close(): void; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + interface ImageData { - data: Uint8ClampedArray; + readonly data: Uint8ClampedArray; readonly height: number; readonly width: number; } @@ -7390,10 +8436,10 @@ interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; readonly intersectionRect: ClientRect | DOMRect; + readonly isIntersecting: boolean; readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; - readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -7403,19 +8449,23 @@ declare var IntersectionObserverEntry: { interface KeyboardEvent extends UIEvent { readonly altKey: boolean; - readonly char: string | null; + /** @deprecated */ + char: string; + /** @deprecated */ readonly charCode: number; + readonly code: string; readonly ctrlKey: boolean; readonly key: string; + /** @deprecated */ readonly keyCode: number; - readonly locale: string; readonly location: number; readonly metaKey: boolean; readonly repeat: boolean; readonly shiftKey: boolean; + /** @deprecated */ readonly which: number; - readonly code: string; getModifierState(keyArg: string): boolean; + /** @deprecated */ 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; @@ -7436,6 +8486,10 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_STANDARD: number; }; +interface LinkStyle { + readonly sheet: StyleSheet | null; +} + interface ListeningStateChangedEvent extends Event { readonly label: string; readonly state: ListeningState; @@ -7467,14 +8521,327 @@ declare var Location: { new(): Location; }; -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; } -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; +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 MSDCCEvent extends Event { + readonly maxFr: number; + readonly maxFs: number; +} + +declare var MSDCCEvent: { + prototype: MSDCCEvent; + new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent; +}; + +interface MSDSHEvent extends Event { + readonly sources: number[]; + readonly timestamp: number; +} + +declare var MSDSHEvent: { + prototype: MSDSHEvent; + new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent; +}; + +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 MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +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 MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null; + 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 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 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 MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string | null): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string; +}; + +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 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 MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MSStreamReaderEventMap { + "abort": UIEvent; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSStreamReader extends EventTarget { + readonly error: DOMError; + onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null; + onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null; + onload: ((this: MSStreamReader, ev: Event) => any) | null; + onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: MSStreamReader, ev: Event) => any) | null; + onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; + 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; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface MediaDeviceInfo { @@ -7494,7 +8861,7 @@ interface MediaDevicesEventMap { } interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; + ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; @@ -7557,26 +8924,16 @@ declare var MediaKeyMessageEvent: { new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; }; -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: BufferSource): 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: BufferSource): Promise; + generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: BufferSource): Promise; + update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; } declare var MediaKeySession: { @@ -7586,9 +8943,9 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: BufferSource): MediaKeyStatus; - has(keyId: BufferSource): boolean; + forEach(callback: Function, thisArg?: any): void; + get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus; + has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean; } declare var MediaKeyStatusMap: { @@ -7607,13 +8964,23 @@ declare var MediaKeySystemAccess: { new(): MediaKeySystemAccess; }; +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + interface MediaList { readonly length: number; mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; + appendMedium(medium: string): void; + deleteMedium(medium: string): void; + item(index: number): string | null; + toString(): number; [index: number]: string; } @@ -7660,10 +9027,10 @@ interface MediaStreamEventMap { 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; + onactive: ((this: MediaStream, ev: Event) => any) | null; + onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + oninactive: ((this: MediaStream, ev: Event) => any) | null; + onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; addTrack(track: MediaStreamTrack): void; clone(): MediaStream; getAudioTracks(): MediaStreamTrack[]; @@ -7680,7 +9047,9 @@ interface MediaStream extends EventTarget { declare var MediaStream: { prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; + new(): MediaStream; + new(stream: MediaStream): MediaStream; + new(tracks: MediaStreamTrack[]): MediaStream; }; interface MediaStreamAudioSourceNode extends AudioNode { @@ -7733,10 +9102,10 @@ interface MediaStreamTrack extends EventTarget { 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; + onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readonly: boolean; readonly readyState: MediaStreamTrackState; readonly remote: boolean; @@ -7779,9 +9148,9 @@ declare var 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; + readonly ports: ReadonlyArray; + readonly source: Window | null; + initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void; } declare var MessageEvent: { @@ -7794,7 +9163,7 @@ interface MessagePortEventMap { } interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; @@ -7840,6 +9209,7 @@ interface MouseEvent extends UIEvent { readonly clientX: number; readonly clientY: number; readonly ctrlKey: boolean; + /** @deprecated */ readonly fromElement: Element; readonly layerX: number; readonly layerY: number; @@ -7854,7 +9224,9 @@ interface MouseEvent extends UIEvent { readonly screenX: number; readonly screenY: number; readonly shiftKey: boolean; + /** @deprecated */ readonly toElement: Element; + /** @deprecated */ readonly which: number; readonly x: number; readonly y: number; @@ -7867,456 +9239,6 @@ declare var 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; @@ -8357,7 +9279,7 @@ interface MutationRecord { readonly previousSibling: Node | null; readonly removedNodes: NodeList; readonly target: Node; - readonly type: string; + readonly type: MutationRecordType; } declare var MutationRecord: { @@ -8367,13 +9289,13 @@ declare var 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; + getNamedItem(qualifiedName: string): Attr | null; + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + item(index: number): Attr | null; + removeNamedItem(qualifiedName: string): Attr; + removeNamedItemNS(namespace: string | null, localName: string): Attr; + setNamedItem(attr: Attr): Attr | null; + setNamedItemNS(attr: Attr): Attr | null; [index: number]: Attr; } @@ -8382,39 +9304,13 @@ declare var 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 { +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage { + readonly activeVRDisplays: ReadonlyArray; readonly authentication: WebAuthentication; readonly cookieEnabled: boolean; + readonly doNotTrack: string | null; gamepadInputEmulation: GamepadInputEmulationType; - readonly language: string; + readonly geolocation: Geolocation; readonly maxTouchPoints: number; readonly mimeTypes: MimeTypeArray; readonly msManipulationViewsEnabled: boolean; @@ -8424,10 +9320,8 @@ 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[]; + getGamepads(): (Gamepad | null)[]; + getVRDisplays(): Promise; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; @@ -8439,10 +9333,50 @@ declare var Navigator: { new(): Navigator; }; +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +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 NavigatorLanguage { + readonly language: string; + readonly languages: ReadonlyArray; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getDisplayMedia(constraints: MediaStreamConstraints): Promise; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + interface Node extends EventTarget { - readonly attributes: NamedNodeMap; readonly baseURI: string | null; - readonly childNodes: NodeList; + readonly childNodes: NodeListOf; readonly firstChild: Node | null; readonly lastChild: Node | null; readonly localName: string | null; @@ -8460,7 +9394,6 @@ interface Node extends EventTarget { 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; @@ -8515,7 +9448,7 @@ declare var Node: { }; interface NodeFilter { - acceptNode(n: Node): number; + acceptNode(node: Node): number; } declare var NodeFilter: { @@ -8538,13 +9471,14 @@ declare var NodeFilter: { }; interface NodeIterator { + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; detach(): void; - nextNode(): Node; - previousNode(): Node; + nextNode(): Node | null; + previousNode(): Node | null; } declare var NodeIterator: { @@ -8563,6 +9497,21 @@ declare var NodeList: { new(): NodeList; }; +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +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 NotificationEventMap { "click": Event; "close": Event; @@ -8571,16 +9520,17 @@ interface NotificationEventMap { } interface Notification extends EventTarget { - readonly body: string; + readonly body: string | null; + readonly data: any; 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 icon: string | null; + readonly lang: string | null; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; readonly permission: NotificationPermission; - readonly tag: string; + readonly tag: string | null; readonly title: string; close(): void; addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8647,6 +9597,14 @@ declare var OES_texture_half_float_linear: { new(): OES_texture_half_float_linear; }; +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; +} + interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; } @@ -8662,7 +9620,7 @@ interface OfflineAudioContextEventMap extends AudioContextEventMap { interface OfflineAudioContext extends AudioContextBase { readonly length: number; - oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; + oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null; startRendering(): Promise; suspend(suspendTime: number): Promise; addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8677,13 +9635,13 @@ declare var OfflineAudioContext: { }; interface OscillatorNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface OscillatorNode extends AudioNode { readonly detune: AudioParam; readonly frequency: AudioParam; - onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: OscillatorNode, ev: Event) => any) | null; type: OscillatorType; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; @@ -8734,8 +9692,11 @@ interface PannerNode extends AudioNode { panningModel: PanningModelType; refDistance: number; rolloffFactor: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -8744,12 +9705,28 @@ declare var PannerNode: { new(): PannerNode; }; -interface Path2D extends Object, CanvasPathMethods { +interface ParentNode { + readonly children: HTMLCollection; + 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 ParentNode { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; +} + +interface Path2D extends CanvasPathMethods { } declare var Path2D: { prototype: Path2D; - new(path?: Path2D): Path2D; + new(d?: Path2D | string): Path2D; }; interface PaymentAddress { @@ -8778,12 +9755,14 @@ interface PaymentRequestEventMap { } interface PaymentRequest extends EventTarget { - onshippingaddresschange: (this: PaymentRequest, ev: Event) => any; - onshippingoptionchange: (this: PaymentRequest, ev: Event) => any; + readonly id: string; + onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; + onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; readonly shippingType: PaymentShippingType | null; abort(): Promise; + canMakePayment(): 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; @@ -8793,11 +9772,11 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; - new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; }; interface PaymentRequestUpdateEvent extends Event { - updateWith(d: Promise): void; + updateWith(detailsPromise: Promise): void; } declare var PaymentRequestUpdateEvent: { @@ -8811,6 +9790,7 @@ interface PaymentResponse { readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; + readonly requestId: string; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; @@ -8822,16 +9802,50 @@ declare var PaymentResponse: { new(): PaymentResponse; }; +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 Performance { + /** @deprecated */ readonly navigation: PerformanceNavigation; + readonly timeOrigin: number; + /** @deprecated */ 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; + getEntriesByName(name: string, type?: string): any; + getEntriesByType(type: string): any; + /** @deprecated */ getMarks(markName?: string): any; + /** @deprecated */ getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; @@ -8850,6 +9864,7 @@ interface PerformanceEntry { readonly entryType: string; readonly name: string; readonly startTime: number; + toJSON(): any; } declare var PerformanceEntry: { @@ -8893,28 +9908,41 @@ declare var PerformanceNavigation: { }; interface PerformanceNavigationTiming extends PerformanceEntry { + /** @deprecated */ readonly connectEnd: number; + /** @deprecated */ readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; + /** @deprecated */ readonly domLoading: number; + /** @deprecated */ + readonly domainLookupEnd: number; + /** @deprecated */ + readonly domainLookupStart: number; + /** @deprecated */ readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; + /** @deprecated */ readonly navigationStart: number; readonly redirectCount: number; + /** @deprecated */ readonly redirectEnd: number; + /** @deprecated */ readonly redirectStart: number; + /** @deprecated */ readonly requestStart: number; + /** @deprecated */ readonly responseEnd: number; + /** @deprecated */ readonly responseStart: number; readonly type: NavigationType; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly workerStart: number; } declare var PerformanceNavigationTiming: { @@ -8934,6 +9962,7 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly workerStart: number; } declare var PerformanceResourceTiming: { @@ -8944,13 +9973,13 @@ declare var 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 domainLookupEnd: number; + readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -8961,9 +9990,9 @@ interface PerformanceTiming { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly secureConnectionStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; - readonly secureConnectionStart: number; toJSON(): any; } @@ -8972,35 +10001,6 @@ declare var 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 { } @@ -9082,12 +10082,11 @@ declare var 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; + new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent; }; interface Position { @@ -9135,10 +10134,21 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; + new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent; }; +interface PromiseRejectionEvent extends Event { + readonly promise: PromiseLike; + readonly reason: any; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: PromiseLike; + reason?: any; +} + interface PushManager { + readonly supportedContentEncodings: ReadonlyArray; getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; subscribe(options?: PushSubscriptionOptionsInit): Promise; @@ -9150,7 +10160,8 @@ declare var PushManager: { }; interface PushSubscription { - readonly endpoint: USVString; + readonly endpoint: string; + readonly expirationTime: number | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): any; @@ -9172,112 +10183,13 @@ declare var 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 | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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; +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } -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; - readonly signal: AbortSignal; - 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; +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDtlsTransportEventMap { @@ -9323,7 +10235,7 @@ interface RTCDtmfSender extends EventTarget { readonly canInsertDTMF: boolean; readonly duration: number; readonly interToneGap: number; - ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null; readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; @@ -9338,19 +10250,10 @@ declare var 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; + sdpMid: string | null; toJSON(): any; } @@ -9455,28 +10358,28 @@ interface RTCPeerConnection extends EventTarget { 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; + onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null; + oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; + onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; readonly remoteDescription: RTCSessionDescription | null; readonly signalingState: RTCSignalingState; - addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise; addStream(stream: MediaStream): void; close(): void; - createAnswer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - createOffer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, options?: RTCOfferOptions): Promise; + createAnswer(options?: RTCOfferOptions): Promise; + createOffer(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; + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit): 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; @@ -9499,10 +10402,14 @@ declare var RTCPeerConnectionIceEvent: { interface RTCRtpReceiverEventMap { "error": Event; + "msdecodercapacitychange": Event; + "msdsh": Event; } interface RTCRtpReceiver extends RTCStatsProvider { onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9599,433 +10506,122 @@ declare var RTCStatsProvider: { new(): RTCStatsProvider; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; +interface RandomSource { + getRandomValues(array: T): T; } -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; +declare var RandomSource: { + prototype: RandomSource; + new(): RandomSource; }; -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; - lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; - unlockOrientation(): 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; +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 | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + insertNode(node: Node): void; + isPointInRange(node: Node, offset: number): boolean; + selectNode(node: Node): void; + selectNodeContents(node: Node): void; + setEnd(node: Node, offset: number): void; + setEndAfter(node: Node): void; + setEndBefore(node: Node): void; + setStart(node: Node, offset: number): void; + setStartAfter(node: Node): void; + setStartBefore(node: 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 Selection: { - prototype: Selection; - new(): Selection; +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 ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -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; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; }; -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } -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; +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; }; -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 { +interface Request extends 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 signal: AbortSignal | null; + readonly type: RequestType; readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; + clone(): Request; } -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; }; -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; +interface Response extends Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; } -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; +declare var Response: { + prototype: Response; + new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; }; interface SVGAElement extends SVGGraphicsElement, SVGURIReference { @@ -10145,6 +10741,11 @@ declare var SVGAnimatedNumberList: { new(): SVGAnimatedNumberList; }; +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; readonly baseVal: SVGPreserveAspectRatio; @@ -10281,21 +10882,21 @@ interface SVGElementEventMap extends ElementEventMap { "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; +interface SVGElement extends Element, ElementCSSInlineStyle { + readonly className: any; + onclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null; + onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null; + onload: ((this: SVGElement, ev: Event) => any) | null; + onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null; + readonly ownerSVGElement: SVGSVGElement | null; + readonly viewportElement: SVGElement | null; + /** @deprecated */ 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; @@ -10325,7 +10926,9 @@ declare var SVGElementInstance: { }; interface SVGElementInstanceList { + /** @deprecated */ readonly length: number; + /** @deprecated */ item(index: number): SVGElementInstance; } @@ -10808,7 +11411,9 @@ declare var SVGFETurbulenceElement: { }; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { + /** @deprecated */ readonly filterResX: SVGAnimatedInteger; + /** @deprecated */ readonly filterResY: SVGAnimatedInteger; readonly filterUnits: SVGAnimatedEnumeration; readonly height: SVGAnimatedLength; @@ -10816,6 +11421,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + /** @deprecated */ 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; @@ -10828,6 +11434,19 @@ declare var SVGFilterElement: { new(): SVGFilterElement; }; +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 SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; readonly width: SVGAnimatedLength; @@ -10880,12 +11499,15 @@ declare var SVGGradientElement: { }; interface SVGGraphicsElement extends SVGElement, SVGTests { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; + /** @deprecated */ + readonly farthestViewportElement: SVGElement | null; + /** @deprecated */ + readonly nearestViewportElement: SVGElement | null; readonly transform: SVGAnimatedTransformList; getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; + getCTM(): SVGMatrix | null; + getScreenCTM(): SVGMatrix | null; + /** @deprecated */ 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; @@ -10967,22 +11589,6 @@ declare var 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; @@ -10999,6 +11605,22 @@ declare var SVGLineElement: { new(): SVGLineElement; }; +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 SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -11009,12 +11631,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: 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; @@ -11024,12 +11646,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; }; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { @@ -11113,26 +11735,47 @@ declare var SVGNumberList: { }; interface SVGPathElement extends SVGGraphicsElement { + /** @deprecated */ readonly pathSegList: SVGPathSegList; + /** @deprecated */ createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + /** @deprecated */ createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + /** @deprecated */ createSVGPathSegClosePath(): SVGPathSegClosePath; + /** @deprecated */ createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + /** @deprecated */ createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + /** @deprecated */ createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + /** @deprecated */ createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + /** @deprecated */ createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + /** @deprecated */ createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + /** @deprecated */ createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + /** @deprecated */ getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; @@ -11578,6 +12221,84 @@ declare var SVGRectElement: { new(): SVGRectElement; }; +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + contentScriptType: string; + /** @deprecated */ + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: ((this: SVGSVGElement, ev: Event) => any) | null; + onerror: ((this: SVGSVGElement, ev: Event) => any) | null; + onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onunload: ((this: SVGSVGElement, ev: Event) => any) | null; + onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; + /** @deprecated */ + readonly pixelUnitToMillimeterX: number; + /** @deprecated */ + readonly pixelUnitToMillimeterY: number; + /** @deprecated */ + readonly screenPixelToMillimeterX: number; + /** @deprecated */ + readonly screenPixelToMillimeterY: number; + /** @deprecated */ + 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; + /** @deprecated */ + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + /** @deprecated */ + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + /** @deprecated */ + pauseAnimations(): void; + /** @deprecated */ + setCurrentTime(seconds: number): void; + /** @deprecated */ + suspendRedraw(maxWaitMilliseconds: number): number; + /** @deprecated */ + unpauseAnimations(): void; + /** @deprecated */ + unsuspendRedraw(suspendHandleID: number): void; + /** @deprecated */ + 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 SVGScriptElement extends SVGElement, SVGURIReference { type: string; addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -11620,6 +12341,15 @@ declare var SVGStringList: { new(): SVGStringList; }; +interface SVGStylable { + className: any; +} + +declare var SVGStylable: { + prototype: SVGStylable; + new(): SVGStylable; +}; + interface SVGStyleElement extends SVGElement { disabled: boolean; media: string; @@ -11636,69 +12366,6 @@ declare var 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; @@ -11723,6 +12390,27 @@ declare var SVGSymbolElement: { new(): SVGSymbolElement; }; +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 SVGTests { + readonly requiredExtensions: SVGStringList; + /** @deprecated */ + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + /** @deprecated */ + hasExtension(extension: string): boolean; +} + interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; readonly textLength: SVGAnimatedLength; @@ -11869,18 +12557,10 @@ declare var 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; +interface SVGURIReference { + readonly href: SVGAnimatedString; } -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -}; - interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11889,9 +12569,9 @@ interface SVGUnitTypes { declare var SVGUnitTypes: SVGUnitTypes; interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; + readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; + readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -11906,7 +12586,8 @@ declare var SVGUseElement: { new(): SVGUseElement; }; -interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { +interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ 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; @@ -11942,6 +12623,477 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; +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; + /** @deprecated */ + 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) | null; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + unlockOrientation(): 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 ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + /** @deprecated */ + readonly bufferSize: number; + /** @deprecated */ + onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null; + 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 ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEvent extends Event { + readonly blockedURI: string; + readonly columnNumber: number; + readonly documentURI: string; + readonly effectiveDirective: string; + readonly lineNumber: number; + readonly originalPolicy: string; + readonly referrer: string; + readonly sourceFile: string; + readonly statusCode: number; + readonly violatedDirective: string; +} + +declare var SecurityPolicyViolationEvent: { + prototype: SecurityPolicyViolationEvent; + new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent; +}; + +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 ServiceUIFrameContext { + getCachedFrameMessage(key: string): string; + postFrameMessage(key: string, data: string): void; +} +declare var ServiceUIFrameContext: ServiceUIFrameContext; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + 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; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): 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: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | 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) | null; + readonly pushManager: PushManager; + readonly scope: string; + 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 ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: "open" | "closed"; +} + +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 | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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) | null; + 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 charLength: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance; +} + +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) | null; + onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + 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(): 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, value: string): void; + [key: string]: any; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + readonly key: string | null; + readonly newValue: string | null; + readonly oldValue: string | null; + readonly storageArea: Storage | null; + readonly url: string; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StorageEventInit extends EventInit { + key?: string; + newValue?: string; + oldValue?: string; + storageArea?: Storage; + url: string; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string | null; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet | null; + readonly title: string | null; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index: number): StyleSheet | null; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SyncManager { getTags(): Promise; register(tag: string): Promise; @@ -11953,8 +13105,8 @@ declare var SyncManager: { }; interface Text extends CharacterData { - readonly wholeText: string; readonly assignedSlot: HTMLSlotElement | null; + readonly wholeText: string; splitText(offset: number): Text; } @@ -11963,10 +13115,30 @@ declare var Text: { new(data?: string): Text; }; +interface TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + 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; @@ -12017,10 +13189,10 @@ interface TextTrack extends EventTarget { 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; + mode: TextTrackMode | number; + oncuechange: ((this: TextTrack, ev: Event) => any) | null; + onerror: ((this: TextTrack, ev: Event) => any) | null; + onload: ((this: TextTrack, ev: Event) => any) | null; readonly readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; @@ -12057,8 +13229,8 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { endTime: number; id: string; - onenter: (this: TextTrackCue, ev: Event) => any; - onexit: (this: TextTrackCue, ev: Event) => any; + onenter: ((this: TextTrackCue, ev: Event) => any) | null; + onexit: ((this: TextTrackCue, ev: Event) => any) | null; pauseOnExit: boolean; startTime: number; text: string; @@ -12144,6 +13316,7 @@ interface TouchEvent extends UIEvent { readonly shiftKey: boolean; readonly targetTouches: TouchList; readonly touches: TouchList; + /** @deprecated */ readonly which: number; } @@ -12152,6 +13325,12 @@ declare var TouchEvent: { new(type: string, touchEventInit?: TouchEventInit): TouchEvent; }; +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + interface TouchList { readonly length: number; item(index: number): Touch | null; @@ -12185,17 +13364,18 @@ declare var TransitionEvent: { interface TreeWalker { currentNode: Node; + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; + firstChild(): Node | null; + lastChild(): Node | null; + nextNode(): Node | null; + nextSibling(): Node | null; + parentNode(): Node | null; + previousNode(): Node | null; + previousSibling(): Node | null; } declare var TreeWalker: { @@ -12214,15 +13394,6 @@ declare var 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; @@ -12234,8 +13405,8 @@ interface URL { port: string; protocol: string; search: string; - username: string; readonly searchParams: URLSearchParams; + username: string; toString(): string; } @@ -12246,6 +13417,142 @@ declare var URL: { revokeObjectURL(url: string): 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; + new (init?: string | URLSearchParams): URLSearchParams; +}; + +interface VRDisplay extends EventTarget { + readonly capabilities: VRDisplayCapabilities; + depthFar: number; + depthNear: number; + readonly displayId: number; + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + readonly stageParameters: VRStageParameters | null; + cancelAnimationFrame(handle: number): void; + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + getFrameData(frameData: VRFrameData): boolean; + getLayers(): VRLayer[]; + /** @deprecated */ + getPose(): VRPose; + requestAnimationFrame(callback: FrameRequestCallback): number; + requestPresent(layers: VRLayer[]): Promise; + resetPose(): void; + submitFrame(pose?: VRPose): void; +} + +declare var VRDisplay: { + prototype: VRDisplay; + new(): VRDisplay; +}; + +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} + +declare var VRDisplayCapabilities: { + prototype: VRDisplayCapabilities; + new(): VRDisplayCapabilities; +}; + +interface VRDisplayEvent extends Event { + readonly display: VRDisplay; + readonly reason: VRDisplayEventReason | null; +} + +declare var VRDisplayEvent: { + prototype: VRDisplayEvent; + new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent; +}; + +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} + +declare var VREyeParameters: { + prototype: VREyeParameters; + new(): VREyeParameters; +}; + +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} + +declare var VRFieldOfView: { + prototype: VRFieldOfView; + new(): VRFieldOfView; +}; + +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} + +declare var VRFrameData: { + prototype: VRFrameData; + new(): VRFrameData; +}; + +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} + +declare var VRPose: { + prototype: VRPose; + new(): VRPose; +}; + interface ValidityState { readonly badInput: boolean; readonly customError: boolean; @@ -12254,10 +13561,10 @@ interface ValidityState { readonly rangeUnderflow: boolean; readonly stepMismatch: boolean; readonly tooLong: boolean; + readonly tooShort: boolean; readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; - readonly tooShort: boolean; } declare var ValidityState: { @@ -12300,9 +13607,9 @@ interface VideoTrackListEventMap { 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; + onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: VideoTrackList, ev: Event) => any) | null; + onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; @@ -12318,6 +13625,137 @@ declare var VideoTrackList: { new(): VideoTrackList; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly RGB32F_EXT: number; + readonly RGBA32F_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + 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_SRGB8_ALPHA8_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_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; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +}; + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_SRGB_S3TC_DXT1_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_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +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 WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_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 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 DRAW_BUFFER0_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 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 MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + interface WaveShaperNode extends AudioNode { curve: Float32Array | null; oversample: OverSampleType; @@ -12329,8 +13767,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -12350,44 +13788,6 @@ declare var 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; @@ -12464,8 +13864,8 @@ interface WebGLRenderingContext { 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; + bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void; + bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void; checkFramebufferStatus(target: number): number; clear(mask: number): void; clearColor(red: number, green: number, blue: number, alpha: number): void; @@ -12473,8 +13873,8 @@ interface WebGLRenderingContext { 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; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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; @@ -12564,7 +13964,7 @@ interface WebGLRenderingContext { 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; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | 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; @@ -12729,13 +14129,13 @@ interface WebGLRenderingContext { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12760,9 +14160,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12792,18 +14192,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -12837,20 +14237,6 @@ interface WebGLRenderingContext { 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; @@ -12883,9 +14269,23 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13031,13 +14431,13 @@ declare var WebGLRenderingContext: { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -13062,9 +14462,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -13094,18 +14494,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -13139,20 +14539,6 @@ declare var WebGLRenderingContext: { 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; @@ -13185,9 +14571,23 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13248,6 +14648,9 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; +interface WebGLVertexArrayObjectOES { +} + interface WebKitCSSMatrix { a: number; b: number; @@ -13348,18 +14751,6 @@ declare var 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; @@ -13368,18 +14759,18 @@ interface WebSocketEventMap { } interface WebSocket extends EventTarget { - binaryType: string; + binaryType: BinaryType; 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; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; readonly protocol: string; readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: USVString | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; @@ -13424,8 +14815,6 @@ declare var WheelEvent: { interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "afterprint": Event; - "beforeprint": Event; "beforeunload": BeforeUnloadEvent; "blur": FocusEvent; "canplay": Event; @@ -13447,7 +14836,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; @@ -13469,21 +14858,21 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "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; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -13513,19 +14902,32 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "touchstart": TouchEvent; "unload": Event; "volumechange": Event; + "vrdisplayactivate": Event; + "vrdisplayblur": Event; + "vrdisplayconnect": Event; + "vrdisplaydeactivate": Event; + "vrdisplaydisconnect": Event; + "vrdisplayfocus": Event; + "vrdisplaypointerrestricted": Event; + "vrdisplaypointerunrestricted": Event; + "vrdisplaypresentchange": Event; "waiting": Event; } interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { + Blob: typeof Blob; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; readonly applicationCache: ApplicationCache; readonly caches: CacheStorage; readonly clientInformation: Navigator; readonly closed: boolean; readonly crypto: Crypto; + customElements: CustomElementRegistry; defaultStatus: string; readonly devicePixelRatio: number; - readonly document: Document; readonly doNotTrack: string; + readonly document: Document; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13535,7 +14937,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly innerWidth: number; readonly isSecureContext: boolean; readonly length: number; - readonly location: Location; + location: Location; readonly locationbar: BarProp; readonly menubar: BarProp; readonly msContentScript: ExtensionScriptApis; @@ -13543,99 +14945,106 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + onabort: ((this: Window, ev: UIEvent) => any) | null; + onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; + onblur: ((this: Window, ev: FocusEvent) => any) | null; + oncanplay: ((this: Window, ev: Event) => any) | null; + oncanplaythrough: ((this: Window, ev: Event) => any) | null; + onchange: ((this: Window, ev: Event) => any) | null; + onclick: ((this: Window, ev: MouseEvent) => any) | null; + oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; + oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; + ondblclick: ((this: Window, ev: MouseEvent) => any) | null; + ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; + ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; + ondrag: ((this: Window, ev: DragEvent) => any) | null; + ondragend: ((this: Window, ev: DragEvent) => any) | null; + ondragenter: ((this: Window, ev: DragEvent) => any) | null; + ondragleave: ((this: Window, ev: DragEvent) => any) | null; + ondragover: ((this: Window, ev: DragEvent) => any) | null; + ondragstart: ((this: Window, ev: DragEvent) => any) | null; + ondrop: ((this: Window, ev: DragEvent) => any) | null; + ondurationchange: ((this: Window, ev: Event) => any) | null; + onemptied: ((this: Window, ev: Event) => any) | null; + onended: ((this: Window, ev: Event) => any) | null; 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; + onfocus: ((this: Window, ev: FocusEvent) => any) | null; + onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; + oninput: ((this: Window, ev: Event) => any) | null; + oninvalid: ((this: Window, ev: Event) => any) | null; + onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; + onload: ((this: Window, ev: Event) => any) | null; + onloadeddata: ((this: Window, ev: Event) => any) | null; + onloadedmetadata: ((this: Window, ev: Event) => any) | null; + onloadstart: ((this: Window, ev: Event) => any) | null; + onmessage: ((this: Window, ev: MessageEvent) => any) | null; + onmousedown: ((this: Window, ev: MouseEvent) => any) | null; + onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; + onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; + onmousemove: ((this: Window, ev: MouseEvent) => any) | null; + onmouseout: ((this: Window, ev: MouseEvent) => any) | null; + onmouseover: ((this: Window, ev: MouseEvent) => any) | null; + onmouseup: ((this: Window, ev: MouseEvent) => any) | null; + onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; + onmsgesturechange: ((this: Window, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; + onmsgestureend: ((this: Window, ev: Event) => any) | null; + onmsgesturehold: ((this: Window, ev: Event) => any) | null; + onmsgesturestart: ((this: Window, ev: Event) => any) | null; + onmsgesturetap: ((this: Window, ev: Event) => any) | null; + onmsinertiastart: ((this: Window, ev: Event) => any) | null; + onmspointercancel: ((this: Window, ev: Event) => any) | null; + onmspointerdown: ((this: Window, ev: Event) => any) | null; + onmspointerenter: ((this: Window, ev: Event) => any) | null; + onmspointerleave: ((this: Window, ev: Event) => any) | null; + onmspointermove: ((this: Window, ev: Event) => any) | null; + onmspointerout: ((this: Window, ev: Event) => any) | null; + onmspointerover: ((this: Window, ev: Event) => any) | null; + onmspointerup: ((this: Window, ev: Event) => any) | null; + onoffline: ((this: Window, ev: Event) => any) | null; + ononline: ((this: Window, ev: Event) => any) | null; + onorientationchange: ((this: Window, ev: Event) => any) | null; + onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpause: ((this: Window, ev: Event) => any) | null; + onplay: ((this: Window, ev: Event) => any) | null; + onplaying: ((this: Window, ev: Event) => any) | null; + onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; + onprogress: ((this: Window, ev: ProgressEvent) => any) | null; + onratechange: ((this: Window, ev: Event) => any) | null; + onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; + onreset: ((this: Window, ev: Event) => any) | null; + onresize: ((this: Window, ev: UIEvent) => any) | null; + onscroll: ((this: Window, ev: UIEvent) => any) | null; + onseeked: ((this: Window, ev: Event) => any) | null; + onseeking: ((this: Window, ev: Event) => any) | null; + onselect: ((this: Window, ev: UIEvent) => any) | null; + onstalled: ((this: Window, ev: Event) => any) | null; + onstorage: ((this: Window, ev: StorageEvent) => any) | null; + onsubmit: ((this: Window, ev: Event) => any) | null; + onsuspend: ((this: Window, ev: Event) => any) | null; + ontimeupdate: ((this: Window, ev: Event) => any) | null; 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; + onunload: ((this: Window, ev: Event) => any) | null; + onvolumechange: ((this: Window, ev: Event) => any) | null; + onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplayblur: ((this: Window, ev: Event) => any) | null; + onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + onwaiting: ((this: Window, ev: Event) => any) | null; + readonly opener: any; + readonly orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; readonly pageXOffset: number; @@ -13648,9 +15057,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; - readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; + readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13659,20 +15068,18 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + 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; departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; getSelection(): Selection; matchMedia(mediaQuery: string): MediaQueryList; moveBy(x?: number, y?: number): void; @@ -13686,19 +15093,17 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window requestAnimationFrame(callback: FrameRequestCallback): number; resizeBy(x?: number, y?: number): void; resizeTo(x?: number, y?: number): void; + scroll(options?: ScrollToOptions): void; scroll(x?: number, y?: number): void; + scrollBy(options?: ScrollToOptions): void; scrollBy(x?: number, y?: number): void; + scrollTo(options?: ScrollToOptions): 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; @@ -13710,12 +15115,79 @@ declare var Window: { new(): Window; }; +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowEventHandlersEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "hashchange": HashChangeEvent; + "message": MessageEvent; + "offline": Event; + "online": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface WindowEventHandlers { + onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; + onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; + ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; + onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers extends 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 WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; } interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: Worker, ev: MessageEvent) => any; + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** @deprecated */ postMessage(message: any, transfer?: any[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -13729,6 +15201,41 @@ declare var Worker: { new(stringUrl: string): Worker; }; +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +declare var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; +}; + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: any): Promise; +} + +declare var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(): WritableStreamDefaultWriter; +}; + 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; @@ -13746,7 +15253,8 @@ interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -13758,15 +15266,12 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { 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; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): 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; @@ -13790,6 +15295,30 @@ declare var XMLHttpRequest: { readonly UNSENT: 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) | null; + onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + 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 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; @@ -13893,1070 +15422,16 @@ declare var 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; +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: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[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 ElementCreationOptions { - is?: 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 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; -} - -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 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; - 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; -} - -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; -} - -interface AnimationKeyFrame { - offset?: number | null | (number | null)[]; - easing?: string | string[]; - [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; -} - -interface AnimationOptions { - id?: string; - delay?: number; - direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; - duration?: number; - easing?: string; - endDelay?: number; - fill?: "none" | "forwards" | "backwards" | "both"| "auto"; - iterationStart?: number; - iterations?: number; -} - -interface AnimationTimeline { - readonly currentTime: number | null; -} - -interface ComputedTimingProperties { - endTime: number; - activeDuration: number; - localTime: number | null; - progress: number | null; - currentIteration: number | null; -} - -interface AnimationEffectReadOnly { - readonly timing: number; - getComputedTiming(): ComputedTimingProperties; -} - -interface AnimationPlaybackEventInit extends EventInit { - currentTime?: number | null; - timelineTime?: number | null; -} - -interface AnimationPlaybackEvent extends Event { - readonly currentTime: number | null; - readonly timelineTime: number | null; -} - -declare var AnimationPlaybackEvent: { - prototype: AnimationPlaybackEvent; - new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; -}; - -interface Animation { - currentTime: number | null; - effect: AnimationEffectReadOnly; - readonly finished: Promise; - id: string; - readonly pending: boolean; - readonly playState: "idle" | "running" | "paused" | "finished"; - playbackRate: number; - readonly ready: Promise; - startTime: number; - timeline: AnimationTimeline; - oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; - onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; - cancel(): void; - finish(): void; - pause(): void; - play(): void; - reverse(): void; -} - -declare var Animation: { - prototype: Animation; - new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; }; declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; @@ -14964,66 +15439,95 @@ declare type EventListenerOrEventListenerObject = EventListener | EventListenerO interface DecodeErrorCallback { (error: DOMException): void; } + interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } + interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; } + +interface EventHandlerNonNull { + (event: Event): any; +} + interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, 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 MediaQueryListListener { + (mql: MediaQueryList): void; } + 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 WritableStreamChunkCallback { + (chunk: any, controller: WritableStreamDefaultController): void; +} + +interface WritableStreamDefaultControllerCallback { + (controller: WritableStreamDefaultController): void; +} + +interface WritableStreamErrorCallback { + (reason: string): void; +} + interface HTMLElementTagNameMap { "a": HTMLAnchorElement; "abbr": HTMLElement; @@ -15150,7 +15654,6 @@ interface HTMLElementTagNameMap { "var": HTMLElement; "video": HTMLVideoElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } @@ -15213,18 +15716,28 @@ interface SVGElementTagNameMap { /** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ 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 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 Blob: typeof Blob; +declare var URL: typeof URL; +declare var URLSearchParams: typeof URLSearchParams; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; declare var closed: boolean; declare var crypto: Crypto; +declare var customElements: CustomElementRegistry; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var document: Document; declare var doNotTrack: string; +declare var document: Document; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -15242,97 +15755,104 @@ 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 onabort: ((this: Window, ev: UIEvent) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +declare var onchange: ((this: Window, ev: Event) => any) | null; +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; +declare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; +declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +declare var onemptied: ((this: Window, ev: Event) => any) | null; +declare var onended: ((this: Window, ev: Event) => any) | null; 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 onfocus: ((this: Window, ev: FocusEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onload: ((this: Window, ev: Event) => any) | null; +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadstart: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; +declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; +declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; +declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; +declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; +declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; +declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; +declare var onmspointermove: ((this: Window, ev: Event) => any) | null; +declare var onmspointerout: ((this: Window, ev: Event) => any) | null; +declare var onmspointerover: ((this: Window, ev: Event) => any) | null; +declare var onmspointerup: ((this: Window, ev: Event) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onorientationchange: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpause: ((this: Window, ev: Event) => any) | null; +declare var onplay: ((this: Window, ev: Event) => any) | null; +declare var onplaying: ((this: Window, ev: Event) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onratechange: ((this: Window, ev: Event) => any) | null; +declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onseeked: ((this: Window, ev: Event) => any) | null; +declare var onseeking: ((this: Window, ev: Event) => any) | null; +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; 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 onunload: ((this: Window, ev: Event) => any) | null; +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; +declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; @@ -15347,9 +15867,9 @@ 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 scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -15358,17 +15878,18 @@ 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 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 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 getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; declare function getSelection(): Selection; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; @@ -15382,23 +15903,21 @@ 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(options?: ScrollToOptions): void; declare function scroll(x?: number, y?: number): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(options?: ScrollToOptions): 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 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; @@ -15409,26 +15928,36 @@ 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 onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; 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 fetch(input?: Request | string, 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 ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type IDBValidKey = number | string | Date | IDBArrayKey; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = Blob | BufferSource | FormData | string; +type MutationRecordType = "attributes" | "characterData" | "childList"; +type AAGUID = string; +type BodyInit = any; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; @@ -15450,9 +15979,6 @@ 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; @@ -15461,35 +15987,32 @@ 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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type AppendMode = "segments" | "sequence"; +type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "suspended" | "running" | "closed"; +type BinaryType = "blob" | "arraybuffer"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanPlayTypeResult = "" | "maybe" | "probably"; type CanvasFillRule = "nonzero" | "evenodd"; type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; +type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; +type EndOfStreamError = "network" | "decode"; type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; +type GamepadHand = "" | "left" | "right"; +type GamepadHapticActuatorType = "vibration"; type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type GamepadMappingType = "" | "standard"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; 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"; @@ -15497,25 +16020,23 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaStreamTrackState = "live" | "ended"; 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 PanningModelType = "equalpower" | "HRTF"; +type PaymentComplete = "success" | "fail" | "unknown"; 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"; @@ -15523,9 +16044,9 @@ 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 RTCIceGatherPolicy = "all" | "nohost" | "relay"; 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"; @@ -15536,9 +16057,22 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " 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 ReadyState = "closed" | "open" | "ended"; +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 ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; +type TextTrackMode = "disabled" | "hidden" | "showing"; type Transport = "usb" | "nfc" | "ble"; +type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; +type VREye = "left" | "right"; type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/lib.es2018.promise.d.ts b/lib/lib.es2018.promise.d.ts new file mode 100644 index 00000000000..d73b4d45688 --- /dev/null +++ b/lib/lib.es2018.promise.d.ts @@ -0,0 +1,32 @@ +/*! ***************************************************************************** +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. +***************************************************************************** */ + + + +/// + + +/** + * 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/lib/lib.es2018.regexp.d.ts b/lib/lib.es2018.regexp.d.ts new file mode 100644 index 00000000000..0c3358ef6af --- /dev/null +++ b/lib/lib.es2018.regexp.d.ts @@ -0,0 +1,31 @@ +/*! ***************************************************************************** +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 RegExpMatchArray { + groups?: { + [key: string]: string + } +} + +interface RegExpExecArray { + groups?: { + [key: string]: string + } +} \ No newline at end of file diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 5275940aa24..132323e4eb8 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -5866,7 +5866,6 @@ interface ArrayBufferConstructor { readonly [Symbol.species]: ArrayBufferConstructor; } - ///////////////////////////// /// DOM APIs ///////////////////////////// @@ -5879,10 +5878,49 @@ interface Account { rpDisplayName: string; } +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + interface Algorithm { name: string; } +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + interface AnimationEventInit extends EventInit { animationName?: string; elapsedTime?: number; @@ -5891,10 +5929,71 @@ interface AnimationEventInit extends EventInit { interface AssertionOptions { allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioContextInfo { + currentTime?: number; + sampleRate?: number; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioParamDescriptor { + defaultValue?: number; + maxValue?: number; + minValue?: number; + name?: string; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: number; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface ByteLengthChunk { + byteLength?: number; +} + interface CacheQueryOptions { cacheName?: string; ignoreMethod?: boolean; @@ -5902,6 +6001,14 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + interface ClientData { challenge: string; extensions?: WebAuthnExtensions; @@ -5911,6 +6018,12 @@ interface ClientData { tokenBinding?: string; } +interface ClientQueryOptions { + includeReserved?: boolean; + includeUncontrolled?: boolean; + type?: ClientTypes; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; @@ -5925,6 +6038,10 @@ interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation arrayOfDomainStrings?: string[]; } +interface ConstantSourceOptions { + offset?: number; +} + interface ConstrainBooleanParameters { exact?: boolean; ideal?: boolean; @@ -5950,10 +6067,27 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + interface CustomEventInit extends EventInit { detail?: T; } +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + interface DeviceAccelerationDict { x?: number | null; y?: number | null; @@ -5984,18 +6118,39 @@ interface DeviceRotationRateDict { gamma?: number | null; } -interface DOMRectInit { - height?: number; - width?: number; - x?: number; - y?: number; -} - interface DoubleRange { max?: number; min?: number; } +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: string; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: string | Algorithm; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -6005,9 +6160,13 @@ interface ErrorEventInit extends EventInit { } interface EventInit { - scoped?: boolean; bubbles?: boolean; cancelable?: boolean; + scoped?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; } interface EventModifierInit extends UIEventInit { @@ -6032,6 +6191,24 @@ interface ExceptionInformation { domain?: string | null; } +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: object | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + request: Request; + reservedClientId?: string; + targetClientId?: string; +} + interface FocusEventInit extends UIEventInit { relatedTarget?: EventTarget | null; } @@ -6051,8 +6228,12 @@ interface FocusNavigationOrigin { originWidth?: number; } +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + interface GamepadEventInit extends EventInit { - gamepad?: Gamepad | null; + gamepad?: Gamepad; } interface GetNotificationOptions { @@ -6060,8 +6241,29 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string | null; - oldURL?: string | null; + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: string | Algorithm; + info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface HmacImportParams extends Algorithm { + hash: string | Algorithm; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: string | Algorithm; + length?: number; } interface IDBIndexParameters { @@ -6074,10 +6276,15 @@ interface IDBObjectStoreParameters { keyPath?: string | string[]; } +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + interface IntersectionObserverEntryInit { - isIntersecting: boolean; boundingClientRect: DOMRectInit; intersectionRect: DOMRectInit; + isIntersecting: boolean; rootBounds: DOMRectInit; target: Element; time: number; @@ -6089,8 +6296,29 @@ interface IntersectionObserverInit { threshold?: number | number[]; } +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + interface KeyAlgorithm { - name?: string; + name: string; } interface KeyboardEventInit extends EventModifierInit { @@ -6105,125 +6333,6 @@ interface LongRange { 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; @@ -6314,6 +6423,16 @@ interface MSCredentialSpec { type: MSCredentialType; } +interface MSDCCEventInit extends EventInit { + maxFr?: number; + maxFs?: number; +} + +interface MSDSHEventInit extends EventInit { + sources?: number[]; + timestamp?: number; +} + interface MSDelay { roundTrip?: number; roundTripMax?: number; @@ -6331,7 +6450,13 @@ interface MSDescription extends RTCStats { interface MSFIDOCredentialParameters extends MSCredentialParameters { algorithm?: string | Algorithm; - authenticators?: AAGUID[]; + authenticators?: string[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSIceWarningFlags { @@ -6359,12 +6484,6 @@ interface MSIceWarningFlags { useCandidateChecksFailed?: boolean; } -interface MSIPAddressInfo { - ipAddr?: string; - manufacturerMacAddrMask?: string; - port?: number; -} - interface MSJitter { interArrival?: number; interArrivalMax?: number; @@ -6393,8 +6512,8 @@ interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; - interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; + interfaceTypeWireless?: boolean; } interface MSOutboundNetwork extends MSNetwork { @@ -6431,8 +6550,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { iceRole?: RTCIceRole; iceWarningFlags?: MSIceWarningFlags; interfaces?: MSNetworkInterfaceType; - localAddress?: string; localAddrType?: MSIceAddrType; + localAddress?: string; localInterface?: MSNetworkInterfaceType; localMR?: string; localMRTCPPort?: number; @@ -6446,8 +6565,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { portRangeMax?: number; portRangeMin?: number; protocol?: RTCIceProtocol; - remoteAddress?: string; remoteAddrType?: MSIceAddrType; + remoteAddress?: string; remoteMR?: string; remoteMRTCPPort?: number; remoteSite?: string; @@ -6516,6 +6635,133 @@ interface MSVideoSendPayload extends MSVideoPayload { sendVideoStreamsMax?: number; } +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +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 MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + channelCount?: number | ConstrainLongRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + displaySurface?: string | string[] | ConstrainDOMStringParameters; + echoCancellation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + latency?: number | ConstrainDoubleRange; + logicalSurface?: boolean | ConstrainBooleanParameters; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +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 { + channel?: string; + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: Window | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + interface MsZoomToOptions { animate?: string; contentX?: number; @@ -6535,8 +6781,14 @@ interface MutationObserverInit { subtree?: boolean; } +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; +} + interface NotificationOptions { body?: string; + data?: any; dir?: NotificationDirection; icon?: string; lang?: string; @@ -6547,18 +6799,49 @@ interface ObjectURLOptions { oneTimeOnly?: boolean; } +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + interface PaymentCurrencyAmount { currency: string; currencySystem?: string; value: string; } -interface PaymentDetails { +interface PaymentDetailsBase { displayItems?: PaymentItem[]; - error?: string; modifiers?: PaymentDetailsModifier[]; shippingOptions?: PaymentShippingOption[]; - total?: PaymentItem; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; } interface PaymentDetailsModifier { @@ -6568,6 +6851,11 @@ interface PaymentDetailsModifier { total?: PaymentItem; } +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + total?: PaymentItem; +} + interface PaymentItem { amount: PaymentCurrencyAmount; label: string; @@ -6597,10 +6885,21 @@ interface PaymentShippingOption { selected?: boolean; } +interface Pbkdf2Params extends Algorithm { + hash: string | Algorithm; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + interface PeriodicWaveConstraints { disableNormalization?: boolean; } +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[]; + real?: number[]; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -6628,35 +6927,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface PushEventInit extends ExtendableEventInit { + data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | null; + applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; userVisibleOnly?: boolean; } -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - signal?: AbortSignal; - body?: Blob | BufferSource | FormData | string | null; - 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 QueuingStrategy { + highWaterMark?: number; + size?: WritableStreamChunkCallback; } interface RTCConfiguration { @@ -6666,6 +6953,10 @@ interface RTCConfiguration { peerIdentity?: string; } +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + interface RTCDtlsFingerprint { algorithm?: string; value?: string; @@ -6676,10 +6967,6 @@ interface RTCDtlsParameters { role?: RTCDtlsRole; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCIceCandidateAttributes extends RTCStats { addressSourceUrl?: string; candidateType?: RTCStatsIceCandidateType; @@ -6707,8 +6994,8 @@ interface RTCIceCandidateDictionary { interface RTCIceCandidateInit { candidate?: string; - sdpMid?: string; sdpMLineIndex?: number; + sdpMid?: string; } interface RTCIceCandidatePair { @@ -6763,13 +7050,13 @@ interface RTCMediaStreamTrackStats extends RTCStats { echoReturnLoss?: number; echoReturnLossEnhancement?: number; frameHeight?: number; + frameWidth?: number; framesCorrupted?: number; framesDecoded?: number; framesDropped?: number; framesPerSecond?: number; framesReceived?: number; framesSent?: number; - frameWidth?: number; remoteSource?: boolean; ssrcIds?: string[]; trackIdentifier?: string; @@ -6793,6 +7080,20 @@ interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + mediaType?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtcpFeedback { parameter?: string; type?: string; @@ -6814,9 +7115,9 @@ interface RTCRtpCapabilities { interface RTCRtpCodecCapability { clockRate?: number; kind?: string; - maxptime?: number; maxSpatialLayers?: number; maxTemporalLayers?: number; + maxptime?: number; name?: string; numChannels?: number; options?: any; @@ -6833,7 +7134,7 @@ interface RTCRtpCodecParameters { name?: string; numChannels?: number; parameters?: any; - payloadType?: any; + payloadType?: number; ptime?: number; rtcpFeedback?: RTCRtcpFeedback[]; } @@ -6892,19 +7193,6 @@ 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; @@ -6956,8 +7244,70 @@ interface RTCTransportStats extends RTCStats { selectedCandidatePairId?: string; } +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: string | Algorithm; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: string | Algorithm; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + interface ScopedCredentialDescriptor { - id: BufferSource; + id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; transports?: Transport[]; type: ScopedCredentialType; } @@ -6965,7 +7315,7 @@ interface ScopedCredentialDescriptor { interface ScopedCredentialOptions { excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } @@ -6974,6 +7324,19 @@ interface ScopedCredentialParameters { type: ScopedCredentialType; } +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; @@ -6984,11 +7347,16 @@ interface ServiceWorkerMessageEventInit extends EventInit { interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; + charLength?: number; elapsedTime?: number; name?: string; utterance?: SpeechSynthesisUtterance | null; } +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + interface StoreExceptionsInformation extends ExceptionInformation { detailURI?: string | null; explanationString?: string | null; @@ -6999,6 +7367,20 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat arrayOfDomainStrings?: string[]; } +interface SyncEventInit extends ExtendableEventInit { + lastChance?: boolean; + tag: string; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } @@ -7013,14 +7395,43 @@ interface UIEventInit extends EventInit { view?: Window | null; } +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCallback; + start: WritableStreamDefaultControllerCallback; + write?: WritableStreamChunkCallback; +} + +interface VRDisplayEventInit extends EventInit { + display: VRDisplay; + reason?: VRDisplayEventReason; +} + +interface VRLayer { + leftBounds?: number[] | null; + rightBounds?: number[] | null; + source?: HTMLCanvasElement | null; +} + +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[]; + oversample?: OverSampleType; +} + interface WebAuthnExtensions { } interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; antialias?: boolean; depth?: boolean; + failIfMajorPerformanceCaveat?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; stencil?: boolean; @@ -7047,6 +7458,67 @@ type WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMErr type WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; }; +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 AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + 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 AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -7064,23 +7536,39 @@ declare var 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; +interface Animation { + currentTime: number | null; + effect: AnimationEffectReadOnly; + readonly finished: Promise; + id: string; + readonly pending: boolean; + readonly playState: "idle" | "running" | "paused" | "finished"; + playbackRate: number; + readonly ready: Promise; + startTime: number; + timeline: AnimationTimeline; + cancel(): void; + finish(): void; + oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; + onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; + pause(): void; + play(): void; + reverse(): void; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; }; +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + 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: { @@ -7088,6 +7576,43 @@ declare var AnimationEvent: { new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; }; +interface AnimationKeyFrame { + easing?: string | string[]; + offset?: number | null | (number | null)[]; + [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; +} + +interface AnimationOptions { + delay?: number; + direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; + duration?: number; + easing?: string; + endDelay?: number; + fill?: "none" | "forwards" | "backwards" | "both"| "auto"; + id?: string; + iterationStart?: number; + iterations?: number; +} + +interface AnimationPlaybackEvent extends Event { + readonly currentTime: number | null; + readonly timelineTime: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +interface AnimationTimeline { + readonly currentTime: number | null; +} + interface ApplicationCacheEventMap { "cached": Event; "checking": Event; @@ -7100,14 +7625,14 @@ interface ApplicationCacheEventMap { } 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; + oncached: ((this: ApplicationCache, ev: Event) => any) | null; + onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + onerror: ((this: ApplicationCache, ev: Event) => any) | null; + onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; readonly status: number; abort(): void; swapCache(): void; @@ -7135,9 +7660,13 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; +interface AssignedNodesOptions { + flatten?: boolean; +} + interface Attr extends Node { readonly name: string; - readonly ownerElement: Element; + readonly ownerElement: Element | null; readonly prefix: string | null; readonly specified: boolean; value: string; @@ -7164,7 +7693,7 @@ declare var AudioBuffer: { }; interface AudioBufferSourceNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface AudioBufferSourceNode extends AudioNode { @@ -7173,7 +7702,7 @@ interface AudioBufferSourceNode extends AudioNode { loop: boolean; loopEnd: number; loopStart: number; - onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null; readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; @@ -7196,7 +7725,7 @@ interface AudioContextBase extends EventTarget { readonly currentTime: number; readonly destination: AudioDestinationNode; readonly listener: AudioListener; - onstatechange: (this: AudioContext, ev: Event) => any; + onstatechange: ((this: AudioContext, ev: Event) => any) | null; readonly sampleRate: number; readonly state: AudioContextState; close(): Promise; @@ -7246,10 +7775,15 @@ declare var AudioDestinationNode: { }; interface AudioListener { + /** @deprecated */ dopplerFactor: number; + /** @deprecated */ speedOfSound: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -7267,9 +7801,13 @@ interface AudioNode extends EventTarget { 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; + disconnect(): void; + disconnect(output: number): void; + disconnect(destination: AudioNode): void; + disconnect(destination: AudioNode, output: number): void; + disconnect(destination: AudioNode, output: number, input: number): void; + disconnect(destination: AudioParam): void; + disconnect(destination: AudioParam, output: number): void; } declare var AudioNode: { @@ -7280,12 +7818,12 @@ declare var AudioNode: { interface AudioParam { readonly defaultValue: number; value: number; - cancelScheduledValues(startTime: number): AudioParam; + cancelScheduledValues(cancelTime: 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; + setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam; } declare var AudioParam: { @@ -7326,9 +7864,9 @@ interface AudioTrackListEventMap { 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; + onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: AudioTrackList, ev: Event) => any) | null; + onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -7361,11 +7899,33 @@ declare var BeforeUnloadEvent: { new(): BeforeUnloadEvent; }; +interface BhxBrowser { + readonly lastError: DOMException; + checkMatchesGlobExpression(pattern: string, value: string): boolean; + checkMatchesUriExpression(pattern: string, value: string): boolean; + clearLastError(): void; + currentWindowId(): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + getThisAddress(): any; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericListenerHandler(eventHandler: Function): void; + setLastError(parameters: string): void; + webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void; +} + +declare var BhxBrowser: { + prototype: BhxBrowser; + new(): BhxBrowser; +}; + interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; - readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -7388,113 +7948,50 @@ declare var 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; +interface BlobPropertyBag { + endings?: string; + type?: string; } -declare var Cache: { - prototype: Cache; - new(): Cache; +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + close(): void; + postMessage(message: any): 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 CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): Promise; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; } -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -}; - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; +interface ByteLengthQueuingStrategy { + highWaterMark: number; + size(chunk?: any): number; } -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; +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -7505,190 +8002,8 @@ declare var 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 { + escape(value: string): string; supports(property: string, value?: string): boolean; } declare var CSS: CSS; @@ -7748,7 +8063,7 @@ interface CSSKeyframesRule extends CSSRule { name: string; appendRule(rule: string): void; deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; + findRule(rule: string): CSSKeyframeRule | null; } declare var CSSKeyframesRule: { @@ -7789,14 +8104,14 @@ declare var CSSPageRule: { interface CSSRule { cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; + readonly parentRule: CSSRule | null; + readonly parentStyleSheet: CSSStyleSheet | null; 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 KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -7812,8 +8127,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAME_RULE: number; readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -7825,7 +8140,7 @@ declare var CSSRule: { interface CSSRuleList { readonly length: number; - item(index: number): CSSRule; + item(index: number): CSSRule | null; [index: number]: CSSRule; } @@ -7837,8 +8152,8 @@ declare var CSSRuleList: { interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignmentBaseline: string | null; alignSelf: string | null; + alignmentBaseline: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -7914,9 +8229,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; - columns: string | null; columnSpan: string | null; columnWidth: any; + columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -7950,11 +8265,32 @@ interface CSSStyleDeclaration { fontStyle: string | null; fontVariant: string | null; fontWeight: string | null; + gap: string | null; glyphOrientationHorizontal: string | null; glyphOrientationVertical: string | null; + grid: string | null; + gridArea: string | null; + gridAutoColumns: string | null; + gridAutoFlow: string | null; + gridAutoRows: string | null; + gridColumn: string | null; + gridColumnEnd: string | null; + gridColumnGap: string | null; + gridColumnStart: string | null; + gridGap: string | null; + gridRow: string | null; + gridRowEnd: string | null; + gridRowGap: string | null; + gridRowStart: string | null; + gridTemplate: string | null; + gridTemplateAreas: string | null; + gridTemplateColumns: string | null; + gridTemplateRows: string | null; height: string | null; imeMode: string | null; justifyContent: string | null; + justifyItems: string | null; + justifySelf: string | null; kerning: string | null; layoutGrid: string | null; layoutGridChar: string | null; @@ -7981,29 +8317,30 @@ interface CSSStyleDeclaration { markerMid: string | null; markerStart: string | null; mask: string | null; + maskImage: 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; + msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumns: string | null; msGridColumnSpan: any; + msGridColumns: string | null; msGridRow: any; msGridRowAlign: string | null; - msGridRows: string | null; msGridRowSpan: any; + msGridRows: string | null; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -8032,6 +8369,8 @@ interface CSSStyleDeclaration { msWrapFlow: string; msWrapMargin: any; msWrapThrough: string; + objectFit: string | null; + objectPosition: string | null; opacity: string | null; order: string | null; orphans: string | null; @@ -8052,13 +8391,16 @@ interface CSSStyleDeclaration { pageBreakBefore: string | null; pageBreakInside: string | null; readonly parentRule: CSSRule; + penAction: string | null; perspective: string | null; perspectiveOrigin: string | null; pointerEvents: string | null; position: string | null; quotes: string | null; + resize: string | null; right: string | null; rotate: string | null; + rowGap: string | null; rubyAlign: string | null; rubyOverhang: string | null; rubyPosition: string | null; @@ -8077,6 +8419,7 @@ interface CSSStyleDeclaration { textAlign: string | null; textAlignLast: string | null; textAnchor: string | null; + textCombineUpright: string | null; textDecoration: string | null; textIndent: string | null; textJustify: string | null; @@ -8098,6 +8441,7 @@ interface CSSStyleDeclaration { transitionTimingFunction: string | null; translate: string | null; unicodeBidi: string | null; + userSelect: string | null; verticalAlign: string | null; visibility: string | null; webkitAlignContent: string | null; @@ -8139,9 +8483,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; - webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; + webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -8180,13 +8524,11 @@ interface CSSStyleDeclaration { 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; + setProperty(propertyName: string, value: string | null, priority?: string | null): void; [index: number]: string; } @@ -8196,7 +8538,6 @@ declare var CSSStyleDeclaration: { }; interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; selectorText: string; readonly style: CSSStyleDeclaration; } @@ -8208,21 +8549,32 @@ declare var CSSStyleRule: { interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; + /** @deprecated */ cssText: string; + /** @deprecated */ readonly id: string; + /** @deprecated */ readonly imports: StyleSheetList; + /** @deprecated */ readonly isAlternate: boolean; + /** @deprecated */ readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; + readonly ownerRule: CSSRule | null; + /** @deprecated */ readonly owningElement: Element; - readonly pages: StyleSheetPageList; + /** @deprecated */ + readonly pages: any; + /** @deprecated */ readonly readOnly: boolean; readonly rules: CSSRuleList; + /** @deprecated */ addImport(bstrURL: string, lIndex?: number): number; + /** @deprecated */ 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; + /** @deprecated */ removeImport(lIndex: number): void; removeRule(lIndex: number): void; } @@ -8240,6 +8592,380 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; +interface Cache { + add(request: Request | string): Promise; + addAll(requests: (Request | string)[]): Promise; + delete(request: Request | string, options?: CacheQueryOptions): Promise; + keys(request?: Request | string, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + matchAll(request?: Request | string, options?: CacheQueryOptions): Promise; + put(request: Request | string, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface Canvas2DContextAttributes { + alpha?: boolean; + storage?: boolean; + willReadFrequently?: boolean; + [attribute: string]: boolean | string | undefined; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +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; + arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: 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 CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends 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; + mozImageSmoothingEnabled: boolean; + msFillRule: CanvasFillRule; + oImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + webkitImageSmoothingEnabled: 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; + drawFocusIfNeeded(path: Path2D, 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; + isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(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 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 ChildNode { + remove(): void; +} + +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 ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(data?: string): 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 ComputedTimingProperties { + activeDuration: number; + currentIteration: number | null; + endTime: number; + localTime: number | null; + progress: number | null; +} + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: 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; + markTimeline(label?: string): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ContentScriptGlobalScope extends EventTarget { + readonly msContentScript: ExtensionScriptApis; + readonly window: Window; +} + +declare var ContentScriptGlobalScope: { + prototype: ContentScriptGlobalScope; + new(): ContentScriptGlobalScope; +}; + +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 CountQueuingStrategy { + highWaterMark: number; + size(): number; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(strategy: QueuingStrategy): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null; +} + +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 CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + whenDefined(name: string): PromiseLike; +} + interface CustomEvent extends Event { readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; @@ -8250,6 +8976,194 @@ declare var CustomEvent: { new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; +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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +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 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 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(...tokens: string[]): void; + contains(token: string): boolean; + item(index: number): string | null; + remove(...tokens: string[]): void; + replace(oldToken: string, newToken: string): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DataCue extends TextTrackCue { data: ArrayBuffer; addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8296,10 +9210,11 @@ declare var DataTransferItem: { interface DataTransferItemList { readonly length: number; add(data: File): DataTransferItem | null; + add(data: string, type: string): DataTransferItem | null; clear(): void; item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: DataTransferItem; + [name: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -8386,11 +9301,30 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; }; +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforedeactivate": UIEvent; + "activate": Event; + "beforeactivate": Event; + "beforedeactivate": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -8398,7 +9332,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "click": MouseEvent; "contextmenu": PointerEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -8408,7 +9342,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "fullscreenchange": Event; @@ -8428,25 +9362,25 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "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; + "MSContentZoom": Event; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSManipulationStateChanged": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "mssitemodejumplistitemremoved": Event; + "msthumbnailclick": Event; "pause": Event; "play": Event; "playing": Event; @@ -8477,7 +9411,15 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "webkitfullscreenerror": Event; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { +interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent { + /** + * 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; /** * Gets the object that has the focus when the parent document has focus. */ @@ -8493,11 +9435,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * 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; + readonly anchors: HTMLCollectionOf; /** * Retrieves a collection of all applet objects in the document. */ - applets: HTMLCollectionOf; + readonly applets: HTMLCollectionOf; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ @@ -8533,7 +9475,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Gets a reference to the root node of the document. */ - documentElement: HTMLElement; + readonly documentElement: HTMLElement; /** * Sets or gets the security domain of the document. */ @@ -8541,7 +9483,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all embed objects in the document. */ - embeds: HTMLCollectionOf; + readonly embeds: HTMLCollectionOf; /** * Sets or gets the foreground (text) color of the document. */ @@ -8549,7 +9491,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of all form objects in the document. */ - forms: HTMLCollectionOf; + readonly forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; @@ -8557,7 +9499,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of img objects in the document. */ - images: HTMLCollectionOf; + readonly images: HTMLCollectionOf; /** * Gets the implementation object of the current document. */ @@ -8577,322 +9519,323 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. */ - links: HTMLCollectionOf; + readonly links: HTMLCollectionOf; /** * Contains information about the current URL. */ - readonly location: Location; - msCapsLockWarningOff: boolean; + location: Location; msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; /** * Fires when the user aborts the download. * @param ev The event. */ - onabort: (this: Document, ev: UIEvent) => any; + onabort: ((this: Document, ev: UIEvent) => any) | null; /** * Fires when the object is set as the active element. * @param ev The event. */ - onactivate: (this: Document, ev: UIEvent) => any; + onactivate: ((this: Document, ev: Event) => any) | null; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ - onbeforeactivate: (this: Document, ev: UIEvent) => any; + onbeforeactivate: ((this: Document, ev: Event) => any) | null; /** * 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; + onbeforedeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ - onblur: (this: Document, ev: FocusEvent) => any; + onblur: ((this: Document, ev: FocusEvent) => any) | null; /** * 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; + oncanplay: ((this: Document, ev: Event) => any) | null; + oncanplaythrough: ((this: Document, ev: Event) => any) | null; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ - onchange: (this: Document, ev: Event) => any; + onchange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ - onclick: (this: Document, ev: MouseEvent) => any; + onclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ - ondblclick: (this: Document, ev: MouseEvent) => any; + ondblclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + ondeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ - ondrag: (this: Document, ev: DragEvent) => any; + ondrag: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragend: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragenter: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragleave: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragover: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragstart: ((this: Document, ev: DragEvent) => any) | null; + ondrop: ((this: Document, ev: DragEvent) => any) | null; /** * Occurs when the duration attribute is updated. * @param ev The event. */ - ondurationchange: (this: Document, ev: Event) => any; + ondurationchange: ((this: Document, ev: Event) => any) | null; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ - onemptied: (this: Document, ev: Event) => any; + onemptied: ((this: Document, ev: Event) => any) | null; /** * Occurs when the end of playback is reached. * @param ev The event */ - onended: (this: Document, ev: MediaStreamErrorEvent) => any; + onended: ((this: Document, ev: Event) => any) | null; /** * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (this: Document, ev: ErrorEvent) => any; + onerror: ((this: Document, ev: ErrorEvent) => any) | null; /** * 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; + onfocus: ((this: Document, ev: FocusEvent) => any) | null; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + oninput: ((this: Document, ev: Event) => any) | null; + oninvalid: ((this: Document, ev: Event) => any) | null; /** * Fires when the user presses a key. * @param ev The keyboard event */ - onkeydown: (this: Document, ev: KeyboardEvent) => any; + onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ - onkeypress: (this: Document, ev: KeyboardEvent) => any; + onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user releases a key. * @param ev The keyboard event */ - onkeyup: (this: Document, ev: KeyboardEvent) => any; + onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires immediately after the browser loads the object. * @param ev The event. */ - onload: (this: Document, ev: Event) => any; + onload: ((this: Document, ev: Event) => any) | null; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ - onloadeddata: (this: Document, ev: Event) => any; + onloadeddata: ((this: Document, ev: Event) => any) | null; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ - onloadedmetadata: (this: Document, ev: Event) => any; + onloadedmetadata: ((this: Document, ev: Event) => any) | null; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ - onloadstart: (this: Document, ev: Event) => any; + onloadstart: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ - onmousedown: (this: Document, ev: MouseEvent) => any; + onmousedown: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ - onmousemove: (this: Document, ev: MouseEvent) => any; + onmousemove: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseout: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ - onmouseover: (this: Document, ev: MouseEvent) => any; + onmouseover: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseup: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmousewheel: ((this: Document, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: Document, ev: Event) => any) | null; + onmsgesturechange: ((this: Document, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null; + onmsgestureend: ((this: Document, ev: Event) => any) | null; + onmsgesturehold: ((this: Document, ev: Event) => any) | null; + onmsgesturestart: ((this: Document, ev: Event) => any) | null; + onmsgesturetap: ((this: Document, ev: Event) => any) | null; + onmsinertiastart: ((this: Document, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null; + onmspointercancel: ((this: Document, ev: Event) => any) | null; + onmspointerdown: ((this: Document, ev: Event) => any) | null; + onmspointerenter: ((this: Document, ev: Event) => any) | null; + onmspointerleave: ((this: Document, ev: Event) => any) | null; + onmspointermove: ((this: Document, ev: Event) => any) | null; + onmspointerout: ((this: Document, ev: Event) => any) | null; + onmspointerover: ((this: Document, ev: Event) => any) | null; + onmspointerup: ((this: Document, ev: Event) => any) | null; /** * 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; + onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null; /** * 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; + onmsthumbnailclick: ((this: Document, ev: Event) => any) | null; /** * Occurs when playback is paused. * @param ev The event. */ - onpause: (this: Document, ev: Event) => any; + onpause: ((this: Document, ev: Event) => any) | null; /** * Occurs when the play method is requested. * @param ev The event. */ - onplay: (this: Document, ev: Event) => any; + onplay: ((this: Document, ev: Event) => any) | null; /** * 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; + onplaying: ((this: Document, ev: Event) => any) | null; + onpointerlockchange: ((this: Document, ev: Event) => any) | null; + onpointerlockerror: ((this: Document, ev: Event) => any) | null; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ - onprogress: (this: Document, ev: ProgressEvent) => any; + onprogress: ((this: Document, ev: ProgressEvent) => any) | null; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ - onratechange: (this: Document, ev: Event) => any; + onratechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the state of the object has changed. * @param ev The event */ - onreadystatechange: (this: Document, ev: Event) => any; + onreadystatechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user resets a form. * @param ev The event. */ - onreset: (this: Document, ev: Event) => any; + onreset: ((this: Document, ev: Event) => any) | null; /** * 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; + onscroll: ((this: Document, ev: UIEvent) => any) | null; /** * Occurs when the seek operation ends. * @param ev The event. */ - onseeked: (this: Document, ev: Event) => any; + onseeked: ((this: Document, ev: Event) => any) | null; /** * Occurs when the current playback position is moved. * @param ev The event. */ - onseeking: (this: Document, ev: Event) => any; + onseeking: ((this: Document, ev: Event) => any) | null; /** * Fires when the current selection changes. * @param ev The event. */ - onselect: (this: Document, ev: UIEvent) => any; + onselect: ((this: Document, ev: UIEvent) => any) | null; /** * 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; + onselectionchange: ((this: Document, ev: Event) => any) | null; + onselectstart: ((this: Document, ev: Event) => any) | null; /** * Occurs when the download has stopped. * @param ev The event. */ - onstalled: (this: Document, ev: Event) => any; + onstalled: ((this: Document, ev: Event) => any) | null; /** * 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; + onstop: ((this: Document, ev: Event) => any) | null; + onsubmit: ((this: Document, ev: Event) => any) | null; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ - onsuspend: (this: Document, ev: Event) => any; + onsuspend: ((this: Document, ev: Event) => any) | null; /** * 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; + ontimeupdate: ((this: Document, ev: Event) => any) | null; + ontouchcancel: ((this: Document, ev: TouchEvent) => any) | null; + ontouchend: ((this: Document, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Document, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Document, ev: TouchEvent) => any) | null; + onvisibilitychange: (this: Document, ev: Event) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ - onvolumechange: (this: Document, ev: Event) => any; + onvolumechange: ((this: Document, ev: Event) => any) | null; /** * 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; + onwaiting: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null; + readonly plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** * Retrieves a value that indicates the current state of the object. @@ -8909,7 +9852,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all script objects in the document. */ - scripts: HTMLCollectionOf; + readonly 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. @@ -8919,14 +9862,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * 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. @@ -8942,7 +9877,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string | null; - onvisibilitychange: (this: Document, ev: Event) => any; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; @@ -9038,6 +9972,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver: Node): XPathNSResolver; /** * 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. @@ -9046,7 +9981,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @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. @@ -9073,6 +10007,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; + elementsFromPoint(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. @@ -9091,6 +10026,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Causes the element to receive the focus and executes the code specified by the onfocus event. */ + /** @deprecated */ focus(): void; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. @@ -9163,10 +10099,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ queryCommandValue(commandId: string): string; releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** @@ -9190,7 +10122,79 @@ declare var Document: { new(): Document; }; -interface DocumentFragment extends Node, NodeSelector, ParentNode { +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + 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: "MSDCCEvent"): MSDCCEvent; + createEvent(eventInterface: "MSDSHEvent"): MSDSHEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + 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: "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: "PromiseRejectionEvent"): PromiseRejectionEvent; + 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: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + 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: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DocumentFragment extends Node, ParentNode { getElementById(elementId: string): HTMLElement | null; } @@ -9199,6 +10203,14 @@ declare var DocumentFragment: { new(): DocumentFragment; }; +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly styleSheets: StyleSheetList; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + getSelection(): Selection | null; +} + interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; readonly internalSubset: string | null; @@ -9213,149 +10225,6 @@ declare var 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; @@ -9381,209 +10250,23 @@ declare var 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 EXT_blend_minmax { + readonly MAX_EXT: number; + readonly MIN_EXT: number; } -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 | null; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB_EXT: number; +} + +interface EXT_shader_texture_lod { +} interface EXT_texture_filter_anisotropic { readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; @@ -9597,14 +10280,262 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; }; +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": Event; + "command": Event; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSGotPointerCapture": Event; + "MSInertiaStart": Event; + "MSLostPointerCapture": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode { + readonly assignedSlot: HTMLSlotElement | null; + readonly attributes: NamedNodeMap; + 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) | null; + oncommand: ((this: Element, ev: Event) => any) | null; + ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onmsgesturechange: ((this: Element, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null; + onmsgestureend: ((this: Element, ev: Event) => any) | null; + onmsgesturehold: ((this: Element, ev: Event) => any) | null; + onmsgesturestart: ((this: Element, ev: Event) => any) | null; + onmsgesturetap: ((this: Element, ev: Event) => any) | null; + onmsgotpointercapture: ((this: Element, ev: Event) => any) | null; + onmsinertiastart: ((this: Element, ev: Event) => any) | null; + onmslostpointercapture: ((this: Element, ev: Event) => any) | null; + onmspointercancel: ((this: Element, ev: Event) => any) | null; + onmspointerdown: ((this: Element, ev: Event) => any) | null; + onmspointerenter: ((this: Element, ev: Event) => any) | null; + onmspointerleave: ((this: Element, ev: Event) => any) | null; + onmspointermove: ((this: Element, ev: Event) => any) | null; + onmspointerout: ((this: Element, ev: Event) => any) | null; + onmspointerover: ((this: Element, ev: Event) => any) | null; + onmspointerup: ((this: Element, ev: Event) => any) | null; + ontouchcancel: ((this: Element, ev: TouchEvent) => any) | null; + ontouchend: ((this: Element, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Element, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Element, ev: TouchEvent) => any) | null; + onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; + outerHTML: string; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly shadowRoot: ShadowRoot | null; + slot: string; + readonly tagName: string; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + getAttribute(qualifiedName: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + getElementsByClassName(classNames: string): NodeListOf; + 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; + hasAttributes(): boolean; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + matches(selectors: string): boolean; + msGetRegionContent(): any; + 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; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + setAttribute(qualifiedName: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): 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: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + readonly style: CSSStyleDeclaration; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ElementDefinitionOptions { + extends: string; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly nextElementSibling: Element | null; + readonly previousElementSibling: Element | null; +} + +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(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly scoped: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget | null; + readonly timeStamp: number; + readonly type: string; + deepPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(typeArg: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; - fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; genericSynchronousFunction(functionId: number, parameters?: string): string; + genericWebRuntimeCallout(to: any, from: any, payload: string): void; getExtensionId(): string; - registerGenericFunctionCallbackHandler(callbackHandler: any): void; - registerGenericPersistentCallbackHandler(callbackHandler: any): void; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericPersistentCallbackHandler(callbackHandler: Function): void; + registerWebRuntimeCallbackHandler(handler: Function): any; } declare var ExtensionScriptApis: { @@ -9621,10 +10552,11 @@ declare var External: { }; interface File extends Blob { + readonly lastModified: number; + /** @deprecated */ readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; - readonly lastModified: number; } declare var File: { @@ -9634,7 +10566,7 @@ declare var File: { interface FileList { readonly length: number; - item(index: number): File; + item(index: number): File | null; [index: number]: File; } @@ -9643,21 +10575,49 @@ declare var FileList: { new(): FileList; }; -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; 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; + readAsText(blob: Blob, label?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[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: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface FocusEvent extends UIEvent { @@ -9695,7 +10655,8 @@ interface FormData { declare var FormData: { prototype: FormData; - new (form?: HTMLFormElement): FormData; + new(): FormData; + new(form: HTMLFormElement): FormData; }; interface GainNode extends AudioNode { @@ -9711,9 +10672,13 @@ interface Gamepad { readonly axes: number[]; readonly buttons: GamepadButton[]; readonly connected: boolean; + readonly displayId: number; + readonly hand: GamepadHand; + readonly hapticActuators: GamepadHapticActuator[]; readonly id: string; readonly index: number; - readonly mapping: string; + readonly mapping: GamepadMappingType; + readonly pose: GamepadPose | null; readonly timestamp: number; } @@ -9724,6 +10689,7 @@ declare var Gamepad: { interface GamepadButton { readonly pressed: boolean; + readonly touched: boolean; readonly value: number; } @@ -9741,6 +10707,32 @@ declare var GamepadEvent: { new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; }; +interface GamepadHapticActuator { + readonly type: GamepadHapticActuatorType; + pulse(value: number, duration: number): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GamepadPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; +} + +declare var GamepadPose: { + prototype: GamepadPose; + new(): GamepadPose; +}; + interface Geolocation { clearWatch(watchId: number): void; getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; @@ -9752,45 +10744,41 @@ declare var Geolocation: { new(): Geolocation; }; -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; +interface GetSVGDocument { + getSVGDocument(): Document; } -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; +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; } -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; +interface GlobalEventHandlers { + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + 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; } -declare var History: { - prototype: History; - new(): History; -}; +interface GlobalFetch { + fetch(input?: Request | string, init?: RequestInit): Promise; +} interface HTMLAllCollection { readonly length: number; @@ -9804,55 +10792,30 @@ declare var HTMLAllCollection: { new(): HTMLAllCollection; }; -interface HTMLAnchorElement extends HTMLElement { +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + Methods: string; /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Sets or retrieves the coordinates of the object. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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. @@ -9861,14 +10824,12 @@ interface HTMLAnchorElement extends HTMLElement { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ 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. */ + /** @deprecated */ shape: string; /** * Sets or retrieves the window or frame at which to target content. @@ -9880,10 +10841,6 @@ interface HTMLAnchorElement extends HTMLElement { 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; @@ -9896,70 +10853,44 @@ declare var HTMLAnchorElement: { }; interface HTMLAppletElement extends HTMLElement { + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ 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. */ + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; /** * Sets or retrieves the shape of the object. */ + /** @deprecated */ 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; + /** @deprecated */ + object: string; + /** @deprecated */ vspace: number; - width: number; + /** @deprecated */ + width: string; 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; @@ -9971,7 +10902,7 @@ declare var HTMLAppletElement: { new(): HTMLAppletElement; }; -interface HTMLAreaElement extends HTMLElement { +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { /** * Sets or retrieves a text alternative to the graphic. */ @@ -9981,43 +10912,12 @@ interface HTMLAreaElement extends HTMLElement { */ 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. */ + /** @deprecated */ 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. */ @@ -10026,10 +10926,6 @@ interface HTMLAreaElement extends HTMLElement { * 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; @@ -10061,6 +10957,23 @@ declare var HTMLAudioElement: { new(): HTMLAudioElement; }; +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. + */ + /** @deprecated */ + 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 HTMLBaseElement extends HTMLElement { /** * Gets or sets the baseline URL on which relative links are based. @@ -10085,10 +10998,12 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ face: string; /** * Sets or retrieves the font size of the object. */ + /** @deprecated */ 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; @@ -10101,51 +11016,34 @@ declare var HTMLBaseFontElement: { new(): HTMLBaseFontElement; }; -interface HTMLBodyElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { + /** @deprecated */ + aLink: string; + /** @deprecated */ background: string; - bgColor: any; + /** @deprecated */ + bgColor: string; bgProperties: string; - link: any; + /** @deprecated */ + link: string; + /** @deprecated */ 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; + onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; + onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null; + /** @deprecated */ + text: string; + /** @deprecated */ + vLink: string; 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; @@ -10157,22 +11055,6 @@ declare var 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. @@ -10198,7 +11080,7 @@ interface HTMLButtonElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -10268,12 +11150,12 @@ interface HTMLCanvasElement extends HTMLElement { * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ msToBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; /** * 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; @@ -10309,6 +11191,26 @@ declare var HTMLCollection: { new(): HTMLCollection; }; +interface HTMLCollectionOf extends HTMLCollectionBase { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface HTMLDListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLDataElement extends HTMLElement { value: string; addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -10323,7 +11225,7 @@ declare var HTMLDataElement: { }; interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; + readonly 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; @@ -10335,6 +11237,36 @@ declare var HTMLDataListElement: { new(): HTMLDataListElement; }; +interface HTMLDetailsElement extends HTMLElement { + open: boolean; + addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; + addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + interface HTMLDirectoryElement extends HTMLElement { compact: boolean; addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -10352,6 +11284,7 @@ interface HTMLDivElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. @@ -10368,19 +11301,6 @@ declare var 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; @@ -10395,12 +11315,12 @@ declare var HTMLDocument: { interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforecopy": ClipboardEvent; - "beforecut": ClipboardEvent; - "beforedeactivate": UIEvent; - "beforepaste": ClipboardEvent; + "activate": Event; + "beforeactivate": Event; + "beforecopy": Event; + "beforecut": Event; + "beforedeactivate": Event; + "beforepaste": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -10411,7 +11331,7 @@ interface HTMLElementEventMap extends ElementEventMap { "cuechange": Event; "cut": ClipboardEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -10421,7 +11341,7 @@ interface HTMLElementEventMap extends ElementEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "input": Event; @@ -10441,8 +11361,8 @@ interface HTMLElementEventMap extends ElementEventMap { "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": WheelEvent; - "MSContentZoom": UIEvent; - "MSManipulationStateChanged": MSManipulationEvent; + "MSContentZoom": Event; + "MSManipulationStateChanged": Event; "paste": ClipboardEvent; "pause": Event; "play": Event; @@ -10463,9 +11383,8 @@ interface HTMLElementEventMap extends ElementEventMap { "waiting": Event; } -interface HTMLElement extends Element { +interface HTMLElement extends Element, ElementCSSInlineStyle { accessKey: string; - readonly children: HTMLCollection; contentEditable: string; readonly dataset: DOMStringMap; dir: string; @@ -10480,84 +11399,83 @@ interface HTMLElement extends Element { 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; + onabort: ((this: HTMLElement, ev: UIEvent) => any) | null; + onactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecut: ((this: HTMLElement, ev: Event) => any) | null; + onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null; + onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oncanplay: ((this: HTMLElement, ev: Event) => any) | null; + oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null; + onchange: ((this: HTMLElement, ev: Event) => any) | null; + onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null; + oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + oncuechange: ((this: HTMLElement, ev: Event) => any) | null; + oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + ondeactivate: ((this: HTMLElement, ev: Event) => any) | null; + ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondurationchange: ((this: HTMLElement, ev: Event) => any) | null; + onemptied: ((this: HTMLElement, ev: Event) => any) | null; + onended: ((this: HTMLElement, ev: Event) => any) | null; + onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null; + onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oninput: ((this: HTMLElement, ev: Event) => any) | null; + oninvalid: ((this: HTMLElement, ev: Event) => any) | null; + onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onload: ((this: HTMLElement, ev: Event) => any) | null; + onloadeddata: ((this: HTMLElement, ev: Event) => any) | null; + onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null; + onloadstart: ((this: HTMLElement, ev: Event) => any) | null; + onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null; + onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + onpause: ((this: HTMLElement, ev: Event) => any) | null; + onplay: ((this: HTMLElement, ev: Event) => any) | null; + onplaying: ((this: HTMLElement, ev: Event) => any) | null; + onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null; + onratechange: ((this: HTMLElement, ev: Event) => any) | null; + onreset: ((this: HTMLElement, ev: Event) => any) | null; + onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null; + onseeked: ((this: HTMLElement, ev: Event) => any) | null; + onseeking: ((this: HTMLElement, ev: Event) => any) | null; + onselect: ((this: HTMLElement, ev: UIEvent) => any) | null; + onselectstart: ((this: HTMLElement, ev: Event) => any) | null; + onstalled: ((this: HTMLElement, ev: Event) => any) | null; + onsubmit: ((this: HTMLElement, ev: Event) => any) | null; + onsuspend: ((this: HTMLElement, ev: Event) => any) | null; + ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null; + onvolumechange: ((this: HTMLElement, ev: Event) => any) | null; + onwaiting: ((this: HTMLElement, ev: Event) => any) | null; outerText: string; spellcheck: boolean; - readonly style: CSSStyleDeclaration; tabIndex: number; title: string; + animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; blur(): void; click(): void; dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; 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; @@ -10594,6 +11512,7 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * Retrieves the palette used for the embedded document. @@ -10674,6 +11593,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ 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; @@ -10754,6 +11674,7 @@ interface HTMLFormElement extends HTMLElement { * Retrieves a form object or an object from an elements collection. */ namedItem(name: string): any; + reportValidity(): boolean; /** * Fires when the user resets a form. */ @@ -10762,8 +11683,6 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ 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; @@ -10792,14 +11711,17 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + /** @deprecated */ + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + /** @deprecated */ + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. @@ -10812,30 +11734,37 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a URI to a long description of the object. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ marginWidth: string; /** * Sets or retrieves the frame name. */ + /** @deprecated */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ + /** @deprecated */ noResize: boolean; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ + /** @deprecated */ src: string; /** * Sets or retrieves the width of the object. @@ -10852,64 +11781,29 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; }; -interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { /** * Sets or retrieves the frame widths of the object. */ + /** @deprecated */ 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; + onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null; + onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null; /** * Sets or retrieves the frame heights of the object. */ + /** @deprecated */ 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; @@ -10922,7 +11816,35 @@ declare var HTMLFrameSetElement: { new(): HTMLFrameSetElement; }; +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + /** @deprecated */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + 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 HTMLHeadElement extends HTMLElement { + /** @deprecated */ 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; @@ -10939,6 +11861,7 @@ interface HTMLHeadingElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ 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; @@ -10951,34 +11874,11 @@ declare var 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. */ + /** @deprecated */ 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; @@ -10991,6 +11891,19 @@ declare var HTMLHtmlElement: { new(): HTMLHtmlElement; }; +interface HTMLHyperlinkElementUtils { + hash: string; + host: string; + hostname: string; + href: string; + origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + toString(): string; +} + interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; } @@ -10999,78 +11912,64 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ 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; + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ 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. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ 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; + readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** - * Sets or retrieves the vertical margin for the object. + * Sets or retrives the content of the page that is to contain. */ - vspace: number; + srcdoc: string; /** * 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; @@ -11086,6 +11985,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -11094,6 +11994,7 @@ interface HTMLImageElement extends HTMLElement { /** * Specifies the properties of a border drawn around an object. */ + /** @deprecated */ border: string; /** * Retrieves whether the object is fully loaded. @@ -11101,6 +12002,7 @@ interface HTMLImageElement extends HTMLElement { readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; /** * Sets or retrieves the height of the object. */ @@ -11108,6 +12010,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ hspace: number; /** * Sets or retrieves whether the image is a server-side image map. @@ -11117,6 +12020,7 @@ interface HTMLImageElement extends HTMLElement { * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. */ longDesc: string; + /** @deprecated */ lowsrc: string; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -11134,6 +12038,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * The original height of the image resource before sizing. @@ -11156,6 +12061,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the vertical margin for the object. */ + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -11183,6 +12089,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -11196,18 +12103,10 @@ interface HTMLInputElement 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 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. */ @@ -11240,7 +12139,7 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -11248,16 +12147,12 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + height: number; indeterminate: boolean; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ - readonly list: HTMLElement; + readonly list: HTMLElement | null; /** * 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. */ @@ -11270,6 +12165,7 @@ interface HTMLInputElement extends HTMLElement { * 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; + minLength: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ @@ -11291,21 +12187,20 @@ interface HTMLInputElement extends HTMLElement { * When present, marks an element that can't be submitted without a value. */ required: boolean; - selectionDirection: string; + selectionDirection: string | null; /** * Gets or sets the end position or offset of a text selection. */ - selectionEnd: number; + selectionEnd: number | null; /** * Gets or sets the starting position or offset of a text selection. */ - selectionStart: number; + selectionStart: number | null; 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. */ @@ -11317,6 +12212,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ + /** @deprecated */ 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. @@ -11330,25 +12226,20 @@ interface HTMLInputElement extends HTMLElement { * Returns the value of the data at the cursor's current position. */ value: string; - valueAsDate: Date; + valueAsDate: any; /** * 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; + width: number; /** * 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. */ @@ -11390,48 +12281,8 @@ declare var 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 { + /** @deprecated */ type: string; /** * Sets or retrieves the value of a list item. @@ -11448,11 +12299,56 @@ declare var HTMLLIElement: { new(): HTMLLIElement; }; +interface HTMLLabelElement extends HTMLElement { + readonly control: HTMLInputElement | null; + /** + * 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; + 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. + */ + /** @deprecated */ + 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 HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; + crossOrigin: string | null; + /** @deprecated */ disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. @@ -11462,6 +12358,8 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { * Sets or retrieves the language code of the object. */ hreflang: string; + import?: Document; + integrity: string; /** * Sets or retrieves the media type. */ @@ -11473,17 +12371,17 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ rev: string; /** * Sets or retrieves the window or frame at which to target content. */ + /** @deprecated */ 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; @@ -11495,6 +12393,18 @@ declare var HTMLLinkElement: { new(): HTMLLinkElement; }; +interface HTMLMainElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. @@ -11522,21 +12432,37 @@ interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { } interface HTMLMarqueeElement extends HTMLElement { + /** @deprecated */ behavior: string; - bgColor: any; + /** @deprecated */ + bgColor: string; + /** @deprecated */ direction: string; + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; + /** @deprecated */ loop: number; - onbounce: (this: HTMLMarqueeElement, ev: Event) => any; - onfinish: (this: HTMLMarqueeElement, ev: Event) => any; - onstart: (this: HTMLMarqueeElement, ev: Event) => any; + /** @deprecated */ + onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ scrollAmount: number; + /** @deprecated */ scrollDelay: number; + /** @deprecated */ trueSpeed: boolean; + /** @deprecated */ vspace: number; + /** @deprecated */ width: string; + /** @deprecated */ start(): void; + /** @deprecated */ 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; @@ -11551,7 +12477,7 @@ declare var HTMLMarqueeElement: { interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; - "msneedkey": MSMediaKeyNeededEvent; + "msneedkey": Event; } interface HTMLMediaElement extends HTMLElement { @@ -11596,7 +12522,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Returns an object representing the current error state of the audio or video element. */ - readonly error: MediaError; + readonly error: MediaError | null; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ @@ -11614,6 +12540,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ + /** @deprecated */ readonly msKeys: MSMediaKeys; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -11643,8 +12570,9 @@ interface HTMLMediaElement extends HTMLElement { * Gets the current network activity for the element. */ readonly networkState: number; - onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null; + /** @deprecated */ + onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null; /** * Gets a flag that specifies whether playback is paused. */ @@ -11661,7 +12589,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: number; + readonly readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -11674,18 +12602,18 @@ interface HTMLMediaElement extends HTMLElement { * The address or URL of the a media resource that is to be considered. */ src: string; - srcObject: MediaStream | null; + srcObject: MediaStream | MediaSource | Blob | 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; + addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack; /** * Returns a string that specifies whether the client can play a given media resource type. */ - canPlayType(type: string): string; + canPlayType(type: string): CanPlayTypeResult; /** * Resets the audio or video object and loads a new media resource. */ @@ -11699,6 +12627,7 @@ interface HTMLMediaElement extends HTMLElement { * Inserts the specified audio effect into media pipeline. */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + /** @deprecated */ msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Specifies the media protection manager for a given media pipeline. @@ -11743,6 +12672,7 @@ declare var HTMLMediaElement: { }; interface HTMLMenuElement extends HTMLElement { + /** @deprecated */ compact: boolean; type: string; addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -11760,6 +12690,7 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. @@ -11776,10 +12707,12 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ + /** @deprecated */ scheme: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ + /** @deprecated */ 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; @@ -11830,41 +12763,63 @@ declare var HTMLModElement: { new(): HTMLModElement; }; +interface HTMLOListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLObjectElement extends HTMLElement, GetSVGDocument { - align: 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; + /** @deprecated */ + align: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ border: string; /** * Sets or retrieves the URL of the file containing the compiled Java class. */ + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ + /** @deprecated */ codeType: string; /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + readonly contentDocument: Document | null; /** * Sets or retrieves the URL that references the data of the object. */ data: string; + /** @deprecated */ declare: boolean; /** * Retrieves a reference to the form that the object is embedded in. @@ -11874,6 +12829,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the height of the object. */ height: string; + /** @deprecated */ hspace: number; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -11899,11 +12855,13 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a message to be displayed while an object is loading. */ + /** @deprecated */ standby: string; /** * Sets or retrieves the MIME type of the object. */ type: string; + typemustmatch: boolean; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ @@ -11916,6 +12874,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -11925,7 +12884,6 @@ 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. */ @@ -11946,54 +12904,16 @@ declare var 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; @@ -12049,7 +12969,7 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; remove(index: number): void; } @@ -12061,7 +12981,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; readonly form: HTMLFormElement | null; - readonly htmlFor: DOMSettableTokenList; + readonly htmlFor: DOMTokenList; name: string; readonly type: string; readonly validationMessage: string; @@ -12086,6 +13006,7 @@ interface HTMLParagraphElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -12107,6 +13028,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the content type of the resource designated by the value attribute. */ + /** @deprecated */ type: string; /** * Sets or retrieves the value of an input parameter for an element. @@ -12115,6 +13037,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the data type of the value attribute. */ + /** @deprecated */ 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; @@ -12143,6 +13066,7 @@ interface HTMLPreElement extends HTMLElement { /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ + /** @deprecated */ 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; @@ -12213,11 +13137,15 @@ interface HTMLScriptElement extends HTMLElement { /** * Sets or retrieves the event for which the script is written. */ + /** @deprecated */ event: string; /** * Sets or retrieves the object that is bound to the event script. */ + /** @deprecated */ htmlFor: string; + integrity: string; + noModule: boolean; /** * Retrieves the URL to an external file that contains the source code or data. */ @@ -12230,7 +13158,6 @@ interface HTMLScriptElement extends HTMLElement { * 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; @@ -12273,7 +13200,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the index of the selected option in a select object. */ selectedIndex: number; - selectedOptions: HTMLCollectionOf; + readonly selectedOptions: HTMLCollectionOf; /** * Sets or retrieves the number of rows in the list box. */ @@ -12303,7 +13230,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -12313,7 +13240,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + item(name?: any, index?: any): Element | null; /** * 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. @@ -12341,11 +13268,21 @@ declare var HTMLSelectElement: { new(): HTMLSelectElement; }; +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; + addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; + /** @deprecated */ msKeySystem: string; sizes: string; /** @@ -12381,6 +13318,7 @@ declare var HTMLSpanElement: { }; interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** @deprecated */ disabled: boolean; /** * Sets or retrieves the media type. @@ -12401,15 +13339,24 @@ declare var HTMLStyleElement: { new(): HTMLStyleElement; }; +interface HTMLSummaryElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. */ + /** @deprecated */ 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; @@ -12421,7 +13368,7 @@ declare var HTMLTableCaptionElement: { new(): HTMLTableCaptionElement; }; -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableCellElement extends HTMLElement { /** * Sets or retrieves abbreviated text for the object. */ @@ -12429,16 +13376,23 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. */ + /** @deprecated */ axis: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves the position of the object in the cells collection of a row. */ readonly cellIndex: number; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number columns in the table that the object should span. */ @@ -12450,10 +13404,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves the height of the object. */ - height: any; + /** @deprecated */ + height: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ + /** @deprecated */ noWrap: boolean; /** * Sets or retrieves how many rows in a table the cell should span. @@ -12463,9 +13419,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ 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; @@ -12478,19 +13437,27 @@ declare var HTMLTableCellElement: { new(): HTMLTableCellElement; }; -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableColElement extends HTMLElement { /** * Sets or retrieves the alignment of the object relative to the display or table. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of columns in the group. */ span: number; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ - width: any; + /** @deprecated */ + width: string; 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; @@ -12518,67 +13485,64 @@ interface HTMLTableElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; /** * Retrieves the caption object of a table. */ - caption: HTMLTableCaptionElement; + caption: HTMLTableCaptionElement | null; /** * Sets or retrieves the amount of space between the border of the cell and the content of the cell. */ + /** @deprecated */ cellPadding: string; /** * Sets or retrieves the amount of space between cells in a table. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + readonly rows: HTMLCollectionOf; /** * Sets or retrieves which dividing lines (inner borders) are displayed. */ + /** @deprecated */ rules: string; /** * Sets or retrieves a description and/or structure of the object. */ + /** @deprecated */ summary: string; /** * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. */ - tBodies: HTMLCollectionOf; + readonly tBodies: HTMLCollectionOf; /** * Retrieves the tFoot object of the table. */ - tFoot: HTMLTableSectionElement; + tFoot: HTMLTableSectionElement | null; /** * Retrieves the tHead object of the table. */ - tHead: HTMLTableSectionElement; + tHead: HTMLTableSectionElement | null; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ width: string; /** * Creates an empty caption element in the table. @@ -12630,9 +13594,6 @@ declare var 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; @@ -12645,20 +13606,22 @@ declare var HTMLTableHeaderCellElement: { new(): HTMLTableHeaderCellElement; }; -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableRowElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves a collection of all cells in the table row. */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; + readonly cells: HTMLCollectionOf; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Retrieves the position of the object in the rows collection for the table. */ @@ -12667,6 +13630,8 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Retrieves the position of the object in the collection. */ readonly sectionRowIndex: number; + /** @deprecated */ + vAlign: string; /** * 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. @@ -12688,15 +13653,22 @@ declare var HTMLTableRowElement: { new(): HTMLTableRowElement; }; -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableSectionElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of horizontal rows contained in the object. */ - rows: HTMLCollectionOf; + readonly rows: HTMLCollectionOf; + /** @deprecated */ + vAlign: string; /** * 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. @@ -12753,6 +13725,7 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; + minLength: number; /** * Sets or retrieves the name of the object. */ @@ -12781,10 +13754,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -12809,7 +13778,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -12898,7 +13866,9 @@ declare var HTMLTrackElement: { }; interface HTMLUListElement extends HTMLElement { + /** @deprecated */ compact: boolean; + /** @deprecated */ 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; @@ -12940,9 +13910,9 @@ interface HTMLVideoElement extends HTMLMediaElement { msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; - onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; /** * 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. */ @@ -12965,10 +13935,10 @@ interface HTMLVideoElement extends HTMLMediaElement { 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; + 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; @@ -12980,13 +13950,71 @@ declare var HTMLVideoElement: { new(): HTMLVideoElement; }; +interface HTMLegendElement { + readonly form: HTMLFormElement | null; +} + +declare var HTMLegendElement: { + prototype: HTMLegendElement; + new(): HTMLegendElement; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string; + readonly oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: Function, thisArg?: any): 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; + scrollRestoration: ScrollRestoration; + readonly state: any; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): 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 HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + interface IDBCursor { readonly direction: IDBCursorDirection; - key: IDBKeyRange | IDBValidKey; + readonly key: IDBKeyRange | number | string | Date | IDBArrayKey; readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; + readonly source: IDBObjectStore | IDBIndex; advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; + continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void; delete(): IDBRequest; update(value: any): IDBRequest; readonly NEXT: string; @@ -13021,16 +14049,14 @@ interface IDBDatabaseEventMap { 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; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: Event) => any) | null; + readonly version: number; 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; @@ -13042,6 +14068,10 @@ declare var IDBDatabase: { new(): IDBDatabase; }; +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + interface IDBFactory { cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; @@ -13054,16 +14084,16 @@ declare var IDBFactory: { }; interface IDBIndex { - keyPath: string | string[]; + readonly keyPath: string | string[]; + multiEntry: boolean; 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; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -13088,21 +14118,21 @@ declare var IDBKeyRange: { }; interface IDBObjectStore { + autoIncrement: boolean; readonly indexNames: DOMStringList; - keyPath: string | string[]; + readonly keyPath: string | string[] | null; readonly name: string; readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): 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; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; } declare var IDBObjectStore: { @@ -13116,8 +14146,8 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { } interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: IDBOpenDBRequest, ev: Event) => any; - onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; 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; @@ -13136,11 +14166,11 @@ interface IDBRequestEventMap { interface IDBRequest extends EventTarget { readonly error: DOMException; - onerror: (this: IDBRequest, ev: Event) => any; - onsuccess: (this: IDBRequest, ev: Event) => any; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; readonly readyState: IDBRequestReadyState; readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; + readonly 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; @@ -13163,9 +14193,9 @@ 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; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -13204,8 +14234,23 @@ declare var IIRFilterNode: { new(): IIRFilterNode; }; +interface ImageBitmap { + readonly height: number; + readonly width: number; + close(): void; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + interface ImageData { - data: Uint8ClampedArray; + readonly data: Uint8ClampedArray; readonly height: number; readonly width: number; } @@ -13235,10 +14280,10 @@ interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; readonly intersectionRect: ClientRect | DOMRect; + readonly isIntersecting: boolean; readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; - readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -13248,19 +14293,23 @@ declare var IntersectionObserverEntry: { interface KeyboardEvent extends UIEvent { readonly altKey: boolean; - readonly char: string | null; + /** @deprecated */ + char: string; + /** @deprecated */ readonly charCode: number; + readonly code: string; readonly ctrlKey: boolean; readonly key: string; + /** @deprecated */ readonly keyCode: number; - readonly locale: string; readonly location: number; readonly metaKey: boolean; readonly repeat: boolean; readonly shiftKey: boolean; + /** @deprecated */ readonly which: number; - readonly code: string; getModifierState(keyArg: string): boolean; + /** @deprecated */ 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; @@ -13281,6 +14330,10 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_STANDARD: number; }; +interface LinkStyle { + readonly sheet: StyleSheet | null; +} + interface ListeningStateChangedEvent extends Event { readonly label: string; readonly state: ListeningState; @@ -13312,14 +14365,327 @@ declare var Location: { new(): Location; }; -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; } -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; +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 MSDCCEvent extends Event { + readonly maxFr: number; + readonly maxFs: number; +} + +declare var MSDCCEvent: { + prototype: MSDCCEvent; + new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent; +}; + +interface MSDSHEvent extends Event { + readonly sources: number[]; + readonly timestamp: number; +} + +declare var MSDSHEvent: { + prototype: MSDSHEvent; + new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent; +}; + +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 MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +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 MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null; + 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 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 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 MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string | null): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string; +}; + +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 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 MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MSStreamReaderEventMap { + "abort": UIEvent; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSStreamReader extends EventTarget { + readonly error: DOMError; + onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null; + onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null; + onload: ((this: MSStreamReader, ev: Event) => any) | null; + onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: MSStreamReader, ev: Event) => any) | null; + onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; + 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; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface MediaDeviceInfo { @@ -13339,7 +14705,7 @@ interface MediaDevicesEventMap { } interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; + ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; @@ -13402,26 +14768,16 @@ declare var MediaKeyMessageEvent: { new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; }; -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: BufferSource): 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: BufferSource): Promise; + generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: BufferSource): Promise; + update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; } declare var MediaKeySession: { @@ -13431,9 +14787,9 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: BufferSource): MediaKeyStatus; - has(keyId: BufferSource): boolean; + forEach(callback: Function, thisArg?: any): void; + get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus; + has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean; } declare var MediaKeyStatusMap: { @@ -13452,13 +14808,23 @@ declare var MediaKeySystemAccess: { new(): MediaKeySystemAccess; }; +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + interface MediaList { readonly length: number; mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; + appendMedium(medium: string): void; + deleteMedium(medium: string): void; + item(index: number): string | null; + toString(): number; [index: number]: string; } @@ -13505,10 +14871,10 @@ interface MediaStreamEventMap { 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; + onactive: ((this: MediaStream, ev: Event) => any) | null; + onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + oninactive: ((this: MediaStream, ev: Event) => any) | null; + onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; addTrack(track: MediaStreamTrack): void; clone(): MediaStream; getAudioTracks(): MediaStreamTrack[]; @@ -13525,7 +14891,9 @@ interface MediaStream extends EventTarget { declare var MediaStream: { prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; + new(): MediaStream; + new(stream: MediaStream): MediaStream; + new(tracks: MediaStreamTrack[]): MediaStream; }; interface MediaStreamAudioSourceNode extends AudioNode { @@ -13578,10 +14946,10 @@ interface MediaStreamTrack extends EventTarget { 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; + onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readonly: boolean; readonly readyState: MediaStreamTrackState; readonly remote: boolean; @@ -13624,9 +14992,9 @@ declare var 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; + readonly ports: ReadonlyArray; + readonly source: Window | null; + initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void; } declare var MessageEvent: { @@ -13639,7 +15007,7 @@ interface MessagePortEventMap { } interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; @@ -13685,6 +15053,7 @@ interface MouseEvent extends UIEvent { readonly clientX: number; readonly clientY: number; readonly ctrlKey: boolean; + /** @deprecated */ readonly fromElement: Element; readonly layerX: number; readonly layerY: number; @@ -13699,7 +15068,9 @@ interface MouseEvent extends UIEvent { readonly screenX: number; readonly screenY: number; readonly shiftKey: boolean; + /** @deprecated */ readonly toElement: Element; + /** @deprecated */ readonly which: number; readonly x: number; readonly y: number; @@ -13712,456 +15083,6 @@ declare var 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; @@ -14202,7 +15123,7 @@ interface MutationRecord { readonly previousSibling: Node | null; readonly removedNodes: NodeList; readonly target: Node; - readonly type: string; + readonly type: MutationRecordType; } declare var MutationRecord: { @@ -14212,13 +15133,13 @@ declare var 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; + getNamedItem(qualifiedName: string): Attr | null; + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + item(index: number): Attr | null; + removeNamedItem(qualifiedName: string): Attr; + removeNamedItemNS(namespace: string | null, localName: string): Attr; + setNamedItem(attr: Attr): Attr | null; + setNamedItemNS(attr: Attr): Attr | null; [index: number]: Attr; } @@ -14227,39 +15148,13 @@ declare var 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 { +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage { + readonly activeVRDisplays: ReadonlyArray; readonly authentication: WebAuthentication; readonly cookieEnabled: boolean; + readonly doNotTrack: string | null; gamepadInputEmulation: GamepadInputEmulationType; - readonly language: string; + readonly geolocation: Geolocation; readonly maxTouchPoints: number; readonly mimeTypes: MimeTypeArray; readonly msManipulationViewsEnabled: boolean; @@ -14269,10 +15164,8 @@ 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[]; + getGamepads(): (Gamepad | null)[]; + getVRDisplays(): Promise; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; @@ -14284,10 +15177,50 @@ declare var Navigator: { new(): Navigator; }; +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +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 NavigatorLanguage { + readonly language: string; + readonly languages: ReadonlyArray; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getDisplayMedia(constraints: MediaStreamConstraints): Promise; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + interface Node extends EventTarget { - readonly attributes: NamedNodeMap; readonly baseURI: string | null; - readonly childNodes: NodeList; + readonly childNodes: NodeListOf; readonly firstChild: Node | null; readonly lastChild: Node | null; readonly localName: string | null; @@ -14305,7 +15238,6 @@ interface Node extends EventTarget { 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; @@ -14360,7 +15292,7 @@ declare var Node: { }; interface NodeFilter { - acceptNode(n: Node): number; + acceptNode(node: Node): number; } declare var NodeFilter: { @@ -14383,13 +15315,14 @@ declare var NodeFilter: { }; interface NodeIterator { + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; detach(): void; - nextNode(): Node; - previousNode(): Node; + nextNode(): Node | null; + previousNode(): Node | null; } declare var NodeIterator: { @@ -14408,6 +15341,21 @@ declare var NodeList: { new(): NodeList; }; +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +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 NotificationEventMap { "click": Event; "close": Event; @@ -14416,16 +15364,17 @@ interface NotificationEventMap { } interface Notification extends EventTarget { - readonly body: string; + readonly body: string | null; + readonly data: any; 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 icon: string | null; + readonly lang: string | null; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; readonly permission: NotificationPermission; - readonly tag: string; + readonly tag: string | null; readonly title: string; close(): void; addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -14492,6 +15441,14 @@ declare var OES_texture_half_float_linear: { new(): OES_texture_half_float_linear; }; +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; +} + interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; } @@ -14507,7 +15464,7 @@ interface OfflineAudioContextEventMap extends AudioContextEventMap { interface OfflineAudioContext extends AudioContextBase { readonly length: number; - oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; + oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null; startRendering(): Promise; suspend(suspendTime: number): Promise; addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -14522,13 +15479,13 @@ declare var OfflineAudioContext: { }; interface OscillatorNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface OscillatorNode extends AudioNode { readonly detune: AudioParam; readonly frequency: AudioParam; - onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: OscillatorNode, ev: Event) => any) | null; type: OscillatorType; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; @@ -14579,8 +15536,11 @@ interface PannerNode extends AudioNode { panningModel: PanningModelType; refDistance: number; rolloffFactor: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -14589,12 +15549,28 @@ declare var PannerNode: { new(): PannerNode; }; -interface Path2D extends Object, CanvasPathMethods { +interface ParentNode { + readonly children: HTMLCollection; + 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 ParentNode { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; +} + +interface Path2D extends CanvasPathMethods { } declare var Path2D: { prototype: Path2D; - new(path?: Path2D): Path2D; + new(d?: Path2D | string): Path2D; }; interface PaymentAddress { @@ -14623,12 +15599,14 @@ interface PaymentRequestEventMap { } interface PaymentRequest extends EventTarget { - onshippingaddresschange: (this: PaymentRequest, ev: Event) => any; - onshippingoptionchange: (this: PaymentRequest, ev: Event) => any; + readonly id: string; + onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; + onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; readonly shippingType: PaymentShippingType | null; abort(): Promise; + canMakePayment(): 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; @@ -14638,11 +15616,11 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; - new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; }; interface PaymentRequestUpdateEvent extends Event { - updateWith(d: Promise): void; + updateWith(detailsPromise: Promise): void; } declare var PaymentRequestUpdateEvent: { @@ -14656,6 +15634,7 @@ interface PaymentResponse { readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; + readonly requestId: string; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; @@ -14667,16 +15646,50 @@ declare var PaymentResponse: { new(): PaymentResponse; }; +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 Performance { + /** @deprecated */ readonly navigation: PerformanceNavigation; + readonly timeOrigin: number; + /** @deprecated */ 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; + getEntriesByName(name: string, type?: string): any; + getEntriesByType(type: string): any; + /** @deprecated */ getMarks(markName?: string): any; + /** @deprecated */ getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; @@ -14695,6 +15708,7 @@ interface PerformanceEntry { readonly entryType: string; readonly name: string; readonly startTime: number; + toJSON(): any; } declare var PerformanceEntry: { @@ -14738,28 +15752,41 @@ declare var PerformanceNavigation: { }; interface PerformanceNavigationTiming extends PerformanceEntry { + /** @deprecated */ readonly connectEnd: number; + /** @deprecated */ readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; + /** @deprecated */ readonly domLoading: number; + /** @deprecated */ + readonly domainLookupEnd: number; + /** @deprecated */ + readonly domainLookupStart: number; + /** @deprecated */ readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; + /** @deprecated */ readonly navigationStart: number; readonly redirectCount: number; + /** @deprecated */ readonly redirectEnd: number; + /** @deprecated */ readonly redirectStart: number; + /** @deprecated */ readonly requestStart: number; + /** @deprecated */ readonly responseEnd: number; + /** @deprecated */ readonly responseStart: number; readonly type: NavigationType; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly workerStart: number; } declare var PerformanceNavigationTiming: { @@ -14779,6 +15806,7 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly workerStart: number; } declare var PerformanceResourceTiming: { @@ -14789,13 +15817,13 @@ declare var 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 domainLookupEnd: number; + readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -14806,9 +15834,9 @@ interface PerformanceTiming { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly secureConnectionStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; - readonly secureConnectionStart: number; toJSON(): any; } @@ -14817,35 +15845,6 @@ declare var 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 { } @@ -14927,12 +15926,11 @@ declare var 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; + new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent; }; interface Position { @@ -14980,10 +15978,21 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; + new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent; }; +interface PromiseRejectionEvent extends Event { + readonly promise: PromiseLike; + readonly reason: any; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: PromiseLike; + reason?: any; +} + interface PushManager { + readonly supportedContentEncodings: ReadonlyArray; getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; subscribe(options?: PushSubscriptionOptionsInit): Promise; @@ -14995,7 +16004,8 @@ declare var PushManager: { }; interface PushSubscription { - readonly endpoint: USVString; + readonly endpoint: string; + readonly expirationTime: number | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): any; @@ -15017,112 +16027,13 @@ declare var 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 | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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; +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } -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; - readonly signal: AbortSignal; - 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; +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDtlsTransportEventMap { @@ -15168,7 +16079,7 @@ interface RTCDtmfSender extends EventTarget { readonly canInsertDTMF: boolean; readonly duration: number; readonly interToneGap: number; - ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null; readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; @@ -15183,19 +16094,10 @@ declare var 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; + sdpMid: string | null; toJSON(): any; } @@ -15300,28 +16202,28 @@ interface RTCPeerConnection extends EventTarget { 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; + onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null; + oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; + onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; readonly remoteDescription: RTCSessionDescription | null; readonly signalingState: RTCSignalingState; - addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise; addStream(stream: MediaStream): void; close(): void; - createAnswer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - createOffer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, options?: RTCOfferOptions): Promise; + createAnswer(options?: RTCOfferOptions): Promise; + createOffer(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; + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit): 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; @@ -15344,10 +16246,14 @@ declare var RTCPeerConnectionIceEvent: { interface RTCRtpReceiverEventMap { "error": Event; + "msdecodercapacitychange": Event; + "msdsh": Event; } interface RTCRtpReceiver extends RTCStatsProvider { onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -15444,433 +16350,122 @@ declare var RTCStatsProvider: { new(): RTCStatsProvider; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; +interface RandomSource { + getRandomValues(array: T): T; } -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; +declare var RandomSource: { + prototype: RandomSource; + new(): RandomSource; }; -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; - lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; - unlockOrientation(): 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; +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 | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + insertNode(node: Node): void; + isPointInRange(node: Node, offset: number): boolean; + selectNode(node: Node): void; + selectNodeContents(node: Node): void; + setEnd(node: Node, offset: number): void; + setEndAfter(node: Node): void; + setEndBefore(node: Node): void; + setStart(node: Node, offset: number): void; + setStartAfter(node: Node): void; + setStartBefore(node: 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 Selection: { - prototype: Selection; - new(): Selection; +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 ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -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; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; }; -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } -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; +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; }; -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 { +interface Request extends 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 signal: AbortSignal | null; + readonly type: RequestType; readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; + clone(): Request; } -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; }; -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; +interface Response extends Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; } -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; +declare var Response: { + prototype: Response; + new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; }; interface SVGAElement extends SVGGraphicsElement, SVGURIReference { @@ -15990,6 +16585,11 @@ declare var SVGAnimatedNumberList: { new(): SVGAnimatedNumberList; }; +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; readonly baseVal: SVGPreserveAspectRatio; @@ -16126,21 +16726,21 @@ interface SVGElementEventMap extends ElementEventMap { "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; +interface SVGElement extends Element, ElementCSSInlineStyle { + readonly className: any; + onclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null; + onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null; + onload: ((this: SVGElement, ev: Event) => any) | null; + onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null; + readonly ownerSVGElement: SVGSVGElement | null; + readonly viewportElement: SVGElement | null; + /** @deprecated */ 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; @@ -16170,7 +16770,9 @@ declare var SVGElementInstance: { }; interface SVGElementInstanceList { + /** @deprecated */ readonly length: number; + /** @deprecated */ item(index: number): SVGElementInstance; } @@ -16653,7 +17255,9 @@ declare var SVGFETurbulenceElement: { }; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { + /** @deprecated */ readonly filterResX: SVGAnimatedInteger; + /** @deprecated */ readonly filterResY: SVGAnimatedInteger; readonly filterUnits: SVGAnimatedEnumeration; readonly height: SVGAnimatedLength; @@ -16661,6 +17265,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + /** @deprecated */ 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; @@ -16673,6 +17278,19 @@ declare var SVGFilterElement: { new(): SVGFilterElement; }; +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 SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; readonly width: SVGAnimatedLength; @@ -16725,12 +17343,15 @@ declare var SVGGradientElement: { }; interface SVGGraphicsElement extends SVGElement, SVGTests { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; + /** @deprecated */ + readonly farthestViewportElement: SVGElement | null; + /** @deprecated */ + readonly nearestViewportElement: SVGElement | null; readonly transform: SVGAnimatedTransformList; getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; + getCTM(): SVGMatrix | null; + getScreenCTM(): SVGMatrix | null; + /** @deprecated */ 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; @@ -16812,22 +17433,6 @@ declare var 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; @@ -16844,6 +17449,22 @@ declare var SVGLineElement: { new(): SVGLineElement; }; +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 SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -16854,12 +17475,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: 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; @@ -16869,12 +17490,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; }; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { @@ -16958,26 +17579,47 @@ declare var SVGNumberList: { }; interface SVGPathElement extends SVGGraphicsElement { + /** @deprecated */ readonly pathSegList: SVGPathSegList; + /** @deprecated */ createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + /** @deprecated */ createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + /** @deprecated */ createSVGPathSegClosePath(): SVGPathSegClosePath; + /** @deprecated */ createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + /** @deprecated */ createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + /** @deprecated */ createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + /** @deprecated */ createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + /** @deprecated */ createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + /** @deprecated */ createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + /** @deprecated */ createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + /** @deprecated */ getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; @@ -17423,6 +18065,84 @@ declare var SVGRectElement: { new(): SVGRectElement; }; +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + contentScriptType: string; + /** @deprecated */ + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: ((this: SVGSVGElement, ev: Event) => any) | null; + onerror: ((this: SVGSVGElement, ev: Event) => any) | null; + onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onunload: ((this: SVGSVGElement, ev: Event) => any) | null; + onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; + /** @deprecated */ + readonly pixelUnitToMillimeterX: number; + /** @deprecated */ + readonly pixelUnitToMillimeterY: number; + /** @deprecated */ + readonly screenPixelToMillimeterX: number; + /** @deprecated */ + readonly screenPixelToMillimeterY: number; + /** @deprecated */ + 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; + /** @deprecated */ + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + /** @deprecated */ + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + /** @deprecated */ + pauseAnimations(): void; + /** @deprecated */ + setCurrentTime(seconds: number): void; + /** @deprecated */ + suspendRedraw(maxWaitMilliseconds: number): number; + /** @deprecated */ + unpauseAnimations(): void; + /** @deprecated */ + unsuspendRedraw(suspendHandleID: number): void; + /** @deprecated */ + 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 SVGScriptElement extends SVGElement, SVGURIReference { type: string; addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -17465,6 +18185,15 @@ declare var SVGStringList: { new(): SVGStringList; }; +interface SVGStylable { + className: any; +} + +declare var SVGStylable: { + prototype: SVGStylable; + new(): SVGStylable; +}; + interface SVGStyleElement extends SVGElement { disabled: boolean; media: string; @@ -17481,69 +18210,6 @@ declare var 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; @@ -17568,6 +18234,27 @@ declare var SVGSymbolElement: { new(): SVGSymbolElement; }; +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 SVGTests { + readonly requiredExtensions: SVGStringList; + /** @deprecated */ + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + /** @deprecated */ + hasExtension(extension: string): boolean; +} + interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; readonly textLength: SVGAnimatedLength; @@ -17714,18 +18401,10 @@ declare var 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; +interface SVGURIReference { + readonly href: SVGAnimatedString; } -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -}; - interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -17734,9 +18413,9 @@ interface SVGUnitTypes { declare var SVGUnitTypes: SVGUnitTypes; interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; + readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; + readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -17751,7 +18430,8 @@ declare var SVGUseElement: { new(): SVGUseElement; }; -interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { +interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ 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; @@ -17787,6 +18467,477 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; +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; + /** @deprecated */ + 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) | null; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + unlockOrientation(): 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 ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + /** @deprecated */ + readonly bufferSize: number; + /** @deprecated */ + onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null; + 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 ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEvent extends Event { + readonly blockedURI: string; + readonly columnNumber: number; + readonly documentURI: string; + readonly effectiveDirective: string; + readonly lineNumber: number; + readonly originalPolicy: string; + readonly referrer: string; + readonly sourceFile: string; + readonly statusCode: number; + readonly violatedDirective: string; +} + +declare var SecurityPolicyViolationEvent: { + prototype: SecurityPolicyViolationEvent; + new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent; +}; + +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 ServiceUIFrameContext { + getCachedFrameMessage(key: string): string; + postFrameMessage(key: string, data: string): void; +} +declare var ServiceUIFrameContext: ServiceUIFrameContext; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + 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; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): 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: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | 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) | null; + readonly pushManager: PushManager; + readonly scope: string; + 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 ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: "open" | "closed"; +} + +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 | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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) | null; + 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 charLength: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance; +} + +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) | null; + onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + 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(): 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, value: string): void; + [key: string]: any; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + readonly key: string | null; + readonly newValue: string | null; + readonly oldValue: string | null; + readonly storageArea: Storage | null; + readonly url: string; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StorageEventInit extends EventInit { + key?: string; + newValue?: string; + oldValue?: string; + storageArea?: Storage; + url: string; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string | null; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet | null; + readonly title: string | null; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index: number): StyleSheet | null; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SyncManager { getTags(): Promise; register(tag: string): Promise; @@ -17798,8 +18949,8 @@ declare var SyncManager: { }; interface Text extends CharacterData { - readonly wholeText: string; readonly assignedSlot: HTMLSlotElement | null; + readonly wholeText: string; splitText(offset: number): Text; } @@ -17808,10 +18959,30 @@ declare var Text: { new(data?: string): Text; }; +interface TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + 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; @@ -17862,10 +19033,10 @@ interface TextTrack extends EventTarget { 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; + mode: TextTrackMode | number; + oncuechange: ((this: TextTrack, ev: Event) => any) | null; + onerror: ((this: TextTrack, ev: Event) => any) | null; + onload: ((this: TextTrack, ev: Event) => any) | null; readonly readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; @@ -17902,8 +19073,8 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { endTime: number; id: string; - onenter: (this: TextTrackCue, ev: Event) => any; - onexit: (this: TextTrackCue, ev: Event) => any; + onenter: ((this: TextTrackCue, ev: Event) => any) | null; + onexit: ((this: TextTrackCue, ev: Event) => any) | null; pauseOnExit: boolean; startTime: number; text: string; @@ -17989,6 +19160,7 @@ interface TouchEvent extends UIEvent { readonly shiftKey: boolean; readonly targetTouches: TouchList; readonly touches: TouchList; + /** @deprecated */ readonly which: number; } @@ -17997,6 +19169,12 @@ declare var TouchEvent: { new(type: string, touchEventInit?: TouchEventInit): TouchEvent; }; +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + interface TouchList { readonly length: number; item(index: number): Touch | null; @@ -18030,17 +19208,18 @@ declare var TransitionEvent: { interface TreeWalker { currentNode: Node; + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; + firstChild(): Node | null; + lastChild(): Node | null; + nextNode(): Node | null; + nextSibling(): Node | null; + parentNode(): Node | null; + previousNode(): Node | null; + previousSibling(): Node | null; } declare var TreeWalker: { @@ -18059,15 +19238,6 @@ declare var 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; @@ -18079,8 +19249,8 @@ interface URL { port: string; protocol: string; search: string; - username: string; readonly searchParams: URLSearchParams; + username: string; toString(): string; } @@ -18091,6 +19261,142 @@ declare var URL: { revokeObjectURL(url: string): 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; + new (init?: string | URLSearchParams): URLSearchParams; +}; + +interface VRDisplay extends EventTarget { + readonly capabilities: VRDisplayCapabilities; + depthFar: number; + depthNear: number; + readonly displayId: number; + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + readonly stageParameters: VRStageParameters | null; + cancelAnimationFrame(handle: number): void; + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + getFrameData(frameData: VRFrameData): boolean; + getLayers(): VRLayer[]; + /** @deprecated */ + getPose(): VRPose; + requestAnimationFrame(callback: FrameRequestCallback): number; + requestPresent(layers: VRLayer[]): Promise; + resetPose(): void; + submitFrame(pose?: VRPose): void; +} + +declare var VRDisplay: { + prototype: VRDisplay; + new(): VRDisplay; +}; + +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} + +declare var VRDisplayCapabilities: { + prototype: VRDisplayCapabilities; + new(): VRDisplayCapabilities; +}; + +interface VRDisplayEvent extends Event { + readonly display: VRDisplay; + readonly reason: VRDisplayEventReason | null; +} + +declare var VRDisplayEvent: { + prototype: VRDisplayEvent; + new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent; +}; + +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} + +declare var VREyeParameters: { + prototype: VREyeParameters; + new(): VREyeParameters; +}; + +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} + +declare var VRFieldOfView: { + prototype: VRFieldOfView; + new(): VRFieldOfView; +}; + +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} + +declare var VRFrameData: { + prototype: VRFrameData; + new(): VRFrameData; +}; + +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} + +declare var VRPose: { + prototype: VRPose; + new(): VRPose; +}; + interface ValidityState { readonly badInput: boolean; readonly customError: boolean; @@ -18099,10 +19405,10 @@ interface ValidityState { readonly rangeUnderflow: boolean; readonly stepMismatch: boolean; readonly tooLong: boolean; + readonly tooShort: boolean; readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; - readonly tooShort: boolean; } declare var ValidityState: { @@ -18145,9 +19451,9 @@ interface VideoTrackListEventMap { 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; + onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: VideoTrackList, ev: Event) => any) | null; + onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; @@ -18163,6 +19469,137 @@ declare var VideoTrackList: { new(): VideoTrackList; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly RGB32F_EXT: number; + readonly RGBA32F_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + 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_SRGB8_ALPHA8_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_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; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +}; + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_SRGB_S3TC_DXT1_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_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +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 WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_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 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 DRAW_BUFFER0_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 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 MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + interface WaveShaperNode extends AudioNode { curve: Float32Array | null; oversample: OverSampleType; @@ -18174,8 +19611,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -18195,44 +19632,6 @@ declare var 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; @@ -18309,8 +19708,8 @@ interface WebGLRenderingContext { 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; + bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void; + bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void; checkFramebufferStatus(target: number): number; clear(mask: number): void; clearColor(red: number, green: number, blue: number, alpha: number): void; @@ -18318,8 +19717,8 @@ interface WebGLRenderingContext { 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; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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; @@ -18409,7 +19808,7 @@ interface WebGLRenderingContext { 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; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | 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; @@ -18574,13 +19973,13 @@ interface WebGLRenderingContext { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -18605,9 +20004,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -18637,18 +20036,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -18682,20 +20081,6 @@ interface WebGLRenderingContext { 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; @@ -18728,9 +20113,23 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -18876,13 +20275,13 @@ declare var WebGLRenderingContext: { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -18907,9 +20306,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -18939,18 +20338,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -18984,20 +20383,6 @@ declare var WebGLRenderingContext: { 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; @@ -19030,9 +20415,23 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -19093,6 +20492,9 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; +interface WebGLVertexArrayObjectOES { +} + interface WebKitCSSMatrix { a: number; b: number; @@ -19193,18 +20595,6 @@ declare var 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; @@ -19213,18 +20603,18 @@ interface WebSocketEventMap { } interface WebSocket extends EventTarget { - binaryType: string; + binaryType: BinaryType; 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; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; readonly protocol: string; readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: USVString | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; @@ -19269,8 +20659,6 @@ declare var WheelEvent: { interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "afterprint": Event; - "beforeprint": Event; "beforeunload": BeforeUnloadEvent; "blur": FocusEvent; "canplay": Event; @@ -19292,7 +20680,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; @@ -19314,21 +20702,21 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "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; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -19358,19 +20746,32 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "touchstart": TouchEvent; "unload": Event; "volumechange": Event; + "vrdisplayactivate": Event; + "vrdisplayblur": Event; + "vrdisplayconnect": Event; + "vrdisplaydeactivate": Event; + "vrdisplaydisconnect": Event; + "vrdisplayfocus": Event; + "vrdisplaypointerrestricted": Event; + "vrdisplaypointerunrestricted": Event; + "vrdisplaypresentchange": Event; "waiting": Event; } interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { + Blob: typeof Blob; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; readonly applicationCache: ApplicationCache; readonly caches: CacheStorage; readonly clientInformation: Navigator; readonly closed: boolean; readonly crypto: Crypto; + customElements: CustomElementRegistry; defaultStatus: string; readonly devicePixelRatio: number; - readonly document: Document; readonly doNotTrack: string; + readonly document: Document; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -19380,7 +20781,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly innerWidth: number; readonly isSecureContext: boolean; readonly length: number; - readonly location: Location; + location: Location; readonly locationbar: BarProp; readonly menubar: BarProp; readonly msContentScript: ExtensionScriptApis; @@ -19388,99 +20789,106 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + onabort: ((this: Window, ev: UIEvent) => any) | null; + onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; + onblur: ((this: Window, ev: FocusEvent) => any) | null; + oncanplay: ((this: Window, ev: Event) => any) | null; + oncanplaythrough: ((this: Window, ev: Event) => any) | null; + onchange: ((this: Window, ev: Event) => any) | null; + onclick: ((this: Window, ev: MouseEvent) => any) | null; + oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; + oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; + ondblclick: ((this: Window, ev: MouseEvent) => any) | null; + ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; + ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; + ondrag: ((this: Window, ev: DragEvent) => any) | null; + ondragend: ((this: Window, ev: DragEvent) => any) | null; + ondragenter: ((this: Window, ev: DragEvent) => any) | null; + ondragleave: ((this: Window, ev: DragEvent) => any) | null; + ondragover: ((this: Window, ev: DragEvent) => any) | null; + ondragstart: ((this: Window, ev: DragEvent) => any) | null; + ondrop: ((this: Window, ev: DragEvent) => any) | null; + ondurationchange: ((this: Window, ev: Event) => any) | null; + onemptied: ((this: Window, ev: Event) => any) | null; + onended: ((this: Window, ev: Event) => any) | null; 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; + onfocus: ((this: Window, ev: FocusEvent) => any) | null; + onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; + oninput: ((this: Window, ev: Event) => any) | null; + oninvalid: ((this: Window, ev: Event) => any) | null; + onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; + onload: ((this: Window, ev: Event) => any) | null; + onloadeddata: ((this: Window, ev: Event) => any) | null; + onloadedmetadata: ((this: Window, ev: Event) => any) | null; + onloadstart: ((this: Window, ev: Event) => any) | null; + onmessage: ((this: Window, ev: MessageEvent) => any) | null; + onmousedown: ((this: Window, ev: MouseEvent) => any) | null; + onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; + onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; + onmousemove: ((this: Window, ev: MouseEvent) => any) | null; + onmouseout: ((this: Window, ev: MouseEvent) => any) | null; + onmouseover: ((this: Window, ev: MouseEvent) => any) | null; + onmouseup: ((this: Window, ev: MouseEvent) => any) | null; + onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; + onmsgesturechange: ((this: Window, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; + onmsgestureend: ((this: Window, ev: Event) => any) | null; + onmsgesturehold: ((this: Window, ev: Event) => any) | null; + onmsgesturestart: ((this: Window, ev: Event) => any) | null; + onmsgesturetap: ((this: Window, ev: Event) => any) | null; + onmsinertiastart: ((this: Window, ev: Event) => any) | null; + onmspointercancel: ((this: Window, ev: Event) => any) | null; + onmspointerdown: ((this: Window, ev: Event) => any) | null; + onmspointerenter: ((this: Window, ev: Event) => any) | null; + onmspointerleave: ((this: Window, ev: Event) => any) | null; + onmspointermove: ((this: Window, ev: Event) => any) | null; + onmspointerout: ((this: Window, ev: Event) => any) | null; + onmspointerover: ((this: Window, ev: Event) => any) | null; + onmspointerup: ((this: Window, ev: Event) => any) | null; + onoffline: ((this: Window, ev: Event) => any) | null; + ononline: ((this: Window, ev: Event) => any) | null; + onorientationchange: ((this: Window, ev: Event) => any) | null; + onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpause: ((this: Window, ev: Event) => any) | null; + onplay: ((this: Window, ev: Event) => any) | null; + onplaying: ((this: Window, ev: Event) => any) | null; + onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; + onprogress: ((this: Window, ev: ProgressEvent) => any) | null; + onratechange: ((this: Window, ev: Event) => any) | null; + onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; + onreset: ((this: Window, ev: Event) => any) | null; + onresize: ((this: Window, ev: UIEvent) => any) | null; + onscroll: ((this: Window, ev: UIEvent) => any) | null; + onseeked: ((this: Window, ev: Event) => any) | null; + onseeking: ((this: Window, ev: Event) => any) | null; + onselect: ((this: Window, ev: UIEvent) => any) | null; + onstalled: ((this: Window, ev: Event) => any) | null; + onstorage: ((this: Window, ev: StorageEvent) => any) | null; + onsubmit: ((this: Window, ev: Event) => any) | null; + onsuspend: ((this: Window, ev: Event) => any) | null; + ontimeupdate: ((this: Window, ev: Event) => any) | null; 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; + onunload: ((this: Window, ev: Event) => any) | null; + onvolumechange: ((this: Window, ev: Event) => any) | null; + onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplayblur: ((this: Window, ev: Event) => any) | null; + onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + onwaiting: ((this: Window, ev: Event) => any) | null; + readonly opener: any; + readonly orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; readonly pageXOffset: number; @@ -19493,9 +20901,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; - readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; + readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -19504,20 +20912,18 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + 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; departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; getSelection(): Selection; matchMedia(mediaQuery: string): MediaQueryList; moveBy(x?: number, y?: number): void; @@ -19531,19 +20937,17 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window requestAnimationFrame(callback: FrameRequestCallback): number; resizeBy(x?: number, y?: number): void; resizeTo(x?: number, y?: number): void; + scroll(options?: ScrollToOptions): void; scroll(x?: number, y?: number): void; + scrollBy(options?: ScrollToOptions): void; scrollBy(x?: number, y?: number): void; + scrollTo(options?: ScrollToOptions): 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; @@ -19555,12 +20959,79 @@ declare var Window: { new(): Window; }; +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowEventHandlersEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "hashchange": HashChangeEvent; + "message": MessageEvent; + "offline": Event; + "online": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface WindowEventHandlers { + onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; + onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; + ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; + onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers extends 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 WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; } interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: Worker, ev: MessageEvent) => any; + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** @deprecated */ postMessage(message: any, transfer?: any[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -19574,6 +21045,41 @@ declare var Worker: { new(stringUrl: string): Worker; }; +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +declare var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; +}; + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: any): Promise; +} + +declare var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(): WritableStreamDefaultWriter; +}; + 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; @@ -19591,7 +21097,8 @@ interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -19603,15 +21110,12 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { 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; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): 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; @@ -19635,6 +21139,30 @@ declare var XMLHttpRequest: { readonly UNSENT: 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) | null; + onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + 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 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; @@ -19738,1070 +21266,16 @@ declare var 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; +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: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[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 ElementCreationOptions { - is?: 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 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; -} - -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 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; - 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; -} - -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; -} - -interface AnimationKeyFrame { - offset?: number | null | (number | null)[]; - easing?: string | string[]; - [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; -} - -interface AnimationOptions { - id?: string; - delay?: number; - direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; - duration?: number; - easing?: string; - endDelay?: number; - fill?: "none" | "forwards" | "backwards" | "both"| "auto"; - iterationStart?: number; - iterations?: number; -} - -interface AnimationTimeline { - readonly currentTime: number | null; -} - -interface ComputedTimingProperties { - endTime: number; - activeDuration: number; - localTime: number | null; - progress: number | null; - currentIteration: number | null; -} - -interface AnimationEffectReadOnly { - readonly timing: number; - getComputedTiming(): ComputedTimingProperties; -} - -interface AnimationPlaybackEventInit extends EventInit { - currentTime?: number | null; - timelineTime?: number | null; -} - -interface AnimationPlaybackEvent extends Event { - readonly currentTime: number | null; - readonly timelineTime: number | null; -} - -declare var AnimationPlaybackEvent: { - prototype: AnimationPlaybackEvent; - new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; -}; - -interface Animation { - currentTime: number | null; - effect: AnimationEffectReadOnly; - readonly finished: Promise; - id: string; - readonly pending: boolean; - readonly playState: "idle" | "running" | "paused" | "finished"; - playbackRate: number; - readonly ready: Promise; - startTime: number; - timeline: AnimationTimeline; - oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; - onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; - cancel(): void; - finish(): void; - pause(): void; - play(): void; - reverse(): void; -} - -declare var Animation: { - prototype: Animation; - new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; }; declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; @@ -20809,66 +21283,95 @@ declare type EventListenerOrEventListenerObject = EventListener | EventListenerO interface DecodeErrorCallback { (error: DOMException): void; } + interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } + interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; } + +interface EventHandlerNonNull { + (event: Event): any; +} + interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, 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 MediaQueryListListener { + (mql: MediaQueryList): void; } + 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 WritableStreamChunkCallback { + (chunk: any, controller: WritableStreamDefaultController): void; +} + +interface WritableStreamDefaultControllerCallback { + (controller: WritableStreamDefaultController): void; +} + +interface WritableStreamErrorCallback { + (reason: string): void; +} + interface HTMLElementTagNameMap { "a": HTMLAnchorElement; "abbr": HTMLElement; @@ -20995,7 +21498,6 @@ interface HTMLElementTagNameMap { "var": HTMLElement; "video": HTMLVideoElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } @@ -21058,18 +21560,28 @@ interface SVGElementTagNameMap { /** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ 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 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 Blob: typeof Blob; +declare var URL: typeof URL; +declare var URLSearchParams: typeof URLSearchParams; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; declare var closed: boolean; declare var crypto: Crypto; +declare var customElements: CustomElementRegistry; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var document: Document; declare var doNotTrack: string; +declare var document: Document; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -21087,97 +21599,104 @@ 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 onabort: ((this: Window, ev: UIEvent) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +declare var onchange: ((this: Window, ev: Event) => any) | null; +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; +declare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; +declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +declare var onemptied: ((this: Window, ev: Event) => any) | null; +declare var onended: ((this: Window, ev: Event) => any) | null; 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 onfocus: ((this: Window, ev: FocusEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onload: ((this: Window, ev: Event) => any) | null; +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadstart: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; +declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; +declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; +declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; +declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; +declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; +declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; +declare var onmspointermove: ((this: Window, ev: Event) => any) | null; +declare var onmspointerout: ((this: Window, ev: Event) => any) | null; +declare var onmspointerover: ((this: Window, ev: Event) => any) | null; +declare var onmspointerup: ((this: Window, ev: Event) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onorientationchange: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpause: ((this: Window, ev: Event) => any) | null; +declare var onplay: ((this: Window, ev: Event) => any) | null; +declare var onplaying: ((this: Window, ev: Event) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onratechange: ((this: Window, ev: Event) => any) | null; +declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onseeked: ((this: Window, ev: Event) => any) | null; +declare var onseeking: ((this: Window, ev: Event) => any) | null; +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; 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 onunload: ((this: Window, ev: Event) => any) | null; +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; +declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; @@ -21192,9 +21711,9 @@ 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 scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -21203,17 +21722,18 @@ 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 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 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 getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; declare function getSelection(): Selection; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; @@ -21227,23 +21747,21 @@ 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(options?: ScrollToOptions): void; declare function scroll(x?: number, y?: number): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(options?: ScrollToOptions): 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 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; @@ -21254,26 +21772,36 @@ 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 onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; 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 fetch(input?: Request | string, 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 ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type IDBValidKey = number | string | Date | IDBArrayKey; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = Blob | BufferSource | FormData | string; +type MutationRecordType = "attributes" | "characterData" | "childList"; +type AAGUID = string; +type BodyInit = any; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; @@ -21295,9 +21823,6 @@ 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; @@ -21306,35 +21831,32 @@ 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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type AppendMode = "segments" | "sequence"; +type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "suspended" | "running" | "closed"; +type BinaryType = "blob" | "arraybuffer"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanPlayTypeResult = "" | "maybe" | "probably"; type CanvasFillRule = "nonzero" | "evenodd"; type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; +type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; +type EndOfStreamError = "network" | "decode"; type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; +type GamepadHand = "" | "left" | "right"; +type GamepadHapticActuatorType = "vibration"; type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type GamepadMappingType = "" | "standard"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; 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"; @@ -21342,25 +21864,23 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaStreamTrackState = "live" | "ended"; 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 PanningModelType = "equalpower" | "HRTF"; +type PaymentComplete = "success" | "fail" | "unknown"; 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"; @@ -21368,9 +21888,9 @@ 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 RTCIceGatherPolicy = "all" | "nohost" | "relay"; 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"; @@ -21381,9 +21901,22 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " 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 ReadyState = "closed" | "open" | "ended"; +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 ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; +type TextTrackMode = "disabled" | "hidden" | "showing"; type Transport = "usb" | "nfc" | "ble"; +type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; +type VREye = "left" | "right"; type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/lib.esnext.d.ts b/lib/lib.esnext.d.ts index 0947f078418..095e46de36f 100644 --- a/lib/lib.esnext.d.ts +++ b/lib/lib.esnext.d.ts @@ -21,4 +21,3 @@ and limitations under the License. /// /// /// -/// diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index 5f047aa2673..0723e558ee8 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -21,8 +21,6 @@ and limitations under the License. /// /// /// -/// - ///////////////////////////// @@ -37,10 +35,49 @@ interface Account { rpDisplayName: string; } +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + interface Algorithm { name: string; } +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + interface AnimationEventInit extends EventInit { animationName?: string; elapsedTime?: number; @@ -49,10 +86,71 @@ interface AnimationEventInit extends EventInit { interface AssertionOptions { allowList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioContextInfo { + currentTime?: number; + sampleRate?: number; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioParamDescriptor { + defaultValue?: number; + maxValue?: number; + minValue?: number; + name?: string; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: number; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface ByteLengthChunk { + byteLength?: number; +} + interface CacheQueryOptions { cacheName?: string; ignoreMethod?: boolean; @@ -60,6 +158,14 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + interface ClientData { challenge: string; extensions?: WebAuthnExtensions; @@ -69,6 +175,12 @@ interface ClientData { tokenBinding?: string; } +interface ClientQueryOptions { + includeReserved?: boolean; + includeUncontrolled?: boolean; + type?: ClientTypes; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; @@ -83,6 +195,10 @@ interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation arrayOfDomainStrings?: string[]; } +interface ConstantSourceOptions { + offset?: number; +} + interface ConstrainBooleanParameters { exact?: boolean; ideal?: boolean; @@ -108,10 +224,27 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + interface CustomEventInit extends EventInit { detail?: T; } +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + interface DeviceAccelerationDict { x?: number | null; y?: number | null; @@ -142,18 +275,39 @@ interface DeviceRotationRateDict { gamma?: number | null; } -interface DOMRectInit { - height?: number; - width?: number; - x?: number; - y?: number; -} - interface DoubleRange { max?: number; min?: number; } +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: string; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: string | Algorithm; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -163,9 +317,13 @@ interface ErrorEventInit extends EventInit { } interface EventInit { - scoped?: boolean; bubbles?: boolean; cancelable?: boolean; + scoped?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; } interface EventModifierInit extends UIEventInit { @@ -190,6 +348,24 @@ interface ExceptionInformation { domain?: string | null; } +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: object | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + request: Request; + reservedClientId?: string; + targetClientId?: string; +} + interface FocusEventInit extends UIEventInit { relatedTarget?: EventTarget | null; } @@ -209,8 +385,12 @@ interface FocusNavigationOrigin { originWidth?: number; } +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + interface GamepadEventInit extends EventInit { - gamepad?: Gamepad | null; + gamepad?: Gamepad; } interface GetNotificationOptions { @@ -218,8 +398,29 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string | null; - oldURL?: string | null; + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: string | Algorithm; + info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface HmacImportParams extends Algorithm { + hash: string | Algorithm; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: string | Algorithm; + length?: number; } interface IDBIndexParameters { @@ -232,10 +433,15 @@ interface IDBObjectStoreParameters { keyPath?: string | string[]; } +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + interface IntersectionObserverEntryInit { - isIntersecting: boolean; boundingClientRect: DOMRectInit; intersectionRect: DOMRectInit; + isIntersecting: boolean; rootBounds: DOMRectInit; target: Element; time: number; @@ -247,8 +453,29 @@ interface IntersectionObserverInit { threshold?: number | number[]; } +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + interface KeyAlgorithm { - name?: string; + name: string; } interface KeyboardEventInit extends EventModifierInit { @@ -263,125 +490,6 @@ interface LongRange { 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; @@ -472,6 +580,16 @@ interface MSCredentialSpec { type: MSCredentialType; } +interface MSDCCEventInit extends EventInit { + maxFr?: number; + maxFs?: number; +} + +interface MSDSHEventInit extends EventInit { + sources?: number[]; + timestamp?: number; +} + interface MSDelay { roundTrip?: number; roundTripMax?: number; @@ -489,7 +607,13 @@ interface MSDescription extends RTCStats { interface MSFIDOCredentialParameters extends MSCredentialParameters { algorithm?: string | Algorithm; - authenticators?: AAGUID[]; + authenticators?: string[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; } interface MSIceWarningFlags { @@ -517,12 +641,6 @@ interface MSIceWarningFlags { useCandidateChecksFailed?: boolean; } -interface MSIPAddressInfo { - ipAddr?: string; - manufacturerMacAddrMask?: string; - port?: number; -} - interface MSJitter { interArrival?: number; interArrivalMax?: number; @@ -551,8 +669,8 @@ interface MSNetworkInterfaceType { interfaceTypeEthernet?: boolean; interfaceTypePPP?: boolean; interfaceTypeTunnel?: boolean; - interfaceTypeWireless?: boolean; interfaceTypeWWAN?: boolean; + interfaceTypeWireless?: boolean; } interface MSOutboundNetwork extends MSNetwork { @@ -589,8 +707,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { iceRole?: RTCIceRole; iceWarningFlags?: MSIceWarningFlags; interfaces?: MSNetworkInterfaceType; - localAddress?: string; localAddrType?: MSIceAddrType; + localAddress?: string; localInterface?: MSNetworkInterfaceType; localMR?: string; localMRTCPPort?: number; @@ -604,8 +722,8 @@ interface MSTransportDiagnosticsStats extends RTCStats { portRangeMax?: number; portRangeMin?: number; protocol?: RTCIceProtocol; - remoteAddress?: string; remoteAddrType?: MSIceAddrType; + remoteAddress?: string; remoteMR?: string; remoteMRTCPPort?: number; remoteSite?: string; @@ -674,6 +792,133 @@ interface MSVideoSendPayload extends MSVideoPayload { sendVideoStreamsMax?: number; } +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +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 MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + channelCount?: number | ConstrainLongRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + displaySurface?: string | string[] | ConstrainDOMStringParameters; + echoCancellation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + latency?: number | ConstrainDoubleRange; + logicalSurface?: boolean | ConstrainBooleanParameters; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +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 { + channel?: string; + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: Window | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + interface MsZoomToOptions { animate?: string; contentX?: number; @@ -693,8 +938,14 @@ interface MutationObserverInit { subtree?: boolean; } +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; +} + interface NotificationOptions { body?: string; + data?: any; dir?: NotificationDirection; icon?: string; lang?: string; @@ -705,18 +956,49 @@ interface ObjectURLOptions { oneTimeOnly?: boolean; } +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + interface PaymentCurrencyAmount { currency: string; currencySystem?: string; value: string; } -interface PaymentDetails { +interface PaymentDetailsBase { displayItems?: PaymentItem[]; - error?: string; modifiers?: PaymentDetailsModifier[]; shippingOptions?: PaymentShippingOption[]; - total?: PaymentItem; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; } interface PaymentDetailsModifier { @@ -726,6 +1008,11 @@ interface PaymentDetailsModifier { total?: PaymentItem; } +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + total?: PaymentItem; +} + interface PaymentItem { amount: PaymentCurrencyAmount; label: string; @@ -755,10 +1042,21 @@ interface PaymentShippingOption { selected?: boolean; } +interface Pbkdf2Params extends Algorithm { + hash: string | Algorithm; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + interface PeriodicWaveConstraints { disableNormalization?: boolean; } +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[]; + real?: number[]; +} + interface PointerEventInit extends MouseEventInit { height?: number; isPrimary?: boolean; @@ -786,35 +1084,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface PushEventInit extends ExtendableEventInit { + data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | null; + applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; userVisibleOnly?: boolean; } -interface RegistrationOptions { - scope?: string; -} - -interface RequestInit { - signal?: AbortSignal; - body?: Blob | BufferSource | FormData | string | null; - 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 QueuingStrategy { + highWaterMark?: number; + size?: WritableStreamChunkCallback; } interface RTCConfiguration { @@ -824,6 +1110,10 @@ interface RTCConfiguration { peerIdentity?: string; } +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + interface RTCDtlsFingerprint { algorithm?: string; value?: string; @@ -834,10 +1124,6 @@ interface RTCDtlsParameters { role?: RTCDtlsRole; } -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - interface RTCIceCandidateAttributes extends RTCStats { addressSourceUrl?: string; candidateType?: RTCStatsIceCandidateType; @@ -865,8 +1151,8 @@ interface RTCIceCandidateDictionary { interface RTCIceCandidateInit { candidate?: string; - sdpMid?: string; sdpMLineIndex?: number; + sdpMid?: string; } interface RTCIceCandidatePair { @@ -921,13 +1207,13 @@ interface RTCMediaStreamTrackStats extends RTCStats { echoReturnLoss?: number; echoReturnLossEnhancement?: number; frameHeight?: number; + frameWidth?: number; framesCorrupted?: number; framesDecoded?: number; framesDropped?: number; framesPerSecond?: number; framesReceived?: number; framesSent?: number; - frameWidth?: number; remoteSource?: boolean; ssrcIds?: string[]; trackIdentifier?: string; @@ -951,6 +1237,20 @@ interface RTCPeerConnectionIceEventInit extends EventInit { candidate?: RTCIceCandidate; } +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + mediaType?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + interface RTCRtcpFeedback { parameter?: string; type?: string; @@ -972,9 +1272,9 @@ interface RTCRtpCapabilities { interface RTCRtpCodecCapability { clockRate?: number; kind?: string; - maxptime?: number; maxSpatialLayers?: number; maxTemporalLayers?: number; + maxptime?: number; name?: string; numChannels?: number; options?: any; @@ -991,7 +1291,7 @@ interface RTCRtpCodecParameters { name?: string; numChannels?: number; parameters?: any; - payloadType?: any; + payloadType?: number; ptime?: number; rtcpFeedback?: RTCRtcpFeedback[]; } @@ -1050,19 +1350,6 @@ 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; @@ -1114,8 +1401,70 @@ interface RTCTransportStats extends RTCStats { selectedCandidatePairId?: string; } +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + signal?: AbortSignal; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: string | Algorithm; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: string | Algorithm; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + interface ScopedCredentialDescriptor { - id: BufferSource; + id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; transports?: Transport[]; type: ScopedCredentialType; } @@ -1123,7 +1472,7 @@ interface ScopedCredentialDescriptor { interface ScopedCredentialOptions { excludeList?: ScopedCredentialDescriptor[]; extensions?: WebAuthnExtensions; - rpId?: USVString; + rpId?: string; timeoutSeconds?: number; } @@ -1132,6 +1481,19 @@ interface ScopedCredentialParameters { type: ScopedCredentialType; } +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; @@ -1142,11 +1504,16 @@ interface ServiceWorkerMessageEventInit extends EventInit { interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; + charLength?: number; elapsedTime?: number; name?: string; utterance?: SpeechSynthesisUtterance | null; } +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + interface StoreExceptionsInformation extends ExceptionInformation { detailURI?: string | null; explanationString?: string | null; @@ -1157,6 +1524,20 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat arrayOfDomainStrings?: string[]; } +interface SyncEventInit extends ExtendableEventInit { + lastChance?: boolean; + tag: string; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + interface TrackEventInit extends EventInit { track?: VideoTrack | AudioTrack | TextTrack | null; } @@ -1171,14 +1552,43 @@ interface UIEventInit extends EventInit { view?: Window | null; } +interface UnderlyingSink { + abort?: WritableStreamErrorCallback; + close?: WritableStreamDefaultControllerCallback; + start: WritableStreamDefaultControllerCallback; + write?: WritableStreamChunkCallback; +} + +interface VRDisplayEventInit extends EventInit { + display: VRDisplay; + reason?: VRDisplayEventReason; +} + +interface VRLayer { + leftBounds?: number[] | null; + rightBounds?: number[] | null; + source?: HTMLCanvasElement | null; +} + +interface VRStageParameters { + sittingToStandingTransform?: Float32Array; + sizeX?: number; + sizeY?: number; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[]; + oversample?: OverSampleType; +} + interface WebAuthnExtensions { } interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; antialias?: boolean; depth?: boolean; + failIfMajorPerformanceCaveat?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; stencil?: boolean; @@ -1205,6 +1615,67 @@ type WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMErr type WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; }; +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 AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + 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 AesCfbParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1222,23 +1693,39 @@ declare var 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; +interface Animation { + currentTime: number | null; + effect: AnimationEffectReadOnly; + readonly finished: Promise; + id: string; + readonly pending: boolean; + readonly playState: "idle" | "running" | "paused" | "finished"; + playbackRate: number; + readonly ready: Promise; + startTime: number; + timeline: AnimationTimeline; + cancel(): void; + finish(): void; + oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; + onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; + pause(): void; + play(): void; + reverse(): void; } -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; }; +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + 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: { @@ -1246,6 +1733,43 @@ declare var AnimationEvent: { new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; }; +interface AnimationKeyFrame { + easing?: string | string[]; + offset?: number | null | (number | null)[]; + [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; +} + +interface AnimationOptions { + delay?: number; + direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; + duration?: number; + easing?: string; + endDelay?: number; + fill?: "none" | "forwards" | "backwards" | "both"| "auto"; + id?: string; + iterationStart?: number; + iterations?: number; +} + +interface AnimationPlaybackEvent extends Event { + readonly currentTime: number | null; + readonly timelineTime: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +interface AnimationTimeline { + readonly currentTime: number | null; +} + interface ApplicationCacheEventMap { "cached": Event; "checking": Event; @@ -1258,14 +1782,14 @@ interface ApplicationCacheEventMap { } 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; + oncached: ((this: ApplicationCache, ev: Event) => any) | null; + onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + onerror: ((this: ApplicationCache, ev: Event) => any) | null; + onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; readonly status: number; abort(): void; swapCache(): void; @@ -1293,9 +1817,13 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; +interface AssignedNodesOptions { + flatten?: boolean; +} + interface Attr extends Node { readonly name: string; - readonly ownerElement: Element; + readonly ownerElement: Element | null; readonly prefix: string | null; readonly specified: boolean; value: string; @@ -1322,7 +1850,7 @@ declare var AudioBuffer: { }; interface AudioBufferSourceNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface AudioBufferSourceNode extends AudioNode { @@ -1331,7 +1859,7 @@ interface AudioBufferSourceNode extends AudioNode { loop: boolean; loopEnd: number; loopStart: number; - onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null; readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; @@ -1354,7 +1882,7 @@ interface AudioContextBase extends EventTarget { readonly currentTime: number; readonly destination: AudioDestinationNode; readonly listener: AudioListener; - onstatechange: (this: AudioContext, ev: Event) => any; + onstatechange: ((this: AudioContext, ev: Event) => any) | null; readonly sampleRate: number; readonly state: AudioContextState; close(): Promise; @@ -1404,10 +1932,15 @@ declare var AudioDestinationNode: { }; interface AudioListener { + /** @deprecated */ dopplerFactor: number; + /** @deprecated */ speedOfSound: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -1425,9 +1958,13 @@ interface AudioNode extends EventTarget { 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; + disconnect(): void; + disconnect(output: number): void; + disconnect(destination: AudioNode): void; + disconnect(destination: AudioNode, output: number): void; + disconnect(destination: AudioNode, output: number, input: number): void; + disconnect(destination: AudioParam): void; + disconnect(destination: AudioParam, output: number): void; } declare var AudioNode: { @@ -1438,12 +1975,12 @@ declare var AudioNode: { interface AudioParam { readonly defaultValue: number; value: number; - cancelScheduledValues(startTime: number): AudioParam; + cancelScheduledValues(cancelTime: 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; + setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam; } declare var AudioParam: { @@ -1484,9 +2021,9 @@ interface AudioTrackListEventMap { 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; + onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: AudioTrackList, ev: Event) => any) | null; + onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -1519,11 +2056,33 @@ declare var BeforeUnloadEvent: { new(): BeforeUnloadEvent; }; +interface BhxBrowser { + readonly lastError: DOMException; + checkMatchesGlobExpression(pattern: string, value: string): boolean; + checkMatchesUriExpression(pattern: string, value: string): boolean; + clearLastError(): void; + currentWindowId(): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; + genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + getThisAddress(): any; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericListenerHandler(eventHandler: Function): void; + setLastError(parameters: string): void; + webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void; +} + +declare var BhxBrowser: { + prototype: BhxBrowser; + new(): BhxBrowser; +}; + interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; readonly detune: AudioParam; readonly frequency: AudioParam; readonly gain: AudioParam; - readonly Q: AudioParam; type: BiquadFilterType; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } @@ -1546,113 +2105,50 @@ declare var 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; +interface BlobPropertyBag { + endings?: string; + type?: string; } -declare var Cache: { - prototype: Cache; - new(): Cache; +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + close(): void; + postMessage(message: any): 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 CacheStorage { - delete(cacheName: string): Promise; - has(cacheName: string): Promise; - keys(): Promise; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; - open(cacheName: string): Promise; +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; } -declare var CacheStorage: { - prototype: CacheStorage; - new(): CacheStorage; -}; - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; +interface ByteLengthQueuingStrategy { + highWaterMark: number; + size(chunk?: any): number; } -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; +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(strategy: QueuingStrategy): ByteLengthQueuingStrategy; }; interface CDATASection extends Text { @@ -1663,190 +2159,8 @@ declare var 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 { + escape(value: string): string; supports(property: string, value?: string): boolean; } declare var CSS: CSS; @@ -1906,7 +2220,7 @@ interface CSSKeyframesRule extends CSSRule { name: string; appendRule(rule: string): void; deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; + findRule(rule: string): CSSKeyframeRule | null; } declare var CSSKeyframesRule: { @@ -1947,14 +2261,14 @@ declare var CSSPageRule: { interface CSSRule { cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; + readonly parentRule: CSSRule | null; + readonly parentStyleSheet: CSSStyleSheet | null; 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 KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1970,8 +2284,8 @@ declare var CSSRule: { readonly CHARSET_RULE: number; readonly FONT_FACE_RULE: number; readonly IMPORT_RULE: number; - readonly KEYFRAME_RULE: number; readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; readonly MEDIA_RULE: number; readonly NAMESPACE_RULE: number; readonly PAGE_RULE: number; @@ -1983,7 +2297,7 @@ declare var CSSRule: { interface CSSRuleList { readonly length: number; - item(index: number): CSSRule; + item(index: number): CSSRule | null; [index: number]: CSSRule; } @@ -1995,8 +2309,8 @@ declare var CSSRuleList: { interface CSSStyleDeclaration { alignContent: string | null; alignItems: string | null; - alignmentBaseline: string | null; alignSelf: string | null; + alignmentBaseline: string | null; animation: string | null; animationDelay: string | null; animationDirection: string | null; @@ -2072,9 +2386,9 @@ interface CSSStyleDeclaration { columnRuleColor: any; columnRuleStyle: string | null; columnRuleWidth: any; - columns: string | null; columnSpan: string | null; columnWidth: any; + columns: string | null; content: string | null; counterIncrement: string | null; counterReset: string | null; @@ -2108,11 +2422,32 @@ interface CSSStyleDeclaration { fontStyle: string | null; fontVariant: string | null; fontWeight: string | null; + gap: string | null; glyphOrientationHorizontal: string | null; glyphOrientationVertical: string | null; + grid: string | null; + gridArea: string | null; + gridAutoColumns: string | null; + gridAutoFlow: string | null; + gridAutoRows: string | null; + gridColumn: string | null; + gridColumnEnd: string | null; + gridColumnGap: string | null; + gridColumnStart: string | null; + gridGap: string | null; + gridRow: string | null; + gridRowEnd: string | null; + gridRowGap: string | null; + gridRowStart: string | null; + gridTemplate: string | null; + gridTemplateAreas: string | null; + gridTemplateColumns: string | null; + gridTemplateRows: string | null; height: string | null; imeMode: string | null; justifyContent: string | null; + justifyItems: string | null; + justifySelf: string | null; kerning: string | null; layoutGrid: string | null; layoutGridChar: string | null; @@ -2139,29 +2474,30 @@ interface CSSStyleDeclaration { markerMid: string | null; markerStart: string | null; mask: string | null; + maskImage: 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; + msContentZooming: string | null; msFlowFrom: string | null; msFlowInto: string | null; msFontFeatureSettings: string | null; msGridColumn: any; msGridColumnAlign: string | null; - msGridColumns: string | null; msGridColumnSpan: any; + msGridColumns: string | null; msGridRow: any; msGridRowAlign: string | null; - msGridRows: string | null; msGridRowSpan: any; + msGridRows: string | null; msHighContrastAdjust: string | null; msHyphenateLimitChars: string | null; msHyphenateLimitLines: any; @@ -2190,6 +2526,8 @@ interface CSSStyleDeclaration { msWrapFlow: string; msWrapMargin: any; msWrapThrough: string; + objectFit: string | null; + objectPosition: string | null; opacity: string | null; order: string | null; orphans: string | null; @@ -2210,13 +2548,16 @@ interface CSSStyleDeclaration { pageBreakBefore: string | null; pageBreakInside: string | null; readonly parentRule: CSSRule; + penAction: string | null; perspective: string | null; perspectiveOrigin: string | null; pointerEvents: string | null; position: string | null; quotes: string | null; + resize: string | null; right: string | null; rotate: string | null; + rowGap: string | null; rubyAlign: string | null; rubyOverhang: string | null; rubyPosition: string | null; @@ -2235,6 +2576,7 @@ interface CSSStyleDeclaration { textAlign: string | null; textAlignLast: string | null; textAnchor: string | null; + textCombineUpright: string | null; textDecoration: string | null; textIndent: string | null; textJustify: string | null; @@ -2256,6 +2598,7 @@ interface CSSStyleDeclaration { transitionTimingFunction: string | null; translate: string | null; unicodeBidi: string | null; + userSelect: string | null; verticalAlign: string | null; visibility: string | null; webkitAlignContent: string | null; @@ -2297,9 +2640,9 @@ interface CSSStyleDeclaration { webkitColumnRuleColor: any; webkitColumnRuleStyle: string | null; webkitColumnRuleWidth: any; - webkitColumns: string | null; webkitColumnSpan: string | null; webkitColumnWidth: any; + webkitColumns: string | null; webkitFilter: string | null; webkitFlex: string | null; webkitFlexBasis: string | null; @@ -2338,13 +2681,11 @@ interface CSSStyleDeclaration { 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; + setProperty(propertyName: string, value: string | null, priority?: string | null): void; [index: number]: string; } @@ -2354,7 +2695,6 @@ declare var CSSStyleDeclaration: { }; interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; selectorText: string; readonly style: CSSStyleDeclaration; } @@ -2366,21 +2706,32 @@ declare var CSSStyleRule: { interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; + /** @deprecated */ cssText: string; + /** @deprecated */ readonly id: string; + /** @deprecated */ readonly imports: StyleSheetList; + /** @deprecated */ readonly isAlternate: boolean; + /** @deprecated */ readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; + readonly ownerRule: CSSRule | null; + /** @deprecated */ readonly owningElement: Element; - readonly pages: StyleSheetPageList; + /** @deprecated */ + readonly pages: any; + /** @deprecated */ readonly readOnly: boolean; readonly rules: CSSRuleList; + /** @deprecated */ addImport(bstrURL: string, lIndex?: number): number; + /** @deprecated */ 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; + /** @deprecated */ removeImport(lIndex: number): void; removeRule(lIndex: number): void; } @@ -2398,6 +2749,380 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; +interface Cache { + add(request: Request | string): Promise; + addAll(requests: (Request | string)[]): Promise; + delete(request: Request | string, options?: CacheQueryOptions): Promise; + keys(request?: Request | string, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + matchAll(request?: Request | string, options?: CacheQueryOptions): Promise; + put(request: Request | string, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface Canvas2DContextAttributes { + alpha?: boolean; + storage?: boolean; + willReadFrequently?: boolean; + [attribute: string]: boolean | string | undefined; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +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; + arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: 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 CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends 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; + mozImageSmoothingEnabled: boolean; + msFillRule: CanvasFillRule; + oImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + webkitImageSmoothingEnabled: 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; + drawFocusIfNeeded(path: Path2D, 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; + isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(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 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 ChildNode { + remove(): void; +} + +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 ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + /** @deprecated */ + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(data?: string): 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 ComputedTimingProperties { + activeDuration: number; + currentIteration: number | null; + endTime: number; + localTime: number | null; + progress: number | null; +} + +interface ConcatParams extends Algorithm { + algorithmId: Uint8Array; + hash?: string | Algorithm; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + privateInfo?: Uint8Array; + publicInfo?: Uint8Array; +} + +interface Console { + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; + clear(): void; + count(label?: 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; + markTimeline(label?: string): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ContentScriptGlobalScope extends EventTarget { + readonly msContentScript: ExtensionScriptApis; + readonly window: Window; +} + +declare var ContentScriptGlobalScope: { + prototype: ContentScriptGlobalScope; + new(): ContentScriptGlobalScope; +}; + +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 CountQueuingStrategy { + highWaterMark: number; + size(): number; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(strategy: QueuingStrategy): CountQueuingStrategy; +}; + +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null; +} + +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 CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + whenDefined(name: string): PromiseLike; +} + interface CustomEvent extends Event { readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; @@ -2408,6 +3133,194 @@ declare var CustomEvent: { new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; +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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_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 DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +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 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 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(...tokens: string[]): void; + contains(token: string): boolean; + item(index: number): string | null; + remove(...tokens: string[]): void; + replace(oldToken: string, newToken: string): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + interface DataCue extends TextTrackCue { data: ArrayBuffer; addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -2454,10 +3367,11 @@ declare var DataTransferItem: { interface DataTransferItemList { readonly length: number; add(data: File): DataTransferItem | null; + add(data: string, type: string): DataTransferItem | null; clear(): void; item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: DataTransferItem; + [name: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -2544,11 +3458,30 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; }; +interface DhImportKeyParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + generator: Uint8Array; + prime: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhKeyGenParams extends Algorithm { + generator: Uint8Array; + prime: Uint8Array; +} + interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforedeactivate": UIEvent; + "activate": Event; + "beforeactivate": Event; + "beforedeactivate": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -2556,7 +3489,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "click": MouseEvent; "contextmenu": PointerEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -2566,7 +3499,7 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "fullscreenchange": Event; @@ -2586,25 +3519,25 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "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; + "MSContentZoom": Event; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSManipulationStateChanged": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "mssitemodejumplistitemremoved": Event; + "msthumbnailclick": Event; "pause": Event; "play": Event; "playing": Event; @@ -2635,7 +3568,15 @@ interface DocumentEventMap extends GlobalEventHandlersEventMap { "webkitfullscreenerror": Event; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { +interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent { + /** + * 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; /** * Gets the object that has the focus when the parent document has focus. */ @@ -2651,11 +3592,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * 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; + readonly anchors: HTMLCollectionOf; /** * Retrieves a collection of all applet objects in the document. */ - applets: HTMLCollectionOf; + readonly applets: HTMLCollectionOf; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ @@ -2691,7 +3632,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Gets a reference to the root node of the document. */ - documentElement: HTMLElement; + readonly documentElement: HTMLElement; /** * Sets or gets the security domain of the document. */ @@ -2699,7 +3640,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all embed objects in the document. */ - embeds: HTMLCollectionOf; + readonly embeds: HTMLCollectionOf; /** * Sets or gets the foreground (text) color of the document. */ @@ -2707,7 +3648,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of all form objects in the document. */ - forms: HTMLCollectionOf; + readonly forms: HTMLCollectionOf; readonly fullscreenElement: Element | null; readonly fullscreenEnabled: boolean; readonly head: HTMLHeadElement; @@ -2715,7 +3656,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection, in source order, of img objects in the document. */ - images: HTMLCollectionOf; + readonly images: HTMLCollectionOf; /** * Gets the implementation object of the current document. */ @@ -2735,322 +3676,323 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. */ - links: HTMLCollectionOf; + readonly links: HTMLCollectionOf; /** * Contains information about the current URL. */ - readonly location: Location; - msCapsLockWarningOff: boolean; + location: Location; msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; /** * Fires when the user aborts the download. * @param ev The event. */ - onabort: (this: Document, ev: UIEvent) => any; + onabort: ((this: Document, ev: UIEvent) => any) | null; /** * Fires when the object is set as the active element. * @param ev The event. */ - onactivate: (this: Document, ev: UIEvent) => any; + onactivate: ((this: Document, ev: Event) => any) | null; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ - onbeforeactivate: (this: Document, ev: UIEvent) => any; + onbeforeactivate: ((this: Document, ev: Event) => any) | null; /** * 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; + onbeforedeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires when the object loses the input focus. * @param ev The focus event. */ - onblur: (this: Document, ev: FocusEvent) => any; + onblur: ((this: Document, ev: FocusEvent) => any) | null; /** * 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; + oncanplay: ((this: Document, ev: Event) => any) | null; + oncanplaythrough: ((this: Document, ev: Event) => any) | null; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ - onchange: (this: Document, ev: Event) => any; + onchange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ - onclick: (this: Document, ev: MouseEvent) => any; + onclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ - ondblclick: (this: Document, ev: MouseEvent) => any; + ondblclick: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + ondeactivate: ((this: Document, ev: Event) => any) | null; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ - ondrag: (this: Document, ev: DragEvent) => any; + ondrag: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragend: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragenter: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragleave: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragover: ((this: Document, ev: DragEvent) => any) | null; /** * 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; + ondragstart: ((this: Document, ev: DragEvent) => any) | null; + ondrop: ((this: Document, ev: DragEvent) => any) | null; /** * Occurs when the duration attribute is updated. * @param ev The event. */ - ondurationchange: (this: Document, ev: Event) => any; + ondurationchange: ((this: Document, ev: Event) => any) | null; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ - onemptied: (this: Document, ev: Event) => any; + onemptied: ((this: Document, ev: Event) => any) | null; /** * Occurs when the end of playback is reached. * @param ev The event */ - onended: (this: Document, ev: MediaStreamErrorEvent) => any; + onended: ((this: Document, ev: Event) => any) | null; /** * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (this: Document, ev: ErrorEvent) => any; + onerror: ((this: Document, ev: ErrorEvent) => any) | null; /** * 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; + onfocus: ((this: Document, ev: FocusEvent) => any) | null; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + oninput: ((this: Document, ev: Event) => any) | null; + oninvalid: ((this: Document, ev: Event) => any) | null; /** * Fires when the user presses a key. * @param ev The keyboard event */ - onkeydown: (this: Document, ev: KeyboardEvent) => any; + onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ - onkeypress: (this: Document, ev: KeyboardEvent) => any; + onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires when the user releases a key. * @param ev The keyboard event */ - onkeyup: (this: Document, ev: KeyboardEvent) => any; + onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null; /** * Fires immediately after the browser loads the object. * @param ev The event. */ - onload: (this: Document, ev: Event) => any; + onload: ((this: Document, ev: Event) => any) | null; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ - onloadeddata: (this: Document, ev: Event) => any; + onloadeddata: ((this: Document, ev: Event) => any) | null; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ - onloadedmetadata: (this: Document, ev: Event) => any; + onloadedmetadata: ((this: Document, ev: Event) => any) | null; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ - onloadstart: (this: Document, ev: Event) => any; + onloadstart: ((this: Document, ev: Event) => any) | null; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ - onmousedown: (this: Document, ev: MouseEvent) => any; + onmousedown: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ - onmousemove: (this: Document, ev: MouseEvent) => any; + onmousemove: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseout: ((this: Document, ev: MouseEvent) => any) | null; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ - onmouseover: (this: Document, ev: MouseEvent) => any; + onmouseover: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmouseup: ((this: Document, ev: MouseEvent) => any) | null; /** * 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; + onmousewheel: ((this: Document, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: Document, ev: Event) => any) | null; + onmsgesturechange: ((this: Document, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null; + onmsgestureend: ((this: Document, ev: Event) => any) | null; + onmsgesturehold: ((this: Document, ev: Event) => any) | null; + onmsgesturestart: ((this: Document, ev: Event) => any) | null; + onmsgesturetap: ((this: Document, ev: Event) => any) | null; + onmsinertiastart: ((this: Document, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null; + onmspointercancel: ((this: Document, ev: Event) => any) | null; + onmspointerdown: ((this: Document, ev: Event) => any) | null; + onmspointerenter: ((this: Document, ev: Event) => any) | null; + onmspointerleave: ((this: Document, ev: Event) => any) | null; + onmspointermove: ((this: Document, ev: Event) => any) | null; + onmspointerout: ((this: Document, ev: Event) => any) | null; + onmspointerover: ((this: Document, ev: Event) => any) | null; + onmspointerup: ((this: Document, ev: Event) => any) | null; /** * 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; + onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null; /** * 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; + onmsthumbnailclick: ((this: Document, ev: Event) => any) | null; /** * Occurs when playback is paused. * @param ev The event. */ - onpause: (this: Document, ev: Event) => any; + onpause: ((this: Document, ev: Event) => any) | null; /** * Occurs when the play method is requested. * @param ev The event. */ - onplay: (this: Document, ev: Event) => any; + onplay: ((this: Document, ev: Event) => any) | null; /** * 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; + onplaying: ((this: Document, ev: Event) => any) | null; + onpointerlockchange: ((this: Document, ev: Event) => any) | null; + onpointerlockerror: ((this: Document, ev: Event) => any) | null; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ - onprogress: (this: Document, ev: ProgressEvent) => any; + onprogress: ((this: Document, ev: ProgressEvent) => any) | null; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ - onratechange: (this: Document, ev: Event) => any; + onratechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the state of the object has changed. * @param ev The event */ - onreadystatechange: (this: Document, ev: Event) => any; + onreadystatechange: ((this: Document, ev: Event) => any) | null; /** * Fires when the user resets a form. * @param ev The event. */ - onreset: (this: Document, ev: Event) => any; + onreset: ((this: Document, ev: Event) => any) | null; /** * 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; + onscroll: ((this: Document, ev: UIEvent) => any) | null; /** * Occurs when the seek operation ends. * @param ev The event. */ - onseeked: (this: Document, ev: Event) => any; + onseeked: ((this: Document, ev: Event) => any) | null; /** * Occurs when the current playback position is moved. * @param ev The event. */ - onseeking: (this: Document, ev: Event) => any; + onseeking: ((this: Document, ev: Event) => any) | null; /** * Fires when the current selection changes. * @param ev The event. */ - onselect: (this: Document, ev: UIEvent) => any; + onselect: ((this: Document, ev: UIEvent) => any) | null; /** * 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; + onselectionchange: ((this: Document, ev: Event) => any) | null; + onselectstart: ((this: Document, ev: Event) => any) | null; /** * Occurs when the download has stopped. * @param ev The event. */ - onstalled: (this: Document, ev: Event) => any; + onstalled: ((this: Document, ev: Event) => any) | null; /** * 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; + onstop: ((this: Document, ev: Event) => any) | null; + onsubmit: ((this: Document, ev: Event) => any) | null; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ - onsuspend: (this: Document, ev: Event) => any; + onsuspend: ((this: Document, ev: Event) => any) | null; /** * 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; + ontimeupdate: ((this: Document, ev: Event) => any) | null; + ontouchcancel: ((this: Document, ev: TouchEvent) => any) | null; + ontouchend: ((this: Document, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Document, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Document, ev: TouchEvent) => any) | null; + onvisibilitychange: (this: Document, ev: Event) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ - onvolumechange: (this: Document, ev: Event) => any; + onvolumechange: ((this: Document, ev: Event) => any) | null; /** * 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; + onwaiting: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null; + readonly plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** * Retrieves a value that indicates the current state of the object. @@ -3067,7 +4009,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Retrieves a collection of all script objects in the document. */ - scripts: HTMLCollectionOf; + readonly 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. @@ -3077,14 +4019,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * 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. @@ -3100,7 +4034,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string | null; - onvisibilitychange: (this: Document, ev: Event) => any; adoptNode(source: T): T; captureEvents(): void; caretRangeFromPoint(x: number, y: number): Range; @@ -3196,6 +4129,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; createElementNS(namespaceURI: string | null, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver: Node): XPathNSResolver; /** * 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. @@ -3204,7 +4138,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @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. @@ -3231,6 +4164,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; + elementsFromPoint(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. @@ -3249,6 +4183,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven /** * Causes the element to receive the focus and executes the code specified by the onfocus event. */ + /** @deprecated */ focus(): void; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. @@ -3321,10 +4256,6 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ queryCommandValue(commandId: string): string; releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** @@ -3348,7 +4279,79 @@ declare var Document: { new(): Document; }; -interface DocumentFragment extends Node, NodeSelector, ParentNode { +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + 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: "MSDCCEvent"): MSDCCEvent; + createEvent(eventInterface: "MSDSHEvent"): MSDSHEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + 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: "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: "PromiseRejectionEvent"): PromiseRejectionEvent; + 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: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + 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: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DocumentFragment extends Node, ParentNode { getElementById(elementId: string): HTMLElement | null; } @@ -3357,6 +4360,14 @@ declare var DocumentFragment: { new(): DocumentFragment; }; +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly styleSheets: StyleSheetList; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + getSelection(): Selection | null; +} + interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; readonly internalSubset: string | null; @@ -3371,149 +4382,6 @@ declare var 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; @@ -3539,209 +4407,23 @@ declare var 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 EXT_blend_minmax { + readonly MAX_EXT: number; + readonly MIN_EXT: number; } -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 | null; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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_sRGB { + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB_EXT: number; +} + +interface EXT_shader_texture_lod { +} interface EXT_texture_filter_anisotropic { readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; @@ -3755,14 +4437,262 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; }; +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": Event; + "command": Event; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSGotPointerCapture": Event; + "MSInertiaStart": Event; + "MSLostPointerCapture": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode { + readonly assignedSlot: HTMLSlotElement | null; + readonly attributes: NamedNodeMap; + 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) | null; + oncommand: ((this: Element, ev: Event) => any) | null; + ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null; + onmsgesturechange: ((this: Element, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null; + onmsgestureend: ((this: Element, ev: Event) => any) | null; + onmsgesturehold: ((this: Element, ev: Event) => any) | null; + onmsgesturestart: ((this: Element, ev: Event) => any) | null; + onmsgesturetap: ((this: Element, ev: Event) => any) | null; + onmsgotpointercapture: ((this: Element, ev: Event) => any) | null; + onmsinertiastart: ((this: Element, ev: Event) => any) | null; + onmslostpointercapture: ((this: Element, ev: Event) => any) | null; + onmspointercancel: ((this: Element, ev: Event) => any) | null; + onmspointerdown: ((this: Element, ev: Event) => any) | null; + onmspointerenter: ((this: Element, ev: Event) => any) | null; + onmspointerleave: ((this: Element, ev: Event) => any) | null; + onmspointermove: ((this: Element, ev: Event) => any) | null; + onmspointerout: ((this: Element, ev: Event) => any) | null; + onmspointerover: ((this: Element, ev: Event) => any) | null; + onmspointerup: ((this: Element, ev: Event) => any) | null; + ontouchcancel: ((this: Element, ev: TouchEvent) => any) | null; + ontouchend: ((this: Element, ev: TouchEvent) => any) | null; + ontouchmove: ((this: Element, ev: TouchEvent) => any) | null; + ontouchstart: ((this: Element, ev: TouchEvent) => any) | null; + onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; + onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; + outerHTML: string; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly shadowRoot: ShadowRoot | null; + slot: string; + readonly tagName: string; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + getAttribute(qualifiedName: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + getElementsByClassName(classNames: string): NodeListOf; + 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; + hasAttributes(): boolean; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + matches(selectors: string): boolean; + msGetRegionContent(): any; + 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; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + setAttribute(qualifiedName: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): 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: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + readonly style: CSSStyleDeclaration; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ElementDefinitionOptions { + extends: string; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly nextElementSibling: Element | null; + readonly previousElementSibling: Element | null; +} + +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(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly scoped: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget | null; + readonly timeStamp: number; + readonly type: string; + deepPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +} + +declare var Event: { + prototype: Event; + new(typeArg: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; + readonly NONE: number; +}; + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventSource extends EventTarget { + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + onerror: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onopen: (evt: MessageEvent) => any; + readonly readyState: number; + readonly url: string; + readonly withCredentials: boolean; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + interface ExtensionScriptApis { extensionIdToShortId(extensionId: string): number; - fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void; genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; genericSynchronousFunction(functionId: number, parameters?: string): string; + genericWebRuntimeCallout(to: any, from: any, payload: string): void; getExtensionId(): string; - registerGenericFunctionCallbackHandler(callbackHandler: any): void; - registerGenericPersistentCallbackHandler(callbackHandler: any): void; + registerGenericFunctionCallbackHandler(callbackHandler: Function): void; + registerGenericPersistentCallbackHandler(callbackHandler: Function): void; + registerWebRuntimeCallbackHandler(handler: Function): any; } declare var ExtensionScriptApis: { @@ -3779,10 +4709,11 @@ declare var External: { }; interface File extends Blob { + readonly lastModified: number; + /** @deprecated */ readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; - readonly lastModified: number; } declare var File: { @@ -3792,7 +4723,7 @@ declare var File: { interface FileList { readonly length: number; - item(index: number): File; + item(index: number): File | null; [index: number]: File; } @@ -3801,21 +4732,49 @@ declare var FileList: { new(): FileList; }; -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; 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; + readAsText(blob: Blob, label?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[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: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface FocusEvent extends UIEvent { @@ -3853,7 +4812,8 @@ interface FormData { declare var FormData: { prototype: FormData; - new (form?: HTMLFormElement): FormData; + new(): FormData; + new(form: HTMLFormElement): FormData; }; interface GainNode extends AudioNode { @@ -3869,9 +4829,13 @@ interface Gamepad { readonly axes: number[]; readonly buttons: GamepadButton[]; readonly connected: boolean; + readonly displayId: number; + readonly hand: GamepadHand; + readonly hapticActuators: GamepadHapticActuator[]; readonly id: string; readonly index: number; - readonly mapping: string; + readonly mapping: GamepadMappingType; + readonly pose: GamepadPose | null; readonly timestamp: number; } @@ -3882,6 +4846,7 @@ declare var Gamepad: { interface GamepadButton { readonly pressed: boolean; + readonly touched: boolean; readonly value: number; } @@ -3899,6 +4864,32 @@ declare var GamepadEvent: { new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; }; +interface GamepadHapticActuator { + readonly type: GamepadHapticActuatorType; + pulse(value: number, duration: number): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GamepadPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; +} + +declare var GamepadPose: { + prototype: GamepadPose; + new(): GamepadPose; +}; + interface Geolocation { clearWatch(watchId: number): void; getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; @@ -3910,45 +4901,41 @@ declare var Geolocation: { new(): Geolocation; }; -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; +interface GetSVGDocument { + getSVGDocument(): Document; } -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; +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; } -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; +interface GlobalEventHandlers { + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + 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; } -declare var History: { - prototype: History; - new(): History; -}; +interface GlobalFetch { + fetch(input?: Request | string, init?: RequestInit): Promise; +} interface HTMLAllCollection { readonly length: number; @@ -3962,55 +4949,30 @@ declare var HTMLAllCollection: { new(): HTMLAllCollection; }; -interface HTMLAnchorElement extends HTMLElement { +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + Methods: string; /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Sets or retrieves the coordinates of the object. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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. @@ -4019,14 +4981,12 @@ interface HTMLAnchorElement extends HTMLElement { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ 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. */ + /** @deprecated */ shape: string; /** * Sets or retrieves the window or frame at which to target content. @@ -4038,10 +4998,6 @@ interface HTMLAnchorElement extends HTMLElement { 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; @@ -4054,70 +5010,44 @@ declare var HTMLAnchorElement: { }; interface HTMLAppletElement extends HTMLElement { + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ 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. */ + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; /** * Sets or retrieves the shape of the object. */ + /** @deprecated */ 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; + /** @deprecated */ + object: string; + /** @deprecated */ vspace: number; - width: number; + /** @deprecated */ + width: string; 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; @@ -4129,7 +5059,7 @@ declare var HTMLAppletElement: { new(): HTMLAppletElement; }; -interface HTMLAreaElement extends HTMLElement { +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { /** * Sets or retrieves a text alternative to the graphic. */ @@ -4139,43 +5069,12 @@ interface HTMLAreaElement extends HTMLElement { */ 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. */ + /** @deprecated */ 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. */ @@ -4184,10 +5083,6 @@ interface HTMLAreaElement extends HTMLElement { * 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; @@ -4219,6 +5114,23 @@ declare var HTMLAudioElement: { new(): HTMLAudioElement; }; +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. + */ + /** @deprecated */ + 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 HTMLBaseElement extends HTMLElement { /** * Gets or sets the baseline URL on which relative links are based. @@ -4243,10 +5155,12 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ face: string; /** * Sets or retrieves the font size of the object. */ + /** @deprecated */ 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; @@ -4259,51 +5173,34 @@ declare var HTMLBaseFontElement: { new(): HTMLBaseFontElement; }; -interface HTMLBodyElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { + /** @deprecated */ + aLink: string; + /** @deprecated */ background: string; - bgColor: any; + /** @deprecated */ + bgColor: string; bgProperties: string; - link: any; + /** @deprecated */ + link: string; + /** @deprecated */ 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; + onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; + onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null; + /** @deprecated */ + text: string; + /** @deprecated */ + vLink: string; 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; @@ -4315,22 +5212,6 @@ declare var 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. @@ -4356,7 +5237,7 @@ interface HTMLButtonElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -4426,12 +5307,12 @@ interface HTMLCanvasElement extends HTMLElement { * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ msToBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; /** * 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; @@ -4467,6 +5348,26 @@ declare var HTMLCollection: { new(): HTMLCollection; }; +interface HTMLCollectionOf extends HTMLCollectionBase { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface HTMLDListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLDataElement extends HTMLElement { value: string; addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4481,7 +5382,7 @@ declare var HTMLDataElement: { }; interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; + readonly 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; @@ -4493,6 +5394,36 @@ declare var HTMLDataListElement: { new(): HTMLDataListElement; }; +interface HTMLDetailsElement extends HTMLElement { + open: boolean; + addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; + addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + interface HTMLDirectoryElement extends HTMLElement { compact: boolean; addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -4510,6 +5441,7 @@ interface HTMLDivElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. @@ -4526,19 +5458,6 @@ declare var 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; @@ -4553,12 +5472,12 @@ declare var HTMLDocument: { interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; - "activate": UIEvent; - "beforeactivate": UIEvent; - "beforecopy": ClipboardEvent; - "beforecut": ClipboardEvent; - "beforedeactivate": UIEvent; - "beforepaste": ClipboardEvent; + "activate": Event; + "beforeactivate": Event; + "beforecopy": Event; + "beforecut": Event; + "beforedeactivate": Event; + "beforepaste": Event; "blur": FocusEvent; "canplay": Event; "canplaythrough": Event; @@ -4569,7 +5488,7 @@ interface HTMLElementEventMap extends ElementEventMap { "cuechange": Event; "cut": ClipboardEvent; "dblclick": MouseEvent; - "deactivate": UIEvent; + "deactivate": Event; "drag": DragEvent; "dragend": DragEvent; "dragenter": DragEvent; @@ -4579,7 +5498,7 @@ interface HTMLElementEventMap extends ElementEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "input": Event; @@ -4599,8 +5518,8 @@ interface HTMLElementEventMap extends ElementEventMap { "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": WheelEvent; - "MSContentZoom": UIEvent; - "MSManipulationStateChanged": MSManipulationEvent; + "MSContentZoom": Event; + "MSManipulationStateChanged": Event; "paste": ClipboardEvent; "pause": Event; "play": Event; @@ -4621,9 +5540,8 @@ interface HTMLElementEventMap extends ElementEventMap { "waiting": Event; } -interface HTMLElement extends Element { +interface HTMLElement extends Element, ElementCSSInlineStyle { accessKey: string; - readonly children: HTMLCollection; contentEditable: string; readonly dataset: DOMStringMap; dir: string; @@ -4638,84 +5556,83 @@ interface HTMLElement extends Element { 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; + onabort: ((this: HTMLElement, ev: UIEvent) => any) | null; + onactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null; + onbeforecut: ((this: HTMLElement, ev: Event) => any) | null; + onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null; + onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null; + onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oncanplay: ((this: HTMLElement, ev: Event) => any) | null; + oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null; + onchange: ((this: HTMLElement, ev: Event) => any) | null; + onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null; + oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + oncuechange: ((this: HTMLElement, ev: Event) => any) | null; + oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; + ondeactivate: ((this: HTMLElement, ev: Event) => any) | null; + ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null; + ondurationchange: ((this: HTMLElement, ev: Event) => any) | null; + onemptied: ((this: HTMLElement, ev: Event) => any) | null; + onended: ((this: HTMLElement, ev: Event) => any) | null; + onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null; + onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null; + oninput: ((this: HTMLElement, ev: Event) => any) | null; + oninvalid: ((this: HTMLElement, ev: Event) => any) | null; + onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; + onload: ((this: HTMLElement, ev: Event) => any) | null; + onloadeddata: ((this: HTMLElement, ev: Event) => any) | null; + onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null; + onloadstart: ((this: HTMLElement, ev: Event) => any) | null; + onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null; + onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null; + onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null; + onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null; + onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; + onpause: ((this: HTMLElement, ev: Event) => any) | null; + onplay: ((this: HTMLElement, ev: Event) => any) | null; + onplaying: ((this: HTMLElement, ev: Event) => any) | null; + onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null; + onratechange: ((this: HTMLElement, ev: Event) => any) | null; + onreset: ((this: HTMLElement, ev: Event) => any) | null; + onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null; + onseeked: ((this: HTMLElement, ev: Event) => any) | null; + onseeking: ((this: HTMLElement, ev: Event) => any) | null; + onselect: ((this: HTMLElement, ev: UIEvent) => any) | null; + onselectstart: ((this: HTMLElement, ev: Event) => any) | null; + onstalled: ((this: HTMLElement, ev: Event) => any) | null; + onsubmit: ((this: HTMLElement, ev: Event) => any) | null; + onsuspend: ((this: HTMLElement, ev: Event) => any) | null; + ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null; + onvolumechange: ((this: HTMLElement, ev: Event) => any) | null; + onwaiting: ((this: HTMLElement, ev: Event) => any) | null; outerText: string; spellcheck: boolean; - readonly style: CSSStyleDeclaration; tabIndex: number; title: string; + animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; blur(): void; click(): void; dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation; 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; @@ -4752,6 +5669,7 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * Retrieves the palette used for the embedded document. @@ -4832,6 +5750,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM /** * Sets or retrieves the current typeface family. */ + /** @deprecated */ 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; @@ -4912,6 +5831,7 @@ interface HTMLFormElement extends HTMLElement { * Retrieves a form object or an object from an elements collection. */ namedItem(name: string): any; + reportValidity(): boolean; /** * Fires when the user resets a form. */ @@ -4920,8 +5840,6 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ 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; @@ -4950,14 +5868,17 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + /** @deprecated */ + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + /** @deprecated */ + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. @@ -4970,30 +5891,37 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a URI to a long description of the object. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ marginWidth: string; /** * Sets or retrieves the frame name. */ + /** @deprecated */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ + /** @deprecated */ noResize: boolean; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ + /** @deprecated */ src: string; /** * Sets or retrieves the width of the object. @@ -5010,64 +5938,29 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; }; -interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { - "afterprint": Event; - "beforeprint": Event; - "beforeunload": BeforeUnloadEvent; +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "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; +interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { /** * Sets or retrieves the frame widths of the object. */ + /** @deprecated */ 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; + onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null; + onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null; /** * Sets or retrieves the frame heights of the object. */ + /** @deprecated */ 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; @@ -5080,7 +5973,35 @@ declare var HTMLFrameSetElement: { new(): HTMLFrameSetElement; }; +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + /** @deprecated */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + /** @deprecated */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + /** @deprecated */ + width: string; + 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 HTMLHeadElement extends HTMLElement { + /** @deprecated */ 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; @@ -5097,6 +6018,7 @@ interface HTMLHeadingElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ 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; @@ -5109,34 +6031,11 @@ declare var 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. */ + /** @deprecated */ 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; @@ -5149,6 +6048,19 @@ declare var HTMLHtmlElement: { new(): HTMLHtmlElement; }; +interface HTMLHyperlinkElementUtils { + hash: string; + host: string; + hostname: string; + href: string; + origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + toString(): string; +} + interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; } @@ -5157,78 +6069,64 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ 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; + readonly contentDocument: Document | null; /** * Retrieves the object of the specified. */ - readonly contentWindow: Window; + readonly contentWindow: Window | null; /** * Sets or retrieves whether to display a border for the frame. */ + /** @deprecated */ 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. */ + /** @deprecated */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ + /** @deprecated */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ + /** @deprecated */ 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; + readonly sandbox: DOMTokenList; /** * Sets or retrieves whether the frame can be scrolled. */ + /** @deprecated */ scrolling: string; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** - * Sets or retrieves the vertical margin for the object. + * Sets or retrives the content of the page that is to contain. */ - vspace: number; + srcdoc: string; /** * 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; @@ -5244,6 +6142,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5252,6 +6151,7 @@ interface HTMLImageElement extends HTMLElement { /** * Specifies the properties of a border drawn around an object. */ + /** @deprecated */ border: string; /** * Retrieves whether the object is fully loaded. @@ -5259,6 +6159,7 @@ interface HTMLImageElement extends HTMLElement { readonly complete: boolean; crossOrigin: string | null; readonly currentSrc: string; + decoding: "async" | "sync" | "auto"; /** * Sets or retrieves the height of the object. */ @@ -5266,6 +6167,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ hspace: number; /** * Sets or retrieves whether the image is a server-side image map. @@ -5275,6 +6177,7 @@ interface HTMLImageElement extends HTMLElement { * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. */ longDesc: string; + /** @deprecated */ lowsrc: string; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5292,6 +6195,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the name of the object. */ + /** @deprecated */ name: string; /** * The original height of the image resource before sizing. @@ -5314,6 +6218,7 @@ interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves the vertical margin for the object. */ + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -5341,6 +6246,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a text alternative to the graphic. @@ -5354,18 +6260,10 @@ interface HTMLInputElement 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 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. */ @@ -5398,7 +6296,7 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + formNoValidate: boolean; /** * Overrides the target attribute on a form element. */ @@ -5406,16 +6304,12 @@ interface HTMLInputElement extends HTMLElement { /** * 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; + height: number; indeterminate: boolean; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ - readonly list: HTMLElement; + readonly list: HTMLElement | null; /** * 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. */ @@ -5428,6 +6322,7 @@ interface HTMLInputElement extends HTMLElement { * 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; + minLength: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ @@ -5449,21 +6344,20 @@ interface HTMLInputElement extends HTMLElement { * When present, marks an element that can't be submitted without a value. */ required: boolean; - selectionDirection: string; + selectionDirection: string | null; /** * Gets or sets the end position or offset of a text selection. */ - selectionEnd: number; + selectionEnd: number | null; /** * Gets or sets the starting position or offset of a text selection. */ - selectionStart: number; + selectionStart: number | null; 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. */ @@ -5475,6 +6369,7 @@ interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ + /** @deprecated */ 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. @@ -5488,25 +6383,20 @@ interface HTMLInputElement extends HTMLElement { * Returns the value of the data at the cursor's current position. */ value: string; - valueAsDate: Date; + valueAsDate: any; /** * 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; + width: number; /** * 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. */ @@ -5548,48 +6438,8 @@ declare var 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 { + /** @deprecated */ type: string; /** * Sets or retrieves the value of a list item. @@ -5606,11 +6456,56 @@ declare var HTMLLIElement: { new(): HTMLLIElement; }; +interface HTMLLabelElement extends HTMLElement { + readonly control: HTMLInputElement | null; + /** + * 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; + 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. + */ + /** @deprecated */ + 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 HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; + crossOrigin: string | null; + /** @deprecated */ disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. @@ -5620,6 +6515,8 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { * Sets or retrieves the language code of the object. */ hreflang: string; + import?: Document; + integrity: string; /** * Sets or retrieves the media type. */ @@ -5631,17 +6528,17 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the relationship between the object and the destination of the link. */ + /** @deprecated */ rev: string; /** * Sets or retrieves the window or frame at which to target content. */ + /** @deprecated */ 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; @@ -5653,6 +6550,18 @@ declare var HTMLLinkElement: { new(): HTMLLinkElement; }; +interface HTMLMainElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. @@ -5680,21 +6589,37 @@ interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { } interface HTMLMarqueeElement extends HTMLElement { + /** @deprecated */ behavior: string; - bgColor: any; + /** @deprecated */ + bgColor: string; + /** @deprecated */ direction: string; + /** @deprecated */ height: string; + /** @deprecated */ hspace: number; + /** @deprecated */ loop: number; - onbounce: (this: HTMLMarqueeElement, ev: Event) => any; - onfinish: (this: HTMLMarqueeElement, ev: Event) => any; - onstart: (this: HTMLMarqueeElement, ev: Event) => any; + /** @deprecated */ + onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ + onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null; + /** @deprecated */ scrollAmount: number; + /** @deprecated */ scrollDelay: number; + /** @deprecated */ trueSpeed: boolean; + /** @deprecated */ vspace: number; + /** @deprecated */ width: string; + /** @deprecated */ start(): void; + /** @deprecated */ 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; @@ -5709,7 +6634,7 @@ declare var HTMLMarqueeElement: { interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; - "msneedkey": MSMediaKeyNeededEvent; + "msneedkey": Event; } interface HTMLMediaElement extends HTMLElement { @@ -5754,7 +6679,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Returns an object representing the current error state of the audio or video element. */ - readonly error: MediaError; + readonly error: MediaError | null; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ @@ -5772,6 +6697,7 @@ interface HTMLMediaElement extends HTMLElement { /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ + /** @deprecated */ readonly msKeys: MSMediaKeys; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -5801,8 +6727,9 @@ interface HTMLMediaElement extends HTMLElement { * Gets the current network activity for the element. */ readonly networkState: number; - onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null; + /** @deprecated */ + onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null; /** * Gets a flag that specifies whether playback is paused. */ @@ -5819,7 +6746,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: number; + readonly readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -5832,18 +6759,18 @@ interface HTMLMediaElement extends HTMLElement { * The address or URL of the a media resource that is to be considered. */ src: string; - srcObject: MediaStream | null; + srcObject: MediaStream | MediaSource | Blob | 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; + addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack; /** * Returns a string that specifies whether the client can play a given media resource type. */ - canPlayType(type: string): string; + canPlayType(type: string): CanPlayTypeResult; /** * Resets the audio or video object and loads a new media resource. */ @@ -5857,6 +6784,7 @@ interface HTMLMediaElement extends HTMLElement { * Inserts the specified audio effect into media pipeline. */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + /** @deprecated */ msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Specifies the media protection manager for a given media pipeline. @@ -5901,6 +6829,7 @@ declare var HTMLMediaElement: { }; interface HTMLMenuElement extends HTMLElement { + /** @deprecated */ compact: boolean; type: string; addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -5918,6 +6847,7 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves the character set used to encode the object. */ + /** @deprecated */ charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. @@ -5934,10 +6864,12 @@ interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ + /** @deprecated */ scheme: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ + /** @deprecated */ 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; @@ -5988,41 +6920,63 @@ declare var HTMLModElement: { new(): HTMLModElement; }; +interface HTMLOListElement extends HTMLElement { + /** @deprecated */ + 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 HTMLObjectElement extends HTMLElement, GetSVGDocument { - align: 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; + /** @deprecated */ + align: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + /** @deprecated */ + archive: string; + /** @deprecated */ border: string; /** * Sets or retrieves the URL of the file containing the compiled Java class. */ + /** @deprecated */ code: string; /** * Sets or retrieves the URL of the component. */ + /** @deprecated */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ + /** @deprecated */ codeType: string; /** * Retrieves the document object of the page or frame. */ - readonly contentDocument: Document; + readonly contentDocument: Document | null; /** * Sets or retrieves the URL that references the data of the object. */ data: string; + /** @deprecated */ declare: boolean; /** * Retrieves a reference to the form that the object is embedded in. @@ -6032,6 +6986,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the height of the object. */ height: string; + /** @deprecated */ hspace: number; /** * Gets or sets whether the DLNA PlayTo device is available. @@ -6057,11 +7012,13 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves a message to be displayed while an object is loading. */ + /** @deprecated */ standby: string; /** * Sets or retrieves the MIME type of the object. */ type: string; + typemustmatch: boolean; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ @@ -6074,6 +7031,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; + /** @deprecated */ vspace: number; /** * Sets or retrieves the width of the object. @@ -6083,7 +7041,6 @@ 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. */ @@ -6104,54 +7061,16 @@ declare var 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; @@ -6207,7 +7126,7 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; remove(index: number): void; } @@ -6219,7 +7138,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; readonly form: HTMLFormElement | null; - readonly htmlFor: DOMSettableTokenList; + readonly htmlFor: DOMTokenList; name: string; readonly type: string; readonly validationMessage: string; @@ -6244,6 +7163,7 @@ interface HTMLParagraphElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -6265,6 +7185,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the content type of the resource designated by the value attribute. */ + /** @deprecated */ type: string; /** * Sets or retrieves the value of an input parameter for an element. @@ -6273,6 +7194,7 @@ interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the data type of the value attribute. */ + /** @deprecated */ 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; @@ -6301,6 +7223,7 @@ interface HTMLPreElement extends HTMLElement { /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ + /** @deprecated */ 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; @@ -6371,11 +7294,15 @@ interface HTMLScriptElement extends HTMLElement { /** * Sets or retrieves the event for which the script is written. */ + /** @deprecated */ event: string; /** * Sets or retrieves the object that is bound to the event script. */ + /** @deprecated */ htmlFor: string; + integrity: string; + noModule: boolean; /** * Retrieves the URL to an external file that contains the source code or data. */ @@ -6388,7 +7315,6 @@ interface HTMLScriptElement extends HTMLElement { * 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; @@ -6431,7 +7357,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the index of the selected option in a select object. */ selectedIndex: number; - selectedOptions: HTMLCollectionOf; + readonly selectedOptions: HTMLCollectionOf; /** * Sets or retrieves the number of rows in the list box. */ @@ -6461,7 +7387,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6471,7 +7397,7 @@ interface HTMLSelectElement extends HTMLElement { * @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; + item(name?: any, index?: any): Element | null; /** * 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. @@ -6499,11 +7425,21 @@ declare var HTMLSelectElement: { new(): HTMLSelectElement; }; +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; + addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; + /** @deprecated */ msKeySystem: string; sizes: string; /** @@ -6539,6 +7475,7 @@ declare var HTMLSpanElement: { }; interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** @deprecated */ disabled: boolean; /** * Sets or retrieves the media type. @@ -6559,15 +7496,24 @@ declare var HTMLStyleElement: { new(): HTMLStyleElement; }; +interface HTMLSummaryElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. */ + /** @deprecated */ 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; @@ -6579,7 +7525,7 @@ declare var HTMLTableCaptionElement: { new(): HTMLTableCaptionElement; }; -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableCellElement extends HTMLElement { /** * Sets or retrieves abbreviated text for the object. */ @@ -6587,16 +7533,23 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; /** * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. */ + /** @deprecated */ axis: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves the position of the object in the cells collection of a row. */ readonly cellIndex: number; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number columns in the table that the object should span. */ @@ -6608,10 +7561,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves the height of the object. */ - height: any; + /** @deprecated */ + height: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ + /** @deprecated */ noWrap: boolean; /** * Sets or retrieves how many rows in a table the cell should span. @@ -6621,9 +7576,12 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ 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; @@ -6636,19 +7594,27 @@ declare var HTMLTableCellElement: { new(): HTMLTableCellElement; }; -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableColElement extends HTMLElement { /** * Sets or retrieves the alignment of the object relative to the display or table. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of columns in the group. */ span: number; + /** @deprecated */ + vAlign: string; /** * Sets or retrieves the width of the object. */ - width: any; + /** @deprecated */ + width: string; 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; @@ -6676,67 +7642,64 @@ interface HTMLTableElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Sets or retrieves the width of the border to draw around the object. */ + /** @deprecated */ border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; /** * Retrieves the caption object of a table. */ - caption: HTMLTableCaptionElement; + caption: HTMLTableCaptionElement | null; /** * Sets or retrieves the amount of space between the border of the cell and the content of the cell. */ + /** @deprecated */ cellPadding: string; /** * Sets or retrieves the amount of space between cells in a table. */ + /** @deprecated */ 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. */ + /** @deprecated */ 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; + readonly rows: HTMLCollectionOf; /** * Sets or retrieves which dividing lines (inner borders) are displayed. */ + /** @deprecated */ rules: string; /** * Sets or retrieves a description and/or structure of the object. */ + /** @deprecated */ summary: string; /** * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. */ - tBodies: HTMLCollectionOf; + readonly tBodies: HTMLCollectionOf; /** * Retrieves the tFoot object of the table. */ - tFoot: HTMLTableSectionElement; + tFoot: HTMLTableSectionElement | null; /** * Retrieves the tHead object of the table. */ - tHead: HTMLTableSectionElement; + tHead: HTMLTableSectionElement | null; /** * Sets or retrieves the width of the object. */ + /** @deprecated */ width: string; /** * Creates an empty caption element in the table. @@ -6788,9 +7751,6 @@ declare var 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; @@ -6803,20 +7763,22 @@ declare var HTMLTableHeaderCellElement: { new(): HTMLTableHeaderCellElement; }; -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableRowElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ + /** @deprecated */ align: string; - bgColor: any; + /** @deprecated */ + bgColor: string; /** * Retrieves a collection of all cells in the table row. */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; + readonly cells: HTMLCollectionOf; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Retrieves the position of the object in the rows collection for the table. */ @@ -6825,6 +7787,8 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Retrieves the position of the object in the collection. */ readonly sectionRowIndex: number; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6846,15 +7810,22 @@ declare var HTMLTableRowElement: { new(): HTMLTableRowElement; }; -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { +interface HTMLTableSectionElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ + /** @deprecated */ align: string; + /** @deprecated */ + ch: string; + /** @deprecated */ + chOff: string; /** * Sets or retrieves the number of horizontal rows contained in the object. */ - rows: HTMLCollectionOf; + readonly rows: HTMLCollectionOf; + /** @deprecated */ + vAlign: string; /** * 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. @@ -6911,6 +7882,7 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; + minLength: number; /** * Sets or retrieves the name of the object. */ @@ -6939,10 +7911,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -6967,7 +7935,6 @@ interface HTMLTextAreaElement extends HTMLElement { * 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. */ @@ -7056,7 +8023,9 @@ declare var HTMLTrackElement: { }; interface HTMLUListElement extends HTMLElement { + /** @deprecated */ compact: boolean; + /** @deprecated */ 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; @@ -7098,9 +8067,9 @@ interface HTMLVideoElement extends HTMLMediaElement { msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; - onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null; + onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null; /** * 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. */ @@ -7123,10 +8092,10 @@ interface HTMLVideoElement extends HTMLMediaElement { 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; + 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; @@ -7138,13 +8107,71 @@ declare var HTMLVideoElement: { new(): HTMLVideoElement; }; +interface HTMLegendElement { + readonly form: HTMLFormElement | null; +} + +declare var HTMLegendElement: { + prototype: HTMLegendElement; + new(): HTMLegendElement; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string; + readonly oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: Function, thisArg?: any): 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; + scrollRestoration: ScrollRestoration; + readonly state: any; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): 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 HkdfCtrParams extends Algorithm { + context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + hash: string | Algorithm; + label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface IDBArrayKey extends Array { +} + interface IDBCursor { readonly direction: IDBCursorDirection; - key: IDBKeyRange | IDBValidKey; + readonly key: IDBKeyRange | number | string | Date | IDBArrayKey; readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; + readonly source: IDBObjectStore | IDBIndex; advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; + continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void; delete(): IDBRequest; update(value: any): IDBRequest; readonly NEXT: string; @@ -7179,16 +8206,14 @@ interface IDBDatabaseEventMap { 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; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: Event) => any) | null; + readonly version: number; 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; @@ -7200,6 +8225,10 @@ declare var IDBDatabase: { new(): IDBDatabase; }; +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + interface IDBFactory { cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; @@ -7212,16 +8241,16 @@ declare var IDBFactory: { }; interface IDBIndex { - keyPath: string | string[]; + readonly keyPath: string | string[]; + multiEntry: boolean; 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; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -7246,21 +8275,21 @@ declare var IDBKeyRange: { }; interface IDBObjectStore { + autoIncrement: boolean; readonly indexNames: DOMStringList; - keyPath: string | string[]; + readonly keyPath: string | string[] | null; readonly name: string; readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): 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; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; } declare var IDBObjectStore: { @@ -7274,8 +8303,8 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { } interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: IDBOpenDBRequest, ev: Event) => any; - onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; 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; @@ -7294,11 +8323,11 @@ interface IDBRequestEventMap { interface IDBRequest extends EventTarget { readonly error: DOMException; - onerror: (this: IDBRequest, ev: Event) => any; - onsuccess: (this: IDBRequest, ev: Event) => any; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; readonly readyState: IDBRequestReadyState; readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; + readonly 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; @@ -7321,9 +8350,9 @@ 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; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -7362,8 +8391,23 @@ declare var IIRFilterNode: { new(): IIRFilterNode; }; +interface ImageBitmap { + readonly height: number; + readonly width: number; + close(): void; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + interface ImageData { - data: Uint8ClampedArray; + readonly data: Uint8ClampedArray; readonly height: number; readonly width: number; } @@ -7393,10 +8437,10 @@ interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; readonly intersectionRect: ClientRect | DOMRect; + readonly isIntersecting: boolean; readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; - readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -7406,19 +8450,23 @@ declare var IntersectionObserverEntry: { interface KeyboardEvent extends UIEvent { readonly altKey: boolean; - readonly char: string | null; + /** @deprecated */ + char: string; + /** @deprecated */ readonly charCode: number; + readonly code: string; readonly ctrlKey: boolean; readonly key: string; + /** @deprecated */ readonly keyCode: number; - readonly locale: string; readonly location: number; readonly metaKey: boolean; readonly repeat: boolean; readonly shiftKey: boolean; + /** @deprecated */ readonly which: number; - readonly code: string; getModifierState(keyArg: string): boolean; + /** @deprecated */ 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; @@ -7439,6 +8487,10 @@ declare var KeyboardEvent: { readonly DOM_KEY_LOCATION_STANDARD: number; }; +interface LinkStyle { + readonly sheet: StyleSheet | null; +} + interface ListeningStateChangedEvent extends Event { readonly label: string; readonly state: ListeningState; @@ -7470,14 +8522,327 @@ declare var Location: { new(): Location; }; -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; } -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; +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 MSDCCEvent extends Event { + readonly maxFr: number; + readonly maxFs: number; +} + +declare var MSDCCEvent: { + prototype: MSDCCEvent; + new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent; +}; + +interface MSDSHEvent extends Event { + readonly sources: number[]; + readonly timestamp: number; +} + +declare var MSDSHEvent: { + prototype: MSDSHEvent; + new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent; +}; + +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 MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +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 MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null; + oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null; + 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 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 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 MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string | null): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string; +}; + +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 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 MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MSStreamReaderEventMap { + "abort": UIEvent; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSStreamReader extends EventTarget { + readonly error: DOMError; + onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null; + onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null; + onload: ((this: MSStreamReader, ev: Event) => any) | null; + onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: MSStreamReader, ev: Event) => any) | null; + onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; + 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; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; }; interface MediaDeviceInfo { @@ -7497,7 +8862,7 @@ interface MediaDevicesEventMap { } interface MediaDevices extends EventTarget { - ondevicechange: (this: MediaDevices, ev: Event) => any; + ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; @@ -7560,26 +8925,16 @@ declare var MediaKeyMessageEvent: { new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; }; -interface MediaKeys { - createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: BufferSource): 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: BufferSource): Promise; + generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: BufferSource): Promise; + update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; } declare var MediaKeySession: { @@ -7589,9 +8944,9 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: BufferSource): MediaKeyStatus; - has(keyId: BufferSource): boolean; + forEach(callback: Function, thisArg?: any): void; + get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus; + has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean; } declare var MediaKeyStatusMap: { @@ -7610,13 +8965,23 @@ declare var MediaKeySystemAccess: { new(): MediaKeySystemAccess; }; +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + interface MediaList { readonly length: number; mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; + appendMedium(medium: string): void; + deleteMedium(medium: string): void; + item(index: number): string | null; + toString(): number; [index: number]: string; } @@ -7663,10 +9028,10 @@ interface MediaStreamEventMap { 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; + onactive: ((this: MediaStream, ev: Event) => any) | null; + onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; + oninactive: ((this: MediaStream, ev: Event) => any) | null; + onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null; addTrack(track: MediaStreamTrack): void; clone(): MediaStream; getAudioTracks(): MediaStreamTrack[]; @@ -7683,7 +9048,9 @@ interface MediaStream extends EventTarget { declare var MediaStream: { prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; + new(): MediaStream; + new(stream: MediaStream): MediaStream; + new(tracks: MediaStreamTrack[]): MediaStream; }; interface MediaStreamAudioSourceNode extends AudioNode { @@ -7736,10 +9103,10 @@ interface MediaStreamTrack extends EventTarget { 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; + onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; + onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null; + onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readonly: boolean; readonly readyState: MediaStreamTrackState; readonly remote: boolean; @@ -7782,9 +9149,9 @@ declare var 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; + readonly ports: ReadonlyArray; + readonly source: Window | null; + initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void; } declare var MessageEvent: { @@ -7797,7 +9164,7 @@ interface MessagePortEventMap { } interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; @@ -7843,6 +9210,7 @@ interface MouseEvent extends UIEvent { readonly clientX: number; readonly clientY: number; readonly ctrlKey: boolean; + /** @deprecated */ readonly fromElement: Element; readonly layerX: number; readonly layerY: number; @@ -7857,7 +9225,9 @@ interface MouseEvent extends UIEvent { readonly screenX: number; readonly screenY: number; readonly shiftKey: boolean; + /** @deprecated */ readonly toElement: Element; + /** @deprecated */ readonly which: number; readonly x: number; readonly y: number; @@ -7870,456 +9240,6 @@ declare var 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; @@ -8360,7 +9280,7 @@ interface MutationRecord { readonly previousSibling: Node | null; readonly removedNodes: NodeList; readonly target: Node; - readonly type: string; + readonly type: MutationRecordType; } declare var MutationRecord: { @@ -8370,13 +9290,13 @@ declare var 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; + getNamedItem(qualifiedName: string): Attr | null; + getNamedItemNS(namespace: string | null, localName: string): Attr | null; + item(index: number): Attr | null; + removeNamedItem(qualifiedName: string): Attr; + removeNamedItemNS(namespace: string | null, localName: string): Attr; + setNamedItem(attr: Attr): Attr | null; + setNamedItemNS(attr: Attr): Attr | null; [index: number]: Attr; } @@ -8385,39 +9305,13 @@ declare var 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 { +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage { + readonly activeVRDisplays: ReadonlyArray; readonly authentication: WebAuthentication; readonly cookieEnabled: boolean; + readonly doNotTrack: string | null; gamepadInputEmulation: GamepadInputEmulationType; - readonly language: string; + readonly geolocation: Geolocation; readonly maxTouchPoints: number; readonly mimeTypes: MimeTypeArray; readonly msManipulationViewsEnabled: boolean; @@ -8427,10 +9321,8 @@ 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[]; + getGamepads(): (Gamepad | null)[]; + getVRDisplays(): Promise; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; @@ -8442,10 +9334,50 @@ declare var Navigator: { new(): Navigator; }; +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +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 NavigatorLanguage { + readonly language: string; + readonly languages: ReadonlyArray; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getDisplayMedia(constraints: MediaStreamConstraints): Promise; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + interface Node extends EventTarget { - readonly attributes: NamedNodeMap; readonly baseURI: string | null; - readonly childNodes: NodeList; + readonly childNodes: NodeListOf; readonly firstChild: Node | null; readonly lastChild: Node | null; readonly localName: string | null; @@ -8463,7 +9395,6 @@ interface Node extends EventTarget { 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; @@ -8518,7 +9449,7 @@ declare var Node: { }; interface NodeFilter { - acceptNode(n: Node): number; + acceptNode(node: Node): number; } declare var NodeFilter: { @@ -8541,13 +9472,14 @@ declare var NodeFilter: { }; interface NodeIterator { + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; detach(): void; - nextNode(): Node; - previousNode(): Node; + nextNode(): Node | null; + previousNode(): Node | null; } declare var NodeIterator: { @@ -8566,6 +9498,21 @@ declare var NodeList: { new(): NodeList; }; +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +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 NotificationEventMap { "click": Event; "close": Event; @@ -8574,16 +9521,17 @@ interface NotificationEventMap { } interface Notification extends EventTarget { - readonly body: string; + readonly body: string | null; + readonly data: any; 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 icon: string | null; + readonly lang: string | null; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; readonly permission: NotificationPermission; - readonly tag: string; + readonly tag: string | null; readonly title: string; close(): void; addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8650,6 +9598,14 @@ declare var OES_texture_half_float_linear: { new(): OES_texture_half_float_linear; }; +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; +} + interface OfflineAudioCompletionEvent extends Event { readonly renderedBuffer: AudioBuffer; } @@ -8665,7 +9621,7 @@ interface OfflineAudioContextEventMap extends AudioContextEventMap { interface OfflineAudioContext extends AudioContextBase { readonly length: number; - oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; + oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null; startRendering(): Promise; suspend(suspendTime: number): Promise; addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8680,13 +9636,13 @@ declare var OfflineAudioContext: { }; interface OscillatorNodeEventMap { - "ended": MediaStreamErrorEvent; + "ended": Event; } interface OscillatorNode extends AudioNode { readonly detune: AudioParam; readonly frequency: AudioParam; - onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + onended: ((this: OscillatorNode, ev: Event) => any) | null; type: OscillatorType; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; @@ -8737,8 +9693,11 @@ interface PannerNode extends AudioNode { panningModel: PanningModelType; refDistance: number; rolloffFactor: number; + /** @deprecated */ setOrientation(x: number, y: number, z: number): void; + /** @deprecated */ setPosition(x: number, y: number, z: number): void; + /** @deprecated */ setVelocity(x: number, y: number, z: number): void; } @@ -8747,12 +9706,28 @@ declare var PannerNode: { new(): PannerNode; }; -interface Path2D extends Object, CanvasPathMethods { +interface ParentNode { + readonly children: HTMLCollection; + 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 ParentNode { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; +} + +interface Path2D extends CanvasPathMethods { } declare var Path2D: { prototype: Path2D; - new(path?: Path2D): Path2D; + new(d?: Path2D | string): Path2D; }; interface PaymentAddress { @@ -8781,12 +9756,14 @@ interface PaymentRequestEventMap { } interface PaymentRequest extends EventTarget { - onshippingaddresschange: (this: PaymentRequest, ev: Event) => any; - onshippingoptionchange: (this: PaymentRequest, ev: Event) => any; + readonly id: string; + onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; + onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; readonly shippingType: PaymentShippingType | null; abort(): Promise; + canMakePayment(): 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; @@ -8796,11 +9773,11 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; - new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; }; interface PaymentRequestUpdateEvent extends Event { - updateWith(d: Promise): void; + updateWith(detailsPromise: Promise): void; } declare var PaymentRequestUpdateEvent: { @@ -8814,6 +9791,7 @@ interface PaymentResponse { readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; + readonly requestId: string; readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; @@ -8825,16 +9803,50 @@ declare var PaymentResponse: { new(): PaymentResponse; }; +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 Performance { + /** @deprecated */ readonly navigation: PerformanceNavigation; + readonly timeOrigin: number; + /** @deprecated */ 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; + getEntriesByName(name: string, type?: string): any; + getEntriesByType(type: string): any; + /** @deprecated */ getMarks(markName?: string): any; + /** @deprecated */ getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; @@ -8853,6 +9865,7 @@ interface PerformanceEntry { readonly entryType: string; readonly name: string; readonly startTime: number; + toJSON(): any; } declare var PerformanceEntry: { @@ -8896,28 +9909,41 @@ declare var PerformanceNavigation: { }; interface PerformanceNavigationTiming extends PerformanceEntry { + /** @deprecated */ readonly connectEnd: number; + /** @deprecated */ readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; readonly domComplete: number; readonly domContentLoadedEventEnd: number; readonly domContentLoadedEventStart: number; readonly domInteractive: number; + /** @deprecated */ readonly domLoading: number; + /** @deprecated */ + readonly domainLookupEnd: number; + /** @deprecated */ + readonly domainLookupStart: number; + /** @deprecated */ readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; + /** @deprecated */ readonly navigationStart: number; readonly redirectCount: number; + /** @deprecated */ readonly redirectEnd: number; + /** @deprecated */ readonly redirectStart: number; + /** @deprecated */ readonly requestStart: number; + /** @deprecated */ readonly responseEnd: number; + /** @deprecated */ readonly responseStart: number; readonly type: NavigationType; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly workerStart: number; } declare var PerformanceNavigationTiming: { @@ -8937,6 +9963,7 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly workerStart: number; } declare var PerformanceResourceTiming: { @@ -8947,13 +9974,13 @@ declare var 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 domainLookupEnd: number; + readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -8964,9 +9991,9 @@ interface PerformanceTiming { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly secureConnectionStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; - readonly secureConnectionStart: number; toJSON(): any; } @@ -8975,35 +10002,6 @@ declare var 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 { } @@ -9085,12 +10083,11 @@ declare var 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; + new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent; }; interface Position { @@ -9138,10 +10135,21 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; + new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent; }; +interface PromiseRejectionEvent extends Event { + readonly promise: PromiseLike; + readonly reason: any; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: PromiseLike; + reason?: any; +} + interface PushManager { + readonly supportedContentEncodings: ReadonlyArray; getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; subscribe(options?: PushSubscriptionOptionsInit): Promise; @@ -9153,7 +10161,8 @@ declare var PushManager: { }; interface PushSubscription { - readonly endpoint: USVString; + readonly endpoint: string; + readonly expirationTime: number | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): any; @@ -9175,112 +10184,13 @@ declare var 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 | DOMRect; - getClientRects(): ClientRectList | DOMRectList; - 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; +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; } -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; - readonly signal: AbortSignal; - 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; +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDtlsTransportEventMap { @@ -9326,7 +10236,7 @@ interface RTCDtmfSender extends EventTarget { readonly canInsertDTMF: boolean; readonly duration: number; readonly interToneGap: number; - ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null; readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; @@ -9341,19 +10251,10 @@ declare var 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; + sdpMid: string | null; toJSON(): any; } @@ -9458,28 +10359,28 @@ interface RTCPeerConnection extends EventTarget { 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; + onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null; + oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; + onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; + onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null; + onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; readonly remoteDescription: RTCSessionDescription | null; readonly signalingState: RTCSignalingState; - addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise; addStream(stream: MediaStream): void; close(): void; - createAnswer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - createOffer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, options?: RTCOfferOptions): Promise; + createAnswer(options?: RTCOfferOptions): Promise; + createOffer(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; + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit): 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; @@ -9502,10 +10403,14 @@ declare var RTCPeerConnectionIceEvent: { interface RTCRtpReceiverEventMap { "error": Event; + "msdecodercapacitychange": Event; + "msdsh": Event; } interface RTCRtpReceiver extends RTCStatsProvider { onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null; + onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9602,433 +10507,122 @@ declare var RTCStatsProvider: { new(): RTCStatsProvider; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; +interface RandomSource { + getRandomValues(array: T): T; } -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; +declare var RandomSource: { + prototype: RandomSource; + new(): RandomSource; }; -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; - lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; - unlockOrientation(): 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; +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 | DOMRect; + getClientRects(): ClientRectList | DOMRectList; + insertNode(node: Node): void; + isPointInRange(node: Node, offset: number): boolean; + selectNode(node: Node): void; + selectNodeContents(node: Node): void; + setEnd(node: Node, offset: number): void; + setEndAfter(node: Node): void; + setEndBefore(node: Node): void; + setStart(node: Node, offset: number): void; + setStartAfter(node: Node): void; + setStartBefore(node: 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 Selection: { - prototype: Selection; - new(): Selection; +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 ServiceWorkerEventMap extends AbstractWorkerEventMap { - "statechange": Event; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; } -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; +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; }; -interface ServiceWorkerContainerEventMap { - "controllerchange": Event; - "message": ServiceWorkerMessageEvent; +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; } -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; +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; }; -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 { +interface Request extends 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 signal: AbortSignal | null; + readonly type: RequestType; readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; + clone(): Request; } -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; }; -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; +interface Response extends Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; } -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; +declare var Response: { + prototype: Response; + new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; }; interface SVGAElement extends SVGGraphicsElement, SVGURIReference { @@ -10148,6 +10742,11 @@ declare var SVGAnimatedNumberList: { new(): SVGAnimatedNumberList; }; +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; readonly baseVal: SVGPreserveAspectRatio; @@ -10284,21 +10883,21 @@ interface SVGElementEventMap extends ElementEventMap { "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; +interface SVGElement extends Element, ElementCSSInlineStyle { + readonly className: any; + onclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null; + onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null; + onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null; + onload: ((this: SVGElement, ev: Event) => any) | null; + onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null; + onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null; + readonly ownerSVGElement: SVGSVGElement | null; + readonly viewportElement: SVGElement | null; + /** @deprecated */ 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; @@ -10328,7 +10927,9 @@ declare var SVGElementInstance: { }; interface SVGElementInstanceList { + /** @deprecated */ readonly length: number; + /** @deprecated */ item(index: number): SVGElementInstance; } @@ -10811,7 +11412,9 @@ declare var SVGFETurbulenceElement: { }; interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { + /** @deprecated */ readonly filterResX: SVGAnimatedInteger; + /** @deprecated */ readonly filterResY: SVGAnimatedInteger; readonly filterUnits: SVGAnimatedEnumeration; readonly height: SVGAnimatedLength; @@ -10819,6 +11422,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + /** @deprecated */ 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; @@ -10831,6 +11435,19 @@ declare var SVGFilterElement: { new(): SVGFilterElement; }; +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 SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; readonly width: SVGAnimatedLength; @@ -10883,12 +11500,15 @@ declare var SVGGradientElement: { }; interface SVGGraphicsElement extends SVGElement, SVGTests { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; + /** @deprecated */ + readonly farthestViewportElement: SVGElement | null; + /** @deprecated */ + readonly nearestViewportElement: SVGElement | null; readonly transform: SVGAnimatedTransformList; getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; + getCTM(): SVGMatrix | null; + getScreenCTM(): SVGMatrix | null; + /** @deprecated */ 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; @@ -10970,22 +11590,6 @@ declare var 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; @@ -11002,6 +11606,22 @@ declare var SVGLineElement: { new(): SVGLineElement; }; +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 SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly markerHeight: SVGAnimatedLength; readonly markerUnits: SVGAnimatedEnumeration; @@ -11012,12 +11632,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: 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; @@ -11027,12 +11647,12 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { 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; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; }; interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { @@ -11116,26 +11736,47 @@ declare var SVGNumberList: { }; interface SVGPathElement extends SVGGraphicsElement { + /** @deprecated */ readonly pathSegList: SVGPathSegList; + /** @deprecated */ createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + /** @deprecated */ createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + /** @deprecated */ createSVGPathSegClosePath(): SVGPathSegClosePath; + /** @deprecated */ createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + /** @deprecated */ createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + /** @deprecated */ createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + /** @deprecated */ createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + /** @deprecated */ createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + /** @deprecated */ createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + /** @deprecated */ createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + /** @deprecated */ createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + /** @deprecated */ createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + /** @deprecated */ getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; @@ -11581,6 +12222,84 @@ declare var SVGRectElement: { new(): SVGRectElement; }; +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ + contentScriptType: string; + /** @deprecated */ + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: ((this: SVGSVGElement, ev: Event) => any) | null; + onerror: ((this: SVGSVGElement, ev: Event) => any) | null; + onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null; + onunload: ((this: SVGSVGElement, ev: Event) => any) | null; + onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; + /** @deprecated */ + readonly pixelUnitToMillimeterX: number; + /** @deprecated */ + readonly pixelUnitToMillimeterY: number; + /** @deprecated */ + readonly screenPixelToMillimeterX: number; + /** @deprecated */ + readonly screenPixelToMillimeterY: number; + /** @deprecated */ + 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; + /** @deprecated */ + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + /** @deprecated */ + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + /** @deprecated */ + pauseAnimations(): void; + /** @deprecated */ + setCurrentTime(seconds: number): void; + /** @deprecated */ + suspendRedraw(maxWaitMilliseconds: number): number; + /** @deprecated */ + unpauseAnimations(): void; + /** @deprecated */ + unsuspendRedraw(suspendHandleID: number): void; + /** @deprecated */ + 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 SVGScriptElement extends SVGElement, SVGURIReference { type: string; addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -11623,6 +12342,15 @@ declare var SVGStringList: { new(): SVGStringList; }; +interface SVGStylable { + className: any; +} + +declare var SVGStylable: { + prototype: SVGStylable; + new(): SVGStylable; +}; + interface SVGStyleElement extends SVGElement { disabled: boolean; media: string; @@ -11639,69 +12367,6 @@ declare var 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; @@ -11726,6 +12391,27 @@ declare var SVGSymbolElement: { new(): SVGSymbolElement; }; +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 SVGTests { + readonly requiredExtensions: SVGStringList; + /** @deprecated */ + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + /** @deprecated */ + hasExtension(extension: string): boolean; +} + interface SVGTextContentElement extends SVGGraphicsElement { readonly lengthAdjust: SVGAnimatedEnumeration; readonly textLength: SVGAnimatedLength; @@ -11872,18 +12558,10 @@ declare var 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; +interface SVGURIReference { + readonly href: SVGAnimatedString; } -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -}; - interface SVGUnitTypes { readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; readonly SVG_UNIT_TYPE_UNKNOWN: number; @@ -11892,9 +12570,9 @@ interface SVGUnitTypes { declare var SVGUnitTypes: SVGUnitTypes; interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; + readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; + readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -11909,7 +12587,8 @@ declare var SVGUseElement: { new(): SVGUseElement; }; -interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { +interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { + /** @deprecated */ 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; @@ -11945,6 +12624,477 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; +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; + /** @deprecated */ + 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) | null; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + unlockOrientation(): 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 ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + /** @deprecated */ + readonly bufferSize: number; + /** @deprecated */ + onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null; + 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 ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEvent extends Event { + readonly blockedURI: string; + readonly columnNumber: number; + readonly documentURI: string; + readonly effectiveDirective: string; + readonly lineNumber: number; + readonly originalPolicy: string; + readonly referrer: string; + readonly sourceFile: string; + readonly statusCode: number; + readonly violatedDirective: string; +} + +declare var SecurityPolicyViolationEvent: { + prototype: SecurityPolicyViolationEvent; + new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent; +}; + +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 ServiceUIFrameContext { + getCachedFrameMessage(key: string): string; + postFrameMessage(key: string, data: string): void; +} +declare var ServiceUIFrameContext: ServiceUIFrameContext; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; + 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; + "messageerror": MessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; + onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null; + readonly ready: Promise; + getRegistration(clientURL?: string): Promise; + getRegistrations(): Promise; + register(scriptURL: string, options?: RegistrationOptions): Promise; + startMessages(): 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: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | 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) | null; + readonly pushManager: PushManager; + readonly scope: string; + 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 ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: "open" | "closed"; +} + +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 | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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) | null; + 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 charLength: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance; +} + +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) | null; + onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + 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(): 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, value: string): void; + [key: string]: any; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + readonly key: string | null; + readonly newValue: string | null; + readonly oldValue: string | null; + readonly storageArea: Storage | null; + readonly url: string; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StorageEventInit extends EventInit { + key?: string; + newValue?: string; + oldValue?: string; + storageArea?: Storage; + url: string; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string | null; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet | null; + readonly title: string | null; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index: number): StyleSheet | null; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): 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: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SyncManager { getTags(): Promise; register(tag: string): Promise; @@ -11956,8 +13106,8 @@ declare var SyncManager: { }; interface Text extends CharacterData { - readonly wholeText: string; readonly assignedSlot: HTMLSlotElement | null; + readonly wholeText: string; splitText(offset: number): Text; } @@ -11966,10 +13116,30 @@ declare var Text: { new(data?: string): Text; }; +interface TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string; +} + +declare var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; +}; + +interface TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; +} + +declare var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; +}; + 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; @@ -12020,10 +13190,10 @@ interface TextTrack extends EventTarget { 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; + mode: TextTrackMode | number; + oncuechange: ((this: TextTrack, ev: Event) => any) | null; + onerror: ((this: TextTrack, ev: Event) => any) | null; + onload: ((this: TextTrack, ev: Event) => any) | null; readonly readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; @@ -12060,8 +13230,8 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { endTime: number; id: string; - onenter: (this: TextTrackCue, ev: Event) => any; - onexit: (this: TextTrackCue, ev: Event) => any; + onenter: ((this: TextTrackCue, ev: Event) => any) | null; + onexit: ((this: TextTrackCue, ev: Event) => any) | null; pauseOnExit: boolean; startTime: number; text: string; @@ -12147,6 +13317,7 @@ interface TouchEvent extends UIEvent { readonly shiftKey: boolean; readonly targetTouches: TouchList; readonly touches: TouchList; + /** @deprecated */ readonly which: number; } @@ -12155,6 +13326,12 @@ declare var TouchEvent: { new(type: string, touchEventInit?: TouchEventInit): TouchEvent; }; +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + interface TouchList { readonly length: number; item(index: number): Touch | null; @@ -12188,17 +13365,18 @@ declare var TransitionEvent: { interface TreeWalker { currentNode: Node; + /** @deprecated */ readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; + readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; + firstChild(): Node | null; + lastChild(): Node | null; + nextNode(): Node | null; + nextSibling(): Node | null; + parentNode(): Node | null; + previousNode(): Node | null; + previousSibling(): Node | null; } declare var TreeWalker: { @@ -12217,15 +13395,6 @@ declare var 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; @@ -12237,8 +13406,8 @@ interface URL { port: string; protocol: string; search: string; - username: string; readonly searchParams: URLSearchParams; + username: string; toString(): string; } @@ -12249,6 +13418,142 @@ declare var URL: { revokeObjectURL(url: string): 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; + new (init?: string | URLSearchParams): URLSearchParams; +}; + +interface VRDisplay extends EventTarget { + readonly capabilities: VRDisplayCapabilities; + depthFar: number; + depthNear: number; + readonly displayId: number; + readonly displayName: string; + readonly isConnected: boolean; + readonly isPresenting: boolean; + readonly stageParameters: VRStageParameters | null; + cancelAnimationFrame(handle: number): void; + exitPresent(): Promise; + getEyeParameters(whichEye: string): VREyeParameters; + getFrameData(frameData: VRFrameData): boolean; + getLayers(): VRLayer[]; + /** @deprecated */ + getPose(): VRPose; + requestAnimationFrame(callback: FrameRequestCallback): number; + requestPresent(layers: VRLayer[]): Promise; + resetPose(): void; + submitFrame(pose?: VRPose): void; +} + +declare var VRDisplay: { + prototype: VRDisplay; + new(): VRDisplay; +}; + +interface VRDisplayCapabilities { + readonly canPresent: boolean; + readonly hasExternalDisplay: boolean; + readonly hasOrientation: boolean; + readonly hasPosition: boolean; + readonly maxLayers: number; +} + +declare var VRDisplayCapabilities: { + prototype: VRDisplayCapabilities; + new(): VRDisplayCapabilities; +}; + +interface VRDisplayEvent extends Event { + readonly display: VRDisplay; + readonly reason: VRDisplayEventReason | null; +} + +declare var VRDisplayEvent: { + prototype: VRDisplayEvent; + new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent; +}; + +interface VREyeParameters { + /** @deprecated */ + readonly fieldOfView: VRFieldOfView; + readonly offset: Float32Array; + readonly renderHeight: number; + readonly renderWidth: number; +} + +declare var VREyeParameters: { + prototype: VREyeParameters; + new(): VREyeParameters; +}; + +interface VRFieldOfView { + readonly downDegrees: number; + readonly leftDegrees: number; + readonly rightDegrees: number; + readonly upDegrees: number; +} + +declare var VRFieldOfView: { + prototype: VRFieldOfView; + new(): VRFieldOfView; +}; + +interface VRFrameData { + readonly leftProjectionMatrix: Float32Array; + readonly leftViewMatrix: Float32Array; + readonly pose: VRPose; + readonly rightProjectionMatrix: Float32Array; + readonly rightViewMatrix: Float32Array; + readonly timestamp: number; +} + +declare var VRFrameData: { + prototype: VRFrameData; + new(): VRFrameData; +}; + +interface VRPose { + readonly angularAcceleration: Float32Array | null; + readonly angularVelocity: Float32Array | null; + readonly linearAcceleration: Float32Array | null; + readonly linearVelocity: Float32Array | null; + readonly orientation: Float32Array | null; + readonly position: Float32Array | null; + readonly timestamp: number; +} + +declare var VRPose: { + prototype: VRPose; + new(): VRPose; +}; + interface ValidityState { readonly badInput: boolean; readonly customError: boolean; @@ -12257,10 +13562,10 @@ interface ValidityState { readonly rangeUnderflow: boolean; readonly stepMismatch: boolean; readonly tooLong: boolean; + readonly tooShort: boolean; readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; - readonly tooShort: boolean; } declare var ValidityState: { @@ -12303,9 +13608,9 @@ interface VideoTrackListEventMap { 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; + onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; + onchange: ((this: VideoTrackList, ev: Event) => any) | null; + onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null; readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; @@ -12321,6 +13626,137 @@ declare var VideoTrackList: { new(): VideoTrackList; }; +interface WEBGL_color_buffer_float { + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly RGB32F_EXT: number; + readonly RGBA32F_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + 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_SRGB8_ALPHA8_ASTC_10x10_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_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_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; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +}; + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_SRGB_S3TC_DXT1_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_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +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 WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_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 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 DRAW_BUFFER0_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 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 MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + interface WaveShaperNode extends AudioNode { curve: Float32Array | null; oversample: OverSampleType; @@ -12332,8 +13768,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -12353,44 +13789,6 @@ declare var 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; @@ -12467,8 +13865,8 @@ interface WebGLRenderingContext { 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; + bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void; + bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void; checkFramebufferStatus(target: number): number; clear(mask: number): void; clearColor(red: number, green: number, blue: number, alpha: number): void; @@ -12476,8 +13874,8 @@ interface WebGLRenderingContext { 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; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): 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; @@ -12567,7 +13965,7 @@ interface WebGLRenderingContext { 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; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | 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; @@ -12732,13 +14130,13 @@ interface WebGLRenderingContext { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -12763,9 +14161,9 @@ interface WebGLRenderingContext { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -12795,18 +14193,18 @@ interface WebGLRenderingContext { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -12840,20 +14238,6 @@ interface WebGLRenderingContext { 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; @@ -12886,9 +14270,23 @@ interface WebGLRenderingContext { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13034,13 +14432,13 @@ declare var WebGLRenderingContext: { 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 LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; readonly LINK_STATUS: number; readonly LOW_FLOAT: number; readonly LOW_INT: number; @@ -13065,9 +14463,9 @@ declare var WebGLRenderingContext: { readonly NEAREST_MIPMAP_NEAREST: number; readonly NEVER: number; readonly NICEST: number; - readonly NO_ERROR: number; readonly NONE: number; readonly NOTEQUAL: number; + readonly NO_ERROR: number; readonly ONE: number; readonly ONE_MINUS_CONSTANT_ALPHA: number; readonly ONE_MINUS_CONSTANT_COLOR: number; @@ -13097,18 +14495,18 @@ declare var WebGLRenderingContext: { readonly REPEAT: number; readonly REPLACE: number; readonly RGB: number; - readonly RGB5_A1: number; readonly RGB565: number; + readonly RGB5_A1: number; readonly RGBA: number; readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: 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; @@ -13142,20 +14540,6 @@ declare var WebGLRenderingContext: { 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; @@ -13188,9 +14572,23 @@ declare var WebGLRenderingContext: { readonly TEXTURE7: number; readonly TEXTURE8: number; readonly TEXTURE9: 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 TRIANGLES: 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; @@ -13251,6 +14649,9 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; +interface WebGLVertexArrayObjectOES { +} + interface WebKitCSSMatrix { a: number; b: number; @@ -13351,18 +14752,6 @@ declare var 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; @@ -13371,18 +14760,18 @@ interface WebSocketEventMap { } interface WebSocket extends EventTarget { - binaryType: string; + binaryType: BinaryType; 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; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; readonly protocol: string; readonly readyState: number; readonly url: string; close(code?: number, reason?: string): void; - send(data: USVString | ArrayBuffer | Blob | ArrayBufferView): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; readonly CLOSED: number; readonly CLOSING: number; readonly CONNECTING: number; @@ -13427,8 +14816,6 @@ declare var WheelEvent: { interface WindowEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; - "afterprint": Event; - "beforeprint": Event; "beforeunload": BeforeUnloadEvent; "blur": FocusEvent; "canplay": Event; @@ -13450,7 +14837,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "drop": DragEvent; "durationchange": Event; "emptied": Event; - "ended": MediaStreamErrorEvent; + "ended": Event; "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; @@ -13472,21 +14859,21 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "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; + "MSGestureChange": Event; + "MSGestureDoubleTap": Event; + "MSGestureEnd": Event; + "MSGestureHold": Event; + "MSGestureStart": Event; + "MSGestureTap": Event; + "MSInertiaStart": Event; + "MSPointerCancel": Event; + "MSPointerDown": Event; + "MSPointerEnter": Event; + "MSPointerLeave": Event; + "MSPointerMove": Event; + "MSPointerOut": Event; + "MSPointerOver": Event; + "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -13516,19 +14903,32 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "touchstart": TouchEvent; "unload": Event; "volumechange": Event; + "vrdisplayactivate": Event; + "vrdisplayblur": Event; + "vrdisplayconnect": Event; + "vrdisplaydeactivate": Event; + "vrdisplaydisconnect": Event; + "vrdisplayfocus": Event; + "vrdisplaypointerrestricted": Event; + "vrdisplaypointerunrestricted": Event; + "vrdisplaypresentchange": Event; "waiting": Event; } interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { + Blob: typeof Blob; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; readonly applicationCache: ApplicationCache; readonly caches: CacheStorage; readonly clientInformation: Navigator; readonly closed: boolean; readonly crypto: Crypto; + customElements: CustomElementRegistry; defaultStatus: string; readonly devicePixelRatio: number; - readonly document: Document; readonly doNotTrack: string; + readonly document: Document; event: Event | undefined; readonly external: External; readonly frameElement: Element; @@ -13538,7 +14938,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly innerWidth: number; readonly isSecureContext: boolean; readonly length: number; - readonly location: Location; + location: Location; readonly locationbar: BarProp; readonly menubar: BarProp; readonly msContentScript: ExtensionScriptApis; @@ -13546,99 +14946,106 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + onabort: ((this: Window, ev: UIEvent) => any) | null; + onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; + onblur: ((this: Window, ev: FocusEvent) => any) | null; + oncanplay: ((this: Window, ev: Event) => any) | null; + oncanplaythrough: ((this: Window, ev: Event) => any) | null; + onchange: ((this: Window, ev: Event) => any) | null; + onclick: ((this: Window, ev: MouseEvent) => any) | null; + oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; + oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; + ondblclick: ((this: Window, ev: MouseEvent) => any) | null; + ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; + ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; + ondrag: ((this: Window, ev: DragEvent) => any) | null; + ondragend: ((this: Window, ev: DragEvent) => any) | null; + ondragenter: ((this: Window, ev: DragEvent) => any) | null; + ondragleave: ((this: Window, ev: DragEvent) => any) | null; + ondragover: ((this: Window, ev: DragEvent) => any) | null; + ondragstart: ((this: Window, ev: DragEvent) => any) | null; + ondrop: ((this: Window, ev: DragEvent) => any) | null; + ondurationchange: ((this: Window, ev: Event) => any) | null; + onemptied: ((this: Window, ev: Event) => any) | null; + onended: ((this: Window, ev: Event) => any) | null; 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; + onfocus: ((this: Window, ev: FocusEvent) => any) | null; + onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; + oninput: ((this: Window, ev: Event) => any) | null; + oninvalid: ((this: Window, ev: Event) => any) | null; + onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; + onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; + onload: ((this: Window, ev: Event) => any) | null; + onloadeddata: ((this: Window, ev: Event) => any) | null; + onloadedmetadata: ((this: Window, ev: Event) => any) | null; + onloadstart: ((this: Window, ev: Event) => any) | null; + onmessage: ((this: Window, ev: MessageEvent) => any) | null; + onmousedown: ((this: Window, ev: MouseEvent) => any) | null; + onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; + onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; + onmousemove: ((this: Window, ev: MouseEvent) => any) | null; + onmouseout: ((this: Window, ev: MouseEvent) => any) | null; + onmouseover: ((this: Window, ev: MouseEvent) => any) | null; + onmouseup: ((this: Window, ev: MouseEvent) => any) | null; + onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; + onmsgesturechange: ((this: Window, ev: Event) => any) | null; + onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; + onmsgestureend: ((this: Window, ev: Event) => any) | null; + onmsgesturehold: ((this: Window, ev: Event) => any) | null; + onmsgesturestart: ((this: Window, ev: Event) => any) | null; + onmsgesturetap: ((this: Window, ev: Event) => any) | null; + onmsinertiastart: ((this: Window, ev: Event) => any) | null; + onmspointercancel: ((this: Window, ev: Event) => any) | null; + onmspointerdown: ((this: Window, ev: Event) => any) | null; + onmspointerenter: ((this: Window, ev: Event) => any) | null; + onmspointerleave: ((this: Window, ev: Event) => any) | null; + onmspointermove: ((this: Window, ev: Event) => any) | null; + onmspointerout: ((this: Window, ev: Event) => any) | null; + onmspointerover: ((this: Window, ev: Event) => any) | null; + onmspointerup: ((this: Window, ev: Event) => any) | null; + onoffline: ((this: Window, ev: Event) => any) | null; + ononline: ((this: Window, ev: Event) => any) | null; + onorientationchange: ((this: Window, ev: Event) => any) | null; + onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; + onpause: ((this: Window, ev: Event) => any) | null; + onplay: ((this: Window, ev: Event) => any) | null; + onplaying: ((this: Window, ev: Event) => any) | null; + onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; + onprogress: ((this: Window, ev: ProgressEvent) => any) | null; + onratechange: ((this: Window, ev: Event) => any) | null; + onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; + onreset: ((this: Window, ev: Event) => any) | null; + onresize: ((this: Window, ev: UIEvent) => any) | null; + onscroll: ((this: Window, ev: UIEvent) => any) | null; + onseeked: ((this: Window, ev: Event) => any) | null; + onseeking: ((this: Window, ev: Event) => any) | null; + onselect: ((this: Window, ev: UIEvent) => any) | null; + onstalled: ((this: Window, ev: Event) => any) | null; + onstorage: ((this: Window, ev: StorageEvent) => any) | null; + onsubmit: ((this: Window, ev: Event) => any) | null; + onsuspend: ((this: Window, ev: Event) => any) | null; + ontimeupdate: ((this: Window, ev: Event) => any) | null; 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; + onunload: ((this: Window, ev: Event) => any) | null; + onvolumechange: ((this: Window, ev: Event) => any) | null; + onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplayblur: ((this: Window, ev: Event) => any) | null; + onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; + onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; + onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; + onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; + onwaiting: ((this: Window, ev: Event) => any) | null; + readonly opener: any; + readonly orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; readonly pageXOffset: number; @@ -13651,9 +15058,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly screenTop: number; readonly screenX: number; readonly screenY: number; - readonly scrollbars: BarProp; readonly scrollX: number; readonly scrollY: number; + readonly scrollbars: BarProp; readonly self: Window; readonly speechSynthesis: SpeechSynthesis; status: string; @@ -13662,20 +15069,18 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window 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; + 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; departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; getSelection(): Selection; matchMedia(mediaQuery: string): MediaQueryList; moveBy(x?: number, y?: number): void; @@ -13689,19 +15094,17 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window requestAnimationFrame(callback: FrameRequestCallback): number; resizeBy(x?: number, y?: number): void; resizeTo(x?: number, y?: number): void; + scroll(options?: ScrollToOptions): void; scroll(x?: number, y?: number): void; + scrollBy(options?: ScrollToOptions): void; scrollBy(x?: number, y?: number): void; + scrollTo(options?: ScrollToOptions): 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; @@ -13713,12 +15116,79 @@ declare var Window: { new(): Window; }; +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowEventHandlersEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "hashchange": HashChangeEvent; + "message": MessageEvent; + "offline": Event; + "online": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface WindowEventHandlers { + onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; + onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; + onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; + ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; + onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; + onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers extends 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 WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; } interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: Worker, ev: MessageEvent) => any; + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** @deprecated */ postMessage(message: any, transfer?: any[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -13732,6 +15202,41 @@ declare var Worker: { new(stringUrl: string): Worker; }; +interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; +}; + +interface WritableStreamDefaultController { + error(error?: any): void; +} + +declare var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; +}; + +interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: any): Promise; +} + +declare var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(): WritableStreamDefaultWriter; +}; + 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; @@ -13749,7 +15254,8 @@ interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -13761,15 +15267,12 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { 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; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): 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; @@ -13793,6 +15296,30 @@ declare var XMLHttpRequest: { readonly UNSENT: 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) | null; + onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + 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 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; @@ -13896,1070 +15423,16 @@ declare var 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; +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: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[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 ElementCreationOptions { - is?: 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 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; -} - -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 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; - 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; -} - -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; -} - -interface AnimationKeyFrame { - offset?: number | null | (number | null)[]; - easing?: string | string[]; - [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined; -} - -interface AnimationOptions { - id?: string; - delay?: number; - direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; - duration?: number; - easing?: string; - endDelay?: number; - fill?: "none" | "forwards" | "backwards" | "both"| "auto"; - iterationStart?: number; - iterations?: number; -} - -interface AnimationTimeline { - readonly currentTime: number | null; -} - -interface ComputedTimingProperties { - endTime: number; - activeDuration: number; - localTime: number | null; - progress: number | null; - currentIteration: number | null; -} - -interface AnimationEffectReadOnly { - readonly timing: number; - getComputedTiming(): ComputedTimingProperties; -} - -interface AnimationPlaybackEventInit extends EventInit { - currentTime?: number | null; - timelineTime?: number | null; -} - -interface AnimationPlaybackEvent extends Event { - readonly currentTime: number | null; - readonly timelineTime: number | null; -} - -declare var AnimationPlaybackEvent: { - prototype: AnimationPlaybackEvent; - new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; -}; - -interface Animation { - currentTime: number | null; - effect: AnimationEffectReadOnly; - readonly finished: Promise; - id: string; - readonly pending: boolean; - readonly playState: "idle" | "running" | "paused" | "finished"; - playbackRate: number; - readonly ready: Promise; - startTime: number; - timeline: AnimationTimeline; - oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any; - onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any; - cancel(): void; - finish(): void; - pause(): void; - play(): void; - reverse(): void; -} - -declare var Animation: { - prototype: Animation; - new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; }; declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; @@ -14967,66 +15440,95 @@ declare type EventListenerOrEventListenerObject = EventListener | EventListenerO interface DecodeErrorCallback { (error: DOMException): void; } + interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } + interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; } + +interface EventHandlerNonNull { + (event: Event): any; +} + interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, 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 MediaQueryListListener { + (mql: MediaQueryList): void; } + 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 WritableStreamChunkCallback { + (chunk: any, controller: WritableStreamDefaultController): void; +} + +interface WritableStreamDefaultControllerCallback { + (controller: WritableStreamDefaultController): void; +} + +interface WritableStreamErrorCallback { + (reason: string): void; +} + interface HTMLElementTagNameMap { "a": HTMLAnchorElement; "abbr": HTMLElement; @@ -15153,7 +15655,6 @@ interface HTMLElementTagNameMap { "var": HTMLElement; "video": HTMLVideoElement; "wbr": HTMLElement; - "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } @@ -15216,18 +15717,28 @@ interface SVGElementTagNameMap { /** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ 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 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 Blob: typeof Blob; +declare var URL: typeof URL; +declare var URLSearchParams: typeof URLSearchParams; declare var applicationCache: ApplicationCache; declare var caches: CacheStorage; declare var clientInformation: Navigator; declare var closed: boolean; declare var crypto: Crypto; +declare var customElements: CustomElementRegistry; declare var defaultStatus: string; declare var devicePixelRatio: number; -declare var document: Document; declare var doNotTrack: string; +declare var document: Document; declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; @@ -15245,97 +15756,104 @@ 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 onabort: ((this: Window, ev: UIEvent) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +declare var onchange: ((this: Window, ev: Event) => any) | null; +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; +declare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; +declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +declare var onemptied: ((this: Window, ev: Event) => any) | null; +declare var onended: ((this: Window, ev: Event) => any) | null; 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 onfocus: ((this: Window, ev: FocusEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +declare var onload: ((this: Window, ev: Event) => any) | null; +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadstart: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; +declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; +declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; +declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; +declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; +declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; +declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; +declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; +declare var onmspointermove: ((this: Window, ev: Event) => any) | null; +declare var onmspointerout: ((this: Window, ev: Event) => any) | null; +declare var onmspointerover: ((this: Window, ev: Event) => any) | null; +declare var onmspointerup: ((this: Window, ev: Event) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onorientationchange: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpause: ((this: Window, ev: Event) => any) | null; +declare var onplay: ((this: Window, ev: Event) => any) | null; +declare var onplaying: ((this: Window, ev: Event) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onratechange: ((this: Window, ev: Event) => any) | null; +declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onseeked: ((this: Window, ev: Event) => any) | null; +declare var onseeking: ((this: Window, ev: Event) => any) | null; +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; 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 onunload: ((this: Window, ev: Event) => any) | null; +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; +declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; +declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; @@ -15350,9 +15868,9 @@ 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 scrollbars: BarProp; declare var self: Window; declare var speechSynthesis: SpeechSynthesis; declare var status: string; @@ -15361,17 +15879,18 @@ 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 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 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 getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; declare function getSelection(): Selection; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; @@ -15385,23 +15904,21 @@ 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(options?: ScrollToOptions): void; declare function scroll(x?: number, y?: number): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(options?: ScrollToOptions): 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 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; @@ -15412,26 +15929,36 @@ 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 onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; +declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; 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 fetch(input?: Request | string, 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 ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type IDBValidKey = number | string | Date | IDBArrayKey; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = Blob | BufferSource | FormData | string; +type MutationRecordType = "attributes" | "characterData" | "childList"; +type AAGUID = string; +type BodyInit = any; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; @@ -15453,9 +15980,6 @@ 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; @@ -15464,35 +15988,32 @@ 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 OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type AppendMode = "segments" | "sequence"; +type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "suspended" | "running" | "closed"; +type BinaryType = "blob" | "arraybuffer"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanPlayTypeResult = "" | "maybe" | "probably"; type CanvasFillRule = "nonzero" | "evenodd"; type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; +type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; +type EndOfStreamError = "network" | "decode"; type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; +type GamepadHand = "" | "left" | "right"; +type GamepadHapticActuatorType = "vibration"; type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type GamepadMappingType = "" | "standard"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; 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"; @@ -15500,25 +16021,23 @@ type MSStatsType = "description" | "localclientevent" | "inbound-network" | "out type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaStreamTrackState = "live" | "ended"; 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 PanningModelType = "equalpower" | "HRTF"; +type PaymentComplete = "success" | "fail" | "unknown"; 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"; @@ -15526,9 +16045,9 @@ 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 RTCIceGatherPolicy = "all" | "nohost" | "relay"; 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"; @@ -15539,9 +16058,22 @@ type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | " 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 ReadyState = "closed" | "open" | "ended"; +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 ScopedCredentialType = "ScopedCred"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; +type TextTrackMode = "disabled" | "hidden" | "showing"; type Transport = "usb" | "nfc" | "ble"; +type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; +type VREye = "left" | "right"; type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 5c1bae54f1b..e9c42de786c 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -18,11 +18,15 @@ and limitations under the License. /// - ///////////////////////////// /// Worker APIs ///////////////////////////// +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + interface Algorithm { name: string; } @@ -34,16 +38,52 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface ClientQueryOptions { + includeReserved?: boolean; + includeUncontrolled?: boolean; + type?: ClientTypes; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; wasClean?: boolean; } +interface ErrorEventInit extends EventInit { + colno?: number; + error?: any; + filename?: string; + lineno?: number; + message?: string; +} + interface EventInit { - scoped?: boolean; bubbles?: boolean; cancelable?: boolean; + scoped?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; +} + +interface ExtendableEventInit extends EventInit { +} + +interface ExtendableMessageEventInit extends ExtendableEventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: Client | ServiceWorker | MessagePort | null; +} + +interface FetchEventInit extends ExtendableEventInit { + clientId?: string; + request: Request; + reservedClientId?: string; + targetClientId?: string; } interface GetNotificationOptions { @@ -61,20 +101,26 @@ interface IDBObjectStoreParameters { } interface KeyAlgorithm { - name?: string; + name: string; } interface MessageEventInit extends EventInit { - lastEventId?: string; channel?: string; data?: any; + lastEventId?: string; origin?: string; ports?: MessagePort[]; - source?: any; + source?: object | null; +} + +interface NotificationEventInit extends ExtendableEventInit { + action?: string; + notification: Notification; } interface NotificationOptions { body?: string; + data?: any; dir?: NotificationDirection; icon?: string; lang?: string; @@ -85,14 +131,28 @@ interface ObjectURLOptions { oneTimeOnly?: boolean; } +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface PushEventInit extends ExtendableEventInit { + data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; +} + +interface PushSubscriptionChangeInit extends ExtendableEventInit { + newSubscription?: PushSubscription; + oldSubscription?: PushSubscription; +} + interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | null; + applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null; userVisibleOnly?: boolean; } interface RequestInit { - signal?: AbortSignal; - body?: Blob | BufferSource | FormData | string | null; + body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -103,6 +163,7 @@ interface RequestInit { redirect?: RequestRedirect; referrer?: string; referrerPolicy?: ReferrerPolicy; + signal?: object; window?: any; } @@ -112,46 +173,27 @@ interface ResponseInit { statusText?: string; } -interface ClientQueryOptions { - includeUncontrolled?: boolean; - type?: ClientType; -} - -interface ExtendableEventInit extends EventInit { -} - -interface ExtendableMessageEventInit extends ExtendableEventInit { - data?: any; - origin?: string; - lastEventId?: string; - source?: Client | ServiceWorker | MessagePort | null; - ports?: MessagePort[] | null; -} - -interface FetchEventInit extends ExtendableEventInit { - request: Request; - clientId?: string | null; - isReload?: boolean; -} - -interface NotificationEventInit extends ExtendableEventInit { - notification: Notification; - action?: string; -} - -interface PushEventInit extends ExtendableEventInit { - data?: BufferSource | USVString; -} - interface SyncEventInit extends ExtendableEventInit { - tag: string; lastChance?: boolean; + tag: string; } interface EventListener { (evt: Event): void; } +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + 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 AudioBuffer { readonly duration: number; readonly length: number; @@ -180,14 +222,28 @@ declare var Blob: { new (blobParts?: any[], options?: BlobPropertyBag): Blob; }; +interface BlobPropertyBag { + endings?: string; + type?: string; +} + +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + 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; + add(request: Request | string): Promise; + addAll(requests: (Request | string)[]): Promise; + delete(request: Request | string, options?: CacheQueryOptions): Promise; + keys(request?: Request | string, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; + matchAll(request?: Request | string, options?: CacheQueryOptions): Promise; + put(request: Request | string, response: Response): Promise; } declare var Cache: { @@ -199,7 +255,7 @@ interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; keys(): Promise; - match(request: RequestInfo, options?: CacheQueryOptions): Promise; + match(request: Request | string, options?: CacheQueryOptions): Promise; open(cacheName: string): Promise; } @@ -208,22 +264,49 @@ declare var CacheStorage: { new(): CacheStorage; }; +interface Client { + readonly id: string; + readonly reserved: boolean; + readonly type: ClientTypes; + readonly url: string; + postMessage(message: any, transfer?: any[]): void; +} + +declare var Client: { + prototype: Client; + new(): Client; +}; + +interface Clients { + claim(): Promise; + get(id: string): Promise; + matchAll(options?: ClientQueryOptions): Promise; + openWindow(url: string): Promise; +} + +declare var Clients: { + prototype: Clients; + new(): Clients; +}; + interface CloseEvent extends Event { readonly code: number; readonly reason: string; readonly wasClean: boolean; + /** @deprecated */ 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; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; }; interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + memory: any; + assert(condition?: boolean, message?: string, ...data: any[]): void; clear(): void; - count(countTitle?: string): void; + count(label?: string): void; debug(message?: any, ...optionalParams: any[]): void; dir(value?: any, ...optionalParams: any[]): void; dirxml(value: any): void; @@ -234,13 +317,17 @@ interface Console { groupEnd(): void; info(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: any): boolean; + markTimeline(label?: string): void; + msIsIndependentlyComposed(element: object): boolean; profile(reportName?: string): void; profileEnd(): void; - select(element: any): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; + select(element: object): void; + table(...tabularData: any[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeStamp(label?: string): void; + timeline(label?: string): void; + timelineEnd(label?: string): void; trace(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; } @@ -305,10 +392,10 @@ interface DOMException { 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 NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; readonly PARSE_ERR: number; readonly QUOTA_EXCEEDED_ERR: number; readonly SECURITY_ERR: number; @@ -337,10 +424,10 @@ declare var DOMException: { 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 NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; readonly PARSE_ERR: number; readonly QUOTA_EXCEEDED_ERR: number; readonly SECURITY_ERR: number; @@ -365,6 +452,25 @@ declare var DOMStringList: { new(): DOMStringList; }; +interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { + "message": MessageEvent; +} + +interface DedicatedWorkerGlobalScope extends WorkerGlobalScope { + onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; + close(): void; + postMessage(message: any, transfer?: any[]): 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: { + prototype: DedicatedWorkerGlobalScope; + new(): DedicatedWorkerGlobalScope; +}; + interface ErrorEvent extends Event { readonly colno: number; readonly error: any; @@ -376,31 +482,32 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; - new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; + new(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; }; interface Event { readonly bubbles: boolean; - readonly cancelable: boolean; cancelBubble: boolean; - readonly currentTarget: EventTarget; + readonly cancelable: boolean; + readonly currentTarget: EventTarget | null; readonly defaultPrevented: boolean; readonly eventPhase: number; readonly isTrusted: boolean; returnValue: boolean; - readonly srcElement: any; - readonly target: EventTarget; + readonly scoped: boolean; + readonly srcElement: object | null; + readonly target: EventTarget | null; readonly timeStamp: number; readonly type: string; - readonly scoped: boolean; - initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; + deepPath(): EventTarget[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; preventDefault(): void; stopImmediatePropagation(): void; stopPropagation(): void; - deepPath(): EventTarget[]; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; + readonly NONE: number; } declare var Event: { @@ -409,12 +516,17 @@ declare var Event: { readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; + readonly NONE: number; }; +interface EventListenerObject { + handleEvent(evt: Event): void; +} + interface EventTarget { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; dispatchEvent(evt: Event): boolean; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; } declare var EventTarget: { @@ -422,11 +534,47 @@ declare var EventTarget: { new(): EventTarget; }; +interface ExtendableEvent extends Event { + waitUntil(f: Promise): void; +} + +declare var ExtendableEvent: { + prototype: ExtendableEvent; + new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent; +}; + +interface ExtendableMessageEvent extends ExtendableEvent { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: ReadonlyArray | null; + readonly source: Client | ServiceWorker | MessagePort | null; +} + +declare var ExtendableMessageEvent: { + prototype: ExtendableMessageEvent; + new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent; +}; + +interface FetchEvent extends ExtendableEvent { + readonly clientId: string; + readonly request: Request; + readonly reservedClientId: string; + readonly targetClientId: string; + respondWith(r: Promise): void; +} + +declare var FetchEvent: { + prototype: FetchEvent; + new(type: string, eventInitDict: FetchEventInit): FetchEvent; +}; + interface File extends Blob { + readonly lastModified: number; + /** @deprecated */ readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; - readonly lastModified: number; } declare var File: { @@ -436,7 +584,7 @@ declare var File: { interface FileList { readonly length: number; - item(index: number): File; + item(index: number): File | null; [index: number]: File; } @@ -445,36 +593,86 @@ declare var FileList: { new(): FileList; }; -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: any; + abort(): void; 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; + readAsText(blob: Blob, label?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[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: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; +}; + +interface FileReaderSync { + readAsArrayBuffer(blob: Blob): any; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): string; + readAsText(blob: Blob, encoding?: string): string; +} + +declare var FileReaderSync: { + prototype: FileReaderSync; + new(): FileReaderSync; }; 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(): FormData; + new(form: object): FormData; }; +interface GlobalFetch { + fetch(input?: Request | string, init?: RequestInit): Promise; +} + interface Headers { append(name: string, value: string): void; delete(name: string): void; - forEach(callback: ForEachCallback): void; + forEach(callback: Function, thisArg?: any): void; get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; @@ -485,13 +683,16 @@ declare var Headers: { new(init?: HeadersInit): Headers; }; +interface IDBArrayKey extends Array { +} + interface IDBCursor { readonly direction: IDBCursorDirection; - key: IDBKeyRange | IDBValidKey; + readonly key: IDBKeyRange | number | string | Date | IDBArrayKey; readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; + readonly source: IDBObjectStore | IDBIndex; advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; + continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void; delete(): IDBRequest; update(value: any): IDBRequest; readonly NEXT: string; @@ -526,16 +727,14 @@ interface IDBDatabaseEventMap { 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; + onabort: ((this: IDBDatabase, ev: Event) => any) | null; + onerror: ((this: IDBDatabase, ev: Event) => any) | null; + onversionchange: ((this: IDBDatabase, ev: Event) => any) | null; + readonly version: number; 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; @@ -559,16 +758,16 @@ declare var IDBFactory: { }; interface IDBIndex { - keyPath: string | string[]; + readonly keyPath: string | string[]; + multiEntry: boolean; 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; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -593,21 +792,21 @@ declare var IDBKeyRange: { }; interface IDBObjectStore { + autoIncrement: boolean; readonly indexNames: DOMStringList; - keyPath: string | string[]; + readonly keyPath: string | string[] | null; readonly name: string; readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): 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; + openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest; } declare var IDBObjectStore: { @@ -621,8 +820,8 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { } interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: IDBOpenDBRequest, ev: Event) => any; - onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; + onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; 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; @@ -641,11 +840,11 @@ interface IDBRequestEventMap { interface IDBRequest extends EventTarget { readonly error: DOMException; - onerror: (this: IDBRequest, ev: Event) => any; - onsuccess: (this: IDBRequest, ev: Event) => any; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; readonly readyState: IDBRequestReadyState; readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; + readonly 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; @@ -668,9 +867,9 @@ 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; + onabort: ((this: IDBTransaction, ev: Event) => any) | null; + oncomplete: ((this: IDBTransaction, ev: Event) => any) | null; + onerror: ((this: IDBTransaction, ev: Event) => any) | null; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -700,8 +899,23 @@ declare var IDBVersionChangeEvent: { new(): IDBVersionChangeEvent; }; +interface ImageBitmap { + readonly height: number; + readonly width: number; + close(): void; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: "none" | "default"; + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; + resizeWidth?: number; +} + interface ImageData { - data: Uint8ClampedArray; + readonly data: Uint8ClampedArray; readonly height: number; readonly width: number; } @@ -725,9 +939,9 @@ declare var MessageChannel: { interface MessageEvent extends Event { readonly data: any; readonly origin: string; - readonly ports: any; - readonly source: any; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: any): void; + readonly ports: ReadonlyArray; + readonly source: object | null; + initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: object): void; } declare var MessageEvent: { @@ -740,7 +954,7 @@ interface MessagePortEventMap { } interface MessagePort extends EventTarget { - onmessage: (this: MessagePort, ev: MessageEvent) => any; + onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; @@ -755,6 +969,30 @@ declare var MessagePort: { new(): MessagePort; }; +interface NavigatorBeacon { + sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +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 NotificationEventMap { "click": Event; "close": Event; @@ -763,16 +1001,17 @@ interface NotificationEventMap { } interface Notification extends EventTarget { - readonly body: string; + readonly body: string | null; + readonly data: any; 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 icon: string | null; + readonly lang: string | null; + onclick: ((this: Notification, ev: Event) => any) | null; + onclose: ((this: Notification, ev: Event) => any) | null; + onerror: ((this: Notification, ev: Event) => any) | null; + onshow: ((this: Notification, ev: Event) => any) | null; readonly permission: NotificationPermission; - readonly tag: string; + readonly tag: string | null; readonly title: string; close(): void; addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -787,16 +1026,31 @@ declare var Notification: { requestPermission(callback?: NotificationPermissionCallback): Promise; }; +interface NotificationEvent extends ExtendableEvent { + readonly action: string; + readonly notification: Notification; +} + +declare var NotificationEvent: { + prototype: NotificationEvent; + new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; +}; + interface Performance { + /** @deprecated */ readonly navigation: PerformanceNavigation; + readonly timeOrigin: number; + /** @deprecated */ 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; + getEntriesByName(name: string, type?: string): any; + getEntriesByType(type: string): any; + /** @deprecated */ getMarks(markName?: string): any; + /** @deprecated */ getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; @@ -832,13 +1086,13 @@ declare var PerformanceNavigation: { 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 domainLookupEnd: number; + readonly domainLookupStart: number; readonly fetchStart: number; readonly loadEventEnd: number; readonly loadEventStart: number; @@ -849,9 +1103,9 @@ interface PerformanceTiming { readonly requestStart: number; readonly responseEnd: number; readonly responseStart: number; + readonly secureConnectionStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; - readonly secureConnectionStart: number; toJSON(): any; } @@ -896,10 +1150,20 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; + new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent; +}; + +interface PushEvent extends ExtendableEvent { + readonly data: PushMessageData | null; +} + +declare var PushEvent: { + prototype: PushEvent; + new(type: string, eventInitDict?: PushEventInit): PushEvent; }; interface PushManager { + readonly supportedContentEncodings: ReadonlyArray; getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; subscribe(options?: PushSubscriptionOptionsInit): Promise; @@ -910,8 +1174,21 @@ declare var PushManager: { new(): PushManager; }; +interface PushMessageData { + arrayBuffer(): ArrayBuffer; + blob(): Blob; + json(): any; + text(): string; +} + +declare var PushMessageData: { + prototype: PushMessageData; + new(): PushMessageData; +}; + interface PushSubscription { - readonly endpoint: USVString; + readonly endpoint: string; + readonly expirationTime: number | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): any; @@ -923,6 +1200,16 @@ declare var PushSubscription: { new(): PushSubscription; }; +interface PushSubscriptionChangeEvent extends ExtendableEvent { + readonly newSubscription: PushSubscription | null; + readonly oldSubscription: PushSubscription | null; +} + +declare var PushSubscriptionChangeEvent: { + prototype: PushSubscriptionChangeEvent; + new(type: string, eventInitDict?: PushSubscriptionChangeInit): PushSubscriptionChangeEvent; +}; + interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; readonly userVisibleOnly: boolean; @@ -955,7 +1242,7 @@ declare var ReadableStreamReader: { new(): ReadableStreamReader; }; -interface Request extends Object, Body { +interface Request extends Body { readonly cache: RequestCache; readonly credentials: RequestCredentials; readonly destination: RequestDestination; @@ -967,9 +1254,9 @@ interface Request extends Object, Body { readonly redirect: RequestRedirect; readonly referrer: string; readonly referrerPolicy: ReferrerPolicy; + readonly signal: object | null; readonly type: RequestType; readonly url: string; - readonly signal: AbortSignal; clone(): Request; } @@ -978,23 +1265,23 @@ declare var Request: { new(input: Request | string, init?: RequestInit): Request; }; -interface Response extends Object, Body { +interface Response extends Body { readonly body: ReadableStream | null; readonly headers: Headers; readonly ok: boolean; + readonly redirected: 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; + new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; }; interface ServiceWorkerEventMap extends AbstractWorkerEventMap { @@ -1002,8 +1289,8 @@ interface ServiceWorkerEventMap extends AbstractWorkerEventMap { } interface ServiceWorker extends EventTarget, AbstractWorker { - onstatechange: (this: ServiceWorker, ev: Event) => any; - readonly scriptURL: USVString; + onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; + readonly scriptURL: string; readonly state: ServiceWorkerState; postMessage(message: any, transfer?: any[]): void; addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -1017,6 +1304,44 @@ declare var ServiceWorker: { new(): ServiceWorker; }; +interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { + "activate": ExtendableEvent; + "fetch": FetchEvent; + "install": ExtendableEvent; + "message": ExtendableMessageEvent; + "messageerror": MessageEvent; + "notificationclick": NotificationEvent; + "notificationclose": NotificationEvent; + "push": PushEvent; + "pushsubscriptionchange": PushSubscriptionChangeEvent; + "sync": SyncEvent; +} + +interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + readonly clients: Clients; + onactivate: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null; + onfetch: ((this: ServiceWorkerGlobalScope, ev: FetchEvent) => any) | null; + oninstall: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null; + onmessage: ((this: ServiceWorkerGlobalScope, ev: ExtendableMessageEvent) => any) | null; + onmessageerror: ((this: ServiceWorkerGlobalScope, ev: MessageEvent) => any) | null; + onnotificationclick: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; + onnotificationclose: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; + onpush: ((this: ServiceWorkerGlobalScope, ev: PushEvent) => any) | null; + onpushsubscriptionchange: ((this: ServiceWorkerGlobalScope, ev: PushSubscriptionChangeEvent) => any) | null; + onsync: ((this: ServiceWorkerGlobalScope, ev: SyncEvent) => any) | null; + readonly registration: ServiceWorkerRegistration; + skipWaiting(): Promise; + 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: { + prototype: ServiceWorkerGlobalScope; + new(): ServiceWorkerGlobalScope; +}; + interface ServiceWorkerRegistrationEventMap { "updatefound": Event; } @@ -1024,9 +1349,9 @@ interface ServiceWorkerRegistrationEventMap { interface ServiceWorkerRegistration extends EventTarget { readonly active: ServiceWorker | null; readonly installing: ServiceWorker | null; - onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + onupdatefound: ((this: ServiceWorkerRegistration, ev: Event) => any) | null; readonly pushManager: PushManager; - readonly scope: USVString; + readonly scope: string; readonly sync: SyncManager; readonly waiting: ServiceWorker | null; getNotifications(filter?: GetNotificationOptions): Promise; @@ -1044,6 +1369,16 @@ declare var ServiceWorkerRegistration: { new(): ServiceWorkerRegistration; }; +interface SyncEvent extends ExtendableEvent { + readonly lastChance: boolean; + readonly tag: string; +} + +declare var SyncEvent: { + prototype: SyncEvent; + new(type: string, init: SyncEventInit): SyncEvent; +}; + interface SyncManager { getTags(): Promise; register(tag: string): Promise; @@ -1065,8 +1400,8 @@ interface URL { port: string; protocol: string; search: string; - username: string; readonly searchParams: URLSearchParams; + username: string; toString(): string; } @@ -1077,524 +1412,6 @@ declare var URL: { revokeObjectURL(url: string): void; }; -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: USVString | ArrayBuffer | Blob | ArrayBufferView): 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 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 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: any; - 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?: 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 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; -} - -interface GlobalFetch { - fetch(input: RequestInfo, init?: RequestInit): Promise; -} - -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 NavigatorBeacon { - sendBeacon(url: USVString, data?: BodyInit): boolean; -} - -interface NavigatorConcurrentHardware { - readonly hardwareConcurrency: number; -} - -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 WindowBase64 { - atob(encodedString: string): string; - btoa(rawString: string): string; -} - -interface WindowConsole { - readonly console: Console; -} - -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 Client { - readonly frameType: FrameType; - readonly id: string; - readonly url: USVString; - postMessage(message: any, transfer?: any[]): void; -} - -declare var Client: { - prototype: Client; - new(): Client; -}; - -interface Clients { - claim(): Promise; - get(id: string): Promise; - matchAll(options?: ClientQueryOptions): Promise; - openWindow(url: USVString): Promise; -} - -declare var Clients: { - prototype: Clients; - new(): Clients; -}; - -interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { - "message": MessageEvent; -} - -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, 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: { - prototype: DedicatedWorkerGlobalScope; - new(): DedicatedWorkerGlobalScope; -}; - -interface ExtendableEvent extends Event { - waitUntil(f: Promise): void; -} - -declare var ExtendableEvent: { - prototype: ExtendableEvent; - new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent; -}; - -interface ExtendableMessageEvent extends ExtendableEvent { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: MessagePort[] | null; - readonly source: Client | ServiceWorker | MessagePort | null; -} - -declare var ExtendableMessageEvent: { - prototype: ExtendableMessageEvent; - new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent; -}; - -interface FetchEvent extends ExtendableEvent { - readonly clientId: string | null; - readonly isReload: boolean; - readonly request: Request; - respondWith(r: Promise): void; -} - -declare var FetchEvent: { - prototype: FetchEvent; - new(type: string, eventInitDict: FetchEventInit): FetchEvent; -}; - -interface FileReaderSync { - readAsArrayBuffer(blob: Blob): any; - readAsBinaryString(blob: Blob): void; - readAsDataURL(blob: Blob): string; - readAsText(blob: Blob, encoding?: string): string; -} - -declare var FileReaderSync: { - prototype: FileReaderSync; - new(): FileReaderSync; -}; - -interface NotificationEvent extends ExtendableEvent { - readonly action: string; - readonly notification: Notification; -} - -declare var NotificationEvent: { - prototype: NotificationEvent; - new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; -}; - -interface PushEvent extends ExtendableEvent { - readonly data: PushMessageData | null; -} - -declare var PushEvent: { - prototype: PushEvent; - new(type: string, eventInitDict?: PushEventInit): PushEvent; -}; - -interface PushMessageData { - arrayBuffer(): ArrayBuffer; - blob(): Blob; - json(): JSON; - text(): USVString; -} - -declare var PushMessageData: { - prototype: PushMessageData; - new(): PushMessageData; -}; - -interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { - "activate": ExtendableEvent; - "fetch": FetchEvent; - "install": ExtendableEvent; - "message": ExtendableMessageEvent; - "notificationclick": NotificationEvent; - "notificationclose": NotificationEvent; - "push": PushEvent; - "pushsubscriptionchange": ExtendableEvent; - "sync": SyncEvent; -} - -interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - readonly clients: Clients; - onactivate: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any; - onfetch: (this: ServiceWorkerGlobalScope, ev: FetchEvent) => any; - oninstall: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any; - onmessage: (this: ServiceWorkerGlobalScope, ev: ExtendableMessageEvent) => any; - onnotificationclick: (this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any; - onnotificationclose: (this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any; - onpush: (this: ServiceWorkerGlobalScope, ev: PushEvent) => any; - onpushsubscriptionchange: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any; - onsync: (this: ServiceWorkerGlobalScope, ev: SyncEvent) => any; - readonly registration: ServiceWorkerRegistration; - skipWaiting(): Promise; - 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: { - prototype: ServiceWorkerGlobalScope; - new(): ServiceWorkerGlobalScope; -}; - -interface SyncEvent extends ExtendableEvent { - readonly lastChance: boolean; - readonly tag: string; -} - -declare var SyncEvent: { - prototype: SyncEvent; - new(type: string, init: SyncEventInit): SyncEvent; -}; - -interface WindowClient extends Client { - readonly focused: boolean; - readonly visibilityState: VisibilityState; - focus(): Promise; - navigate(url: USVString): Promise; -} - -declare var WindowClient: { - prototype: WindowClient; - new(): WindowClient; -}; - -interface WorkerGlobalScopeEventMap { - "error": ErrorEvent; -} - -interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, GlobalFetch { - readonly caches: CacheStorage; - readonly isSecureContext: boolean; - readonly location: WorkerLocation; - onerror: (this: WorkerGlobalScope, ev: ErrorEvent) => any; - readonly performance: Performance; - readonly self: WorkerGlobalScope; - 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, 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: { - prototype: WorkerGlobalScope; - new(): WorkerGlobalScope; -}; - -interface WorkerLocation { - readonly hash: string; - readonly host: string; - readonly hostname: string; - readonly href: string; - readonly origin: string; - readonly pathname: string; - readonly port: string; - readonly protocol: string; - readonly search: string; - toString(): string; -} - -declare var WorkerLocation: { - prototype: WorkerLocation; - new(): WorkerLocation; -}; - -interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware { - readonly hardwareConcurrency: number; -} - -declare var WorkerNavigator: { - prototype: WorkerNavigator; - new(): WorkerNavigator; -}; - -interface WorkerUtils extends Object, WindowBase64 { - readonly indexedDB: IDBFactory; - readonly msIndexedDB: IDBFactory; - readonly navigator: WorkerNavigator; - clearImmediate(handle: number): void; - clearInterval(handle: number): void; - clearTimeout(handle: number): void; - importScripts(...urls: string[]): void; - setImmediate(handler: (...args: any[]) => void): number; - setImmediate(handler: any, ...args: any[]): number; - 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 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 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. @@ -1624,289 +1441,284 @@ interface URLSearchParams { declare var URLSearchParams: { prototype: URLSearchParams; - /** - * Constructor returning a URLSearchParams object. - */ new (init?: string | URLSearchParams): URLSearchParams; }; -interface BlobPropertyBag { - type?: string; - endings?: string; +interface WebSocketEventMap { + "close": CloseEvent; + "error": Event; + "message": MessageEvent; + "open": Event; } -interface FilePropertyBag extends BlobPropertyBag { - lastModified?: number; -} - -interface EventListenerObject { - handleEvent(evt: Event): void; -} - -interface ProgressEventInit extends EventInit { - lengthComputable?: boolean; - loaded?: number; - total?: number; -} - -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 EventListenerOptions { - capture?: boolean; -} - -interface AddEventListenerOptions extends EventListenerOptions { - passive?: boolean; - 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 { +interface WebSocket extends EventTarget { + binaryType: BinaryType; + readonly bufferedAmount: number; + readonly extensions: string; + onclose: ((this: WebSocket, ev: CloseEvent) => any) | null; + onerror: ((this: WebSocket, ev: Event) => any) | null; + onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onopen: ((this: WebSocket, ev: Event) => any) | null; + readonly protocol: string; + readonly readyState: number; readonly url: string; - readonly withCredentials: boolean; + close(code?: number, reason?: string): void; + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; + readonly CLOSED: number; + readonly CLOSING: number; 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; + 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 EventSource: { - prototype: EventSource; - new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +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 EventSourceInit { - readonly withCredentials: boolean; +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; } +interface WindowClient extends Client { + readonly ancestorOrigins: ReadonlyArray; + readonly focused: boolean; + readonly visibilityState: VisibilityState; + focus(): Promise; + navigate(url: string): Promise; +} + +declare var WindowClient: { + prototype: WindowClient; + new(): WindowClient; +}; + +interface WindowConsole { + readonly console: Console; +} + +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** @deprecated */ + 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 WorkerGlobalScopeEventMap { + "error": ErrorEvent; +} + +interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, GlobalFetch { + readonly caches: CacheStorage; + readonly isSecureContext: boolean; + readonly location: WorkerLocation; + onerror: ((this: WorkerGlobalScope, ev: ErrorEvent) => any) | null; + readonly performance: Performance; + readonly self: WorkerGlobalScope; + createImageBitmap(image: ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; + createImageBitmap(image: ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; + msWriteProfilerMark(profilerMarkName: string): 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: { + prototype: WorkerGlobalScope; + new(): WorkerGlobalScope; +}; + +interface WorkerLocation { + readonly hash: string; + readonly host: string; + readonly hostname: string; + readonly href: string; + readonly origin: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + toString(): string; +} + +declare var WorkerLocation: { + prototype: WorkerLocation; + new(): WorkerLocation; +}; + +interface WorkerNavigator extends NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware { +} + +declare var WorkerNavigator: { + prototype: WorkerNavigator; + new(): WorkerNavigator; +}; + +interface WorkerUtils extends WindowBase64 { + readonly indexedDB: IDBFactory; + readonly msIndexedDB: IDBFactory; + readonly navigator: WorkerNavigator; + clearImmediate(handle: number): void; + clearInterval(handle: number): void; + clearTimeout(handle: number): void; + importScripts(...urls: string[]): void; + setImmediate(handler: any, ...args: any[]): number; + setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: any, timeout?: any, ...args: any[]): number; +} + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { + msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; + readonly readyState: number; + readonly response: any; + readonly responseText: string; + responseType: XMLHttpRequestResponseType; + readonly responseURL: string; + readonly responseXML: object | null; + readonly status: number; + readonly statusText: string; + timeout: number; + readonly upload: XMLHttpRequestUpload; + withCredentials: boolean; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string | null; + msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): void; + overrideMimeType(mime: 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 XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + +interface XMLHttpRequestEventTarget { + onabort: ((this: XMLHttpRequest, ev: Event) => any) | null; + onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null; + 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 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; +}; + 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; + (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void; } + interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, status: MediaKeyStatus): void; } + interface FunctionStringCallback { (data: string): void; } + interface NotificationPermissionCallback { (permission: NotificationPermission): void; } + interface PositionCallback { (position: Position): void; } + interface PositionErrorCallback { (error: PositionError): void; } -declare var onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any; + +declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; declare function close(): void; declare function postMessage(message: any, transfer?: any[]): void; +declare function dispatchEvent(evt: Event): boolean; declare var caches: CacheStorage; declare var isSecureContext: boolean; declare var location: WorkerLocation; -declare var onerror: (this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any; +declare var onerror: ((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null; declare var performance: Performance; declare var self: WorkerGlobalScope; -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 msWriteProfilerMark(profilerMarkName: string): void; declare function dispatchEvent(evt: Event): boolean; declare var indexedDB: IDBFactory; declare var msIndexedDB: IDBFactory; @@ -1915,33 +1727,50 @@ declare function clearImmediate(handle: number): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function importScripts(...urls: string[]): void; -declare function setImmediate(handler: (...args: any[]) => void): number; declare function setImmediate(handler: any, ...args: any[]): number; -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 atob(encodedString: string): string; 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 fetch(input?: Request | string, init?: RequestInit): Promise; 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 FormDataEntryValue = string | File; +type HeadersInit = Headers | string[][] | { [key: string]: string }; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = Blob | BufferSource | FormData | string; +type AAGUID = string; +type BodyInit = any; +type ByteString = string; +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 RequestInfo = Request | string; 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 payloadtype = number; +type ClientTypes = "window" | "worker" | "sharedworker" | "all"; +type BinaryType = "blob" | "arraybuffer"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; @@ -1957,6 +1786,4 @@ type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; -type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; -type ClientType = "window" | "worker" | "sharedworker" | "all"; -type FrameType = "auxiliary" | "top-level" | "nested" | "none"; \ No newline at end of file +type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; \ No newline at end of file diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 21691cd1e20..bd93858ddfd 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Obie metody dostępu muszą być abstrakcyjne lub nieabstrakcyjne.", "Add_0_to_existing_import_declaration_from_1_90015": "Dodaj element „{0}” do istniejącej deklaracji importu z elementu „{1}”", "Add_async_modifier_to_containing_function_90029": "Dodaj modyfikator asynchroniczny do funkcji zawierającej", + "Add_definite_assignment_assertion_to_property_0_95020": "Dodaj asercję określonego przypisania do właściwości „{0}”", "Add_index_signature_for_property_0_90017": "Dodaj sygnaturę indeksu dla właściwości „{0}”", + "Add_initializer_to_property_0_95019": "Dodaj inicjator do 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", + "Add_undefined_type_to_property_0_95018": "Dodaj typ „undefined” do właściwości „{0}”", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "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.", + "All_imports_in_import_declaration_are_unused_6192": "Wszystkie importy w deklaracji importu są nieużywane.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Zezwalaj na domyślne importy z modułów bez domyślnego eksportu. To nie wpływa na emitowanie kodu, a tylko na sprawdzanie typów.", "Allow_javascript_files_to_be_compiled_6102": "Zezwalaj na kompilowanie plików JavaScript.", "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”.", @@ -379,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Plik jest modułem CommonJS. Może zostać przekonwertowany na moduł ES6.", "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}”.", @@ -425,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "Import może zostać przekonwertowany na import domyślny.", "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.", @@ -463,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Tag JSDoc „@param” ma nazwę „{0}”, ale nie istnieje parametr o tej nazwie. Byłby on zgodny z elementem „arguments”, gdyby miał typ tablicy.", "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.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Typy JSDoc mogą być przenoszone do typów TypeScript.", "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.", @@ -477,6 +485,7 @@ "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_an_inline_JSX_factory_pragma_17017": "Fragment JSX nie jest obsługiwany podczas używania śródwierszowej dyrektywy pragma fabryki JSX", "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.", @@ -508,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "Moduł „{0}” nie ma wyeksportowanego elementu członkowskiego „{1}”. Czy chodziło o „{2}”?", "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 *”.", @@ -651,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Zgłaszaj błąd w przypadku wyrażeń „this” z niejawnym typem „any”.", "Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.", "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”", + "Remove_import_from_0_90005": "Usuń import z „{0}”", "Replace_import_with_0_95015": "Zamień import na element „{0}”.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.", @@ -658,7 +669,7 @@ "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.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Znaleziono rozwiązanie dla modułu „{0}” w pamięci podręcznej z lokalizacji „{1}”.", "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}”.", @@ -792,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Ta funkcja konstruktora może zostać przekonwertowana na deklarację klasy.", "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.", @@ -888,6 +900,7 @@ "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.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Określa, czy zachować nieaktualne dane wyjściowe konsoli w trybie śledzenia zamiast wyczyścić ekran.", "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}()”?", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 12fcad54070..b0812b95319 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -23,10 +23,12 @@ declare namespace ts.server.protocol { GeterrForProject = "geterrForProject", SemanticDiagnosticsSync = "semanticDiagnosticsSync", SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", NavBar = "navbar", Navto = "navto", NavTree = "navtree", NavTreeFull = "navtree-full", + /** @deprecated */ Occurrences = "occurrences", DocumentHighlights = "documentHighlights", Open = "open", @@ -44,6 +46,7 @@ declare namespace ts.server.protocol { OpenExternalProject = "openExternalProject", OpenExternalProjects = "openExternalProjects", CloseExternalProject = "closeExternalProject", + GetOutliningSpans = "getOutliningSpans", TodoComments = "todoComments", Indentation = "indentation", DocCommentTemplate = "docCommentTemplate", @@ -202,6 +205,31 @@ declare namespace ts.server.protocol { */ onlyMultiLine: boolean; } + /** + * Request to obtain outlining spans in file. + */ + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.GetOutliningSpans; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + } + /** + * Response to OutliningSpansRequest request. + */ + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } /** * A request to get indentation for a location in file */ @@ -627,6 +655,7 @@ declare namespace ts.server.protocol { openingBrace: string; } /** + * @deprecated * Get occurrences request; value of command field is * "occurrences". Return response giving spans that are relevant * in the file at a given line and column. @@ -634,6 +663,7 @@ declare namespace ts.server.protocol { interface OccurrencesRequest extends FileLocationRequest { command: CommandTypes.Occurrences; } + /** @deprecated */ interface OccurrencesResponseItem extends FileSpan { /** * True if the occurrence is a write location, false otherwise. @@ -644,6 +674,7 @@ declare namespace ts.server.protocol { */ isInString?: true; } + /** @deprecated */ interface OccurrencesResponse extends Response { body?: OccurrencesResponseItem[]; } @@ -906,6 +937,7 @@ declare namespace ts.server.protocol { * The format options to use during formatting and other code editing features. */ formatOptions?: FormatCodeSettings; + preferences?: UserPreferences; /** * The host's additional supported .js file extensions */ @@ -1240,6 +1272,8 @@ declare namespace ts.server.protocol { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; } /** * Format and format on key response message. @@ -1278,15 +1312,13 @@ declare namespace ts.server.protocol { */ 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.`. + * @deprecated Use UserPreferences.includeCompletionsForModuleExports */ - includeExternalModuleExports: boolean; + 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"]`. + * @deprecated Use UserPreferences.includeCompletionsWithInsertText */ - includeInsertTextCompletions: boolean; + includeInsertTextCompletions?: boolean; } /** * Completions request; value of command field is "completions". @@ -1541,6 +1573,12 @@ declare namespace ts.server.protocol { interface SemanticDiagnosticsSyncResponse extends Response { body?: Diagnostic[] | DiagnosticWithLinePosition[]; } + interface SuggestionDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SuggestionDiagnosticsSync; + arguments: SuggestionDiagnosticsSyncRequestArgs; + } + type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; + type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; /** * Synchronous request for syntactic diagnostics of one file. */ @@ -1637,7 +1675,7 @@ declare namespace ts.server.protocol { */ text: string; /** - * The category of the diagnostic message, e.g. "error" vs. "warning" + * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". */ category: string; /** @@ -1665,8 +1703,9 @@ declare namespace ts.server.protocol { */ diagnostics: Diagnostic[]; } + type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; /** - * Event message for "syntaxDiag" and "semanticDiag" event types. + * Event message for DiagnosticEventKind event types. * These events provide syntactic and semantic errors for a file. */ interface DiagnosticEvent extends Event { @@ -2036,6 +2075,20 @@ declare namespace ts.server.protocol { placeOpenBraceOnNewLineForControlBlocks?: boolean; insertSpaceBeforeTypeAnnotation?: boolean; } + interface UserPreferences { + readonly quotePreference?: "double" | "single"; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + readonly includeCompletionsForModuleExports?: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + } interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -2162,7 +2215,7 @@ declare namespace ts.server.protocol { none = "none", definition = "definition", reference = "reference", - writtenReference = "writtenReference", + writtenReference = "writtenReference" } enum ScriptElementKind { @@ -2230,7 +2283,7 @@ declare namespace ts.server.protocol { /** * */ - jsxAttribute = "JSX attribute", + jsxAttribute = "JSX attribute" } interface TypeAcquisition { diff --git a/lib/pt-BR/diagnosticMessages.generated.json b/lib/pt-BR/diagnosticMessages.generated.json index c2770a52b40..ea360393853 100644 --- a/lib/pt-BR/diagnosticMessages.generated.json +++ b/lib/pt-BR/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Acessadores devem ser abstratos ou não abstratos.", "Add_0_to_existing_import_declaration_from_1_90015": "Adicionar '{0}' à declaração de importação existente de \"{1}\"", "Add_async_modifier_to_containing_function_90029": "Adicione o modificador assíncrono que contém a função", + "Add_definite_assignment_assertion_to_property_0_95020": "Adicionar a asserção de atribuição definitiva à propriedade '{0}'", "Add_index_signature_for_property_0_90017": "Adicionar assinatura de índice para a propriedade '{0}'", + "Add_initializer_to_property_0_95019": "Adicionar inicializador à propriedade '{0}'", "Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente", "Add_this_to_unresolved_variable_90008": "Adicionar 'this.' a uma variável não resolvida", + "Add_undefined_type_to_property_0_95018": "Adicionar tipo 'indefinido' à propriedade '{0}'", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Adicionar um arquivo tsconfig.json ajudará 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.", + "All_imports_in_import_declaration_are_unused_6192": "Nenhuma das importações na declaração de importação está sendo utilizada.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permita importações padrão de módulos sem exportação padrão. Isso não afeta a emissão do código, apenas a verificação de digitação.", "Allow_javascript_files_to_be_compiled_6102": "Permita que arquivos javascript sejam compilados.", "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.", @@ -324,6 +328,7 @@ "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": "A enumeração '{0}' usada antes de sua declaração.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações de enum apenas podem se mescladas com namespaces ou com outras declarações de enum.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações de enumeração devem ser const ou não const.", "Enum_member_expected_1132": "Membro de enumeração esperado.", "Enum_member_must_have_initializer_1061": "O membro de enumeração deve ter um inicializador.", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "O arquivo é um módulo CommonJS; ele pode ser convertido em um módulo ES6.", "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}'.", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "A importação pode ser convertida em uma importação padrão.", "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.", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "A marca '@param' do JSDoc tem o nome '{0}', mas não há nenhum parâmetro com esse nome. Ela corresponderia a 'argumentos' se tivesse um tipo de matriz.", "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.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Tipos JSDoc podem ser movidos para tipos TypeScript.", "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.", @@ -476,6 +485,7 @@ "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_an_inline_JSX_factory_pragma_17017": "O fragmento de JSX não é compatível ao se utilizar um pragma de fábrica JSX embutido", "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.", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro exportado '{1}'. Você quis dizer '{2}'?", "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 *'.", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Gerar erro em expressões 'this' com um tipo 'any' implícito.", "Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.", "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", + "Remove_import_from_0_90005": "Remover importação do '{0}'", "Replace_import_with_0_95015": "Substitua a importação com '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Relate erro quando nem todos os caminhos de código na função retornarem um valor.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Relate erros para casos de fallthrough na instrução switch.", @@ -657,7 +669,7 @@ "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.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "A resolução para o módulo '{0}' foi encontrada no cache do local '{1}'.", "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}'.", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta função de construtor pode ser convertida em uma declaração de classe.", "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.", @@ -887,6 +900,7 @@ "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.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se se deve manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", "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}()'?", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index aee384f8f7d..9f653368ee5 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Методы доступа должны быть абстрактными или неабстрактными.", "Add_0_to_existing_import_declaration_from_1_90015": "Добавьте \"{0}\" в существующее объявление импорта из \"{1}\"", "Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию", + "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного присваивания к свойству \"{0}\"", "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"", + "Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"", "Add_missing_super_call_90001": "Добавьте отсутствующий вызов \"super()\"", "Add_this_to_unresolved_variable_90008": "Добавьте \"this.\" к неразрешенной переменной", + "Add_undefined_type_to_property_0_95018": "Добавить тип \"undefined\" к свойству \"{0}\"", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Добавление файла tsconfig.json поможет организовать проекты, содержащие файлы TypeScript и JavaScript. Дополнительные сведения: https://aka.ms/tsconfig.", "Additional_Checks_6176": "Дополнительные проверки", "Advanced_Options_6178": "Дополнительные параметры", "All_declarations_of_0_must_have_identical_modifiers_2687": "Все объявления \"{0}\" должны иметь одинаковые модификаторы.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Все объявления \"{0}\" должны иметь одинаковые параметры типа.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Все объявления абстрактных методов должны быть последовательными.", + "All_imports_in_import_declaration_are_unused_6192": "Ни один из импортов в объявлении импорта не используется.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Разрешить импорт по умолчанию из модулей без экспорта по умолчанию. Это не повлияет на выведение кода — только на проверку типов.", "Allow_javascript_files_to_be_compiled_6102": "Разрешить компиляцию файлов javascript.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Перечисление внешних констант не разрешено, если задан флаг \"--isolatedModules\".", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Объявления перечислений можно объединять только с пространствами имен или другими объявлениями перечислений.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Все объявления перечислений должны иметь значение const или отличное от const.", "Enum_member_expected_1132": "Ожидался элемент перечисления.", "Enum_member_must_have_initializer_1061": "У элемента перечисления должен быть инициализатор.", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Файл является модулем CommonJS; его можно преобразовать в модуль ES6.", "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}\".", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "Импорт можно преобразовать в импорт по умолчанию.", "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": "Операции импорта запрещены в улучшениях модуля. Попробуйте переместить их в содержащий внешний модуль.", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Тег \"@param\" JSDoc имеет имя \"{0}\", но параметра с таким именем не существует. Он совпадал бы с \"arguments\", если бы у него был указан тип массива.", "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 можно использовать только в комментариях в документации.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Типы JSDoc могут быть преобразованы в типы TypeScript.", "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}\" не содержит соответствующий закрывающий тег.", @@ -476,6 +485,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Элементы JSX не могут иметь несколько атрибутов с одним именем.", "JSX_expressions_must_have_one_parent_element_2657": "Выражения JSX должны иметь один родительский элемент.", "JSX_fragment_has_no_corresponding_closing_tag_17014": "Фрагмент JSX не имеет соответствующего закрывающего тега.", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "Фрагмент JSX не поддерживается при использовании встроенной директивы pragma фабрики 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": "Целевой объект перехода не может находиться за границей функции.", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "В модуле \"{0}\" нет экспортированного элемента \"{1}\". Вы имели в виду \"{2}\"?", "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 *\".", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Вызвать ошибку в выражениях this с неявным типом any.", "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\"", + "Remove_import_from_0_90005": "Удалить импорт из \"{0}\"", "Replace_import_with_0_95015": "Замена импорта на \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.", @@ -657,7 +669,7 @@ "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}\" найдено в кэше.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Разрешение для модуля \"{0}\" найдено в кэше из расположения \"{1}\".", "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}\".", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Эту функцию конструктора можно преобразовать в объявление класса.", "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": "Завершающая запятая запрещена.", @@ -887,6 +900,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "Список объявлений переменной не может быть пустым.", "Version_0_6029": "Версия {0}", "Watch_input_files_6005": "Просмотр входных файлов.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Сохранять ли устаревшие выходные данные консоли в режиме просмотра вместо очистки экрана.", "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}()\"?", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index cc088011fa5..14b0bb7d3ed 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "İki erişimci de soyut veya soyut olmayan olmalıdır.", "Add_0_to_existing_import_declaration_from_1_90015": "'{0}' öğesini \"{1}\" konumundaki mevcut içeri aktarma bildirimine ekle", "Add_async_modifier_to_containing_function_90029": "İçeren işleve zaman uyumsuz değiştirici ekle", + "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' özelliğine belirli atama onayı ekle", "Add_index_signature_for_property_0_90017": "'{0}' özelliği için dizin imzası ekle", + "Add_initializer_to_property_0_95019": "'{0}' özelliğine başlatıcı ekle", "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", "Add_this_to_unresolved_variable_90008": "Çözümlenmemiş değişkene 'this.' ekle", + "Add_undefined_type_to_property_0_95018": "'{0}' özelliğine 'undefined' türünü ekle", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "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.", + "All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", "Allow_javascript_files_to_be_compiled_6102": "Javascript dosyalarının derlenmesine izin ver.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' bayrağı sağlandığında çevresel const sabit listesi değerlerine izin verilmez.", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enum bildirimleri yalnızca ad alanı veya diğer enum bildirimleri ile birleştirilebilir.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Sabit listesi bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", "Enum_member_expected_1132": "Sabit listesi üyesi bekleniyor.", "Enum_member_must_have_initializer_1061": "Sabit listesi üyesi bir başlatıcıya sahip olmalıdır.", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Bir CommonJS modülü olan dosya, ES6 modülüne dönüştürülebilir.", "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}'.", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "İçeri aktarma varsayılan bir içeri aktarmaya dönüştürülebilir.", "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.", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' etiketi '{0}' adına sahip ancak bu ada sahip bir parametre yok. Bir dizi türü olsaydı 'arguments' ile eşleşirdi.", "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.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc türleri TypeScript türlerine taşınabilir.", "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.", @@ -476,6 +485,7 @@ "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_an_inline_JSX_factory_pragma_17017": "Satır içi JSX fabrika pragma'sı kullanılırken JSX parçası desteklenmez", "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.", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "'{0}' modülünün dışa aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", "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.", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Örtük olarak 'any' türü içeren 'this' ifadelerinde hata tetikle.", "Redirect_output_structure_to_the_directory_6006": "Çıktı yapısını dizine yeniden yönlendir.", "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", + "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", "Replace_import_with_0_95015": "İçeri aktarma işlemini '{0}' ile değiştirin.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "İşlevdeki tüm kod yolları bir değer döndürmediğinde hata bildir.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch deyiminde sonraki ifadelere geçiş ile ilgili hataları bildir.", @@ -657,7 +669,7 @@ "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.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' modülünün çözümü '{1}' konumundaki ö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.", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "Bu oluşturucu işlevi bir sınıf bildirimine dönüştürülebilir.", "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.", @@ -887,6 +900,7 @@ "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.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Eski konsol çıktısının ekrandan kaldırılmak yerine izleme modunda tutulup tutulmayacağı.", "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?", diff --git a/lib/tsc.js b/lib/tsc.js index b5c5051820e..042118cead7 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -54,8 +54,15 @@ var ts; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; - DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; @@ -71,6 +78,37 @@ var ts; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + function _contextuallyTypePragmas(args) { + return args; + } + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 + }, + "ts-check": { + kind: 2 + }, + "ts-nocheck": { + kind: 2 + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 + }, + }); })(ts || (ts = {})); var ts; (function (ts) { @@ -131,7 +169,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.8"; + ts.versionMajorMinor = "2.9"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { @@ -146,6 +184,10 @@ var ts; })(ts || (ts = {})); (function (ts) { ts.emptyArray = []; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -648,18 +690,6 @@ var ts; }; } ts.singleIterator = singleIterator; - function span(array, f) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (!f(array[i], i)) { - return [array.slice(0, i), array.slice(i)]; - } - } - return [array.slice(0), []]; - } - return undefined; - } - ts.span = span; function spanMap(array, keyfn, mapfn) { var result; if (array) { @@ -998,7 +1028,7 @@ var ts; } ts.elementAt = elementAt; function firstOrUndefined(array) { - return elementAt(array, 0); + return array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -1007,7 +1037,7 @@ var ts; } ts.first = first; function lastOrUndefined(array) { - return elementAt(array, -1); + return array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -1190,19 +1220,21 @@ var ts; } ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } var result = createMap(); 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); + result.set(makeKey(value), makeValue(value)); } return result; } ts.arrayToMap = arrayToMap; function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } 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; + result[makeKey(value)] = makeValue(value); } return result; } @@ -1211,6 +1243,20 @@ var ts; return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } ts.arrayToSet = arrayToSet; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -1268,15 +1314,6 @@ var ts; } } } - function group(values, getGroupId) { - var groupIdToGroup = createMultiMap(); - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - groupIdToGroup.add(getGroupId(value), value); - } - return arrayFrom(groupIdToGroup.values()); - } - ts.group = group; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -1384,7 +1421,6 @@ var ts; return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.formatStringFromArgs = formatStringFromArgs; - ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } @@ -1726,6 +1762,10 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAreDeclarationMapsEnabled(options) { + return !!(options.declaration && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined @@ -2086,7 +2126,6 @@ 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); }); @@ -2117,7 +2156,7 @@ var ts; } } }; - for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + for (var _i = 0, _b = sort(files, compareStringsCaseSensitive); _i < _b.length; _i++) { var current = _b[_i]; _loop_1(current); } @@ -2127,7 +2166,7 @@ var ts; return; } } - for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -2150,7 +2189,7 @@ var ts; } includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -2493,7 +2532,7 @@ var ts; } ts.matchedText = matchedText; function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; + var matchedValue; var longestMatchPrefixLength = -1; for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { var v = values_2[_i]; @@ -2575,6 +2614,38 @@ var ts; return t === undefined ? undefined : [t]; } ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(ts || (ts = {})); var ts; (function (ts) { @@ -2590,6 +2661,269 @@ var ts; FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + function getPriorityValues(highPriorityValue) { + var mediumPriorityValue = highPriorityValue * 2; + var lowPriorityValue = mediumPriorityValue * 4; + return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; + } + function pollingInterval(watchPriority) { + return pollingIntervalsForPriority[watchPriority]; + } + var pollingIntervalsForPriority = getPriorityValues(250); + function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { + return host.watchFile(fileName, callback, pollingInterval(watchPriority)); + } + ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; + ts.missingFileModifiedTime = new Date(0); + function createPollingIntervalBasedLevels(levels) { + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + var _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + pollQueue(changedFilesInLastPoll, PollingInterval.Low, 0, changedFilesInLastPoll.length); + pollPollingIntervalQueue(queue); + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + var eventKind = oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + watchedFile.callback(watchedFile.fileName, eventKind); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + function createRecursiveDirectoryWatcher(host) { + return createDirectoryWatcher; + function createDirectoryWatcher(dirName, callback) { + var watcher = host.watchDirectory(dirName, function (fileName) { + callback(fileName); + updateChildWatches(result, callback); + }); + var result = { + close: function () { + watcher.close(); + result.childWatches.forEach(ts.closeFileWatcher); + result = undefined; + }, + dirName: dirName, + childWatches: ts.emptyArray + }; + updateChildWatches(result, callback); + return result; + } + function updateChildWatches(watcher, callback) { + if (watcher) { + watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + } + } + function watchChildDirectories(parentDir, existingChildWatches, callback) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(ts.getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(ts.getNormalizedAbsolutePath(childName, parentDir), callback); + addChildDirectoryWatcher(result); + } + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -2618,75 +2952,104 @@ var ts; catch (_a) { _crypto = undefined; } - var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } - function createMD5HashUsingNativeCrypto(data) { - var hash = _crypto.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - } - function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - var fileWatcherCallbacks = ts.createMultiMap(); - return { addFile: addFile, removeFile: removeFile }; - function reduceDirWatcherRefCountForFile(fileName) { - var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers.get(dirName); - if (watcher) { - watcher.referenceCount -= 1; - if (watcher.referenceCount <= 0) { - watcher.close(); - dirWatchers.delete(dirName); - } - } - } - function addDirWatcher(dirPath) { - var watcher = dirWatchers.get(dirPath); - if (watcher) { - watcher.referenceCount += 1; - return; - } - watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); - watcher.referenceCount = 1; - dirWatchers.set(dirPath, watcher); - return; - } - function addFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.add(filePath, callback); - } - function addFile(fileName, callback) { - addFileWatcherCallback(fileName, callback); - addDirWatcher(ts.getDirectoryPath(fileName)); - return { fileName: fileName, callback: callback }; - } - function removeFile(watchedFile) { - removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback); - reduceDirWatcherRefCountForFile(watchedFile.fileName); - } - function removeFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.remove(filePath, callback); - } - function fileEventHandler(eventName, relativeFileName, baseDirPath) { - var fileName = !ts.isString(relativeFileName) - ? undefined - : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename")) { - var callbacks = fileWatcherCallbacks.get(fileName); - if (callbacks) { - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); - } - } - } - } - } - var watchedFileSet = createWatchedFileSet(); + var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (_a) { } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: function (path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + base64decode: Buffer.from ? function (input) { + return Buffer.from(input, "base64").toString("utf8"); + } : function (input) { + return new Buffer(input, "base64").toString("utf8"); + }, + base64encode: Buffer.from ? function (input) { + return Buffer.from(input).toString("base64"); + } : function (input) { + return new Buffer(input).toString("base64"); + } + }; + return nodeSystem; function isFileSystemCaseSensitive() { if (platform === "win32" || platform === "win64") { return false; @@ -2699,40 +3062,154 @@ var ts; return ch === up ? ch.toLowerCase() : up; }); } - var platform = _os.platform(); - var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + return fsWatchFile; + case "DynamicPriorityPolling": + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + filePathComparer: useCaseSensitiveFileNames ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive, + directoryExists: directoryExists, + getAccessileSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + var fileName = !ts.isString(relativeFileName) + ? undefined + : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } function fsWatchFile(fileName, callback, pollingInterval) { _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; 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) { + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + else if (+curr.mtime === +prev.mtime) { return; } + else { + eventKind = FileWatcherEventKind.Changed; + } callback(fileName, eventKind); } } - function fsWatchDirectory(directoryName, callback, recursive) { + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + if (eventName === "rename") { + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { var options; - var watcher = !directoryExists(directoryName) ? - watchMissingDirectory() : - watchPresentDirectory(); + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); return { close: function () { watcher.close(); + watcher = undefined; } }; - function watchPresentDirectory() { + function invokeCallbackAndUpdateWatcher(createWatcher) { + callback("rename", ""); + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + function watchPresentFileSystemEntry() { if (options === undefined) { if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; @@ -2741,24 +3218,40 @@ var ts; options = { persistent: true }; } } - var dirWatcher = _fs.watch(directoryName, options, callback); - dirWatcher.on("error", function () { - if (!directoryExists(directoryName)) { - watcher = watchMissingDirectory(); - callback("rename", ""); - } - }); - return dirWatcher; + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + return watchPresentFileSystemEntryWithFsWatchFile(); + } } - function watchMissingDirectory() { - return fsWatchFile(directoryName, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { - watcher.close(); - watcher = watchPresentDirectory(); - callback("rename", ""); - } - }); + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); } + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { @@ -2853,103 +3346,23 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - var nodeSystem = { - clearScreen: function () { - process.stdout.write("\x1Bc"); - }, - args: process.argv.slice(2), - newLine: _os.EOL, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - write: function (s) { - process.stdout.write(s); - }, - readFile: readFile, - writeFile: writeFile, - watchFile: function (fileName, callback, pollingInterval) { - if (useNonPollingWatchers) { - var watchedFile_1 = watchedFileSet.addFile(fileName, callback); - return { - close: function () { return watchedFileSet.removeFile(watchedFile_1); } - }; - } - else { - return fsWatchFile(fileName, callback, pollingInterval); - } - }, - watchDirectory: function (directoryName, callback, recursive) { - 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, - directoryExists: directoryExists, - createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { - _fs.mkdirSync(directoryName); - } - }, - getExecutingFilePath: function () { - return __filename; - }, - getCurrentDirectory: function () { - return process.cwd(); - }, - getDirectories: getDirectories, - getEnvironmentVariable: function (name) { - return process.env[name] || ""; - }, - readDirectory: readDirectory, - getModifiedTime: function (path) { - try { - return _fs.statSync(path).mtime; - } - catch (e) { - return undefined; - } - }, - createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, - getMemoryUsage: function () { - if (global.gc) { - global.gc(); - } - return process.memoryUsage().heapUsed; - }, - getFileSize: function (path) { - try { - var stat = _fs.statSync(path); - if (stat.isFile()) { - return stat.size; - } - } - catch (_a) { } - return 0; - }, - exit: function (exitCode) { - process.exit(exitCode); - }, - realpath: function (path) { - try { - return _fs.realpathSync(path); - } - catch (_a) { - return path; - } - }, - debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), - tryEnableSourceMapsForHost: function () { - try { - require("source-map-support").install(); - } - catch (_a) { - } - }, - setTimeout: setTimeout, - clearTimeout: clearTimeout - }; - return nodeSystem; + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -3013,6 +3426,7 @@ var ts; return sys; })(); if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) ? 1 : 0; @@ -3606,6 +4020,7 @@ var ts; Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), 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}'."), @@ -3677,7 +4092,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), 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."), @@ -3717,6 +4132,8 @@ var ts; 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."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), 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."), @@ -3850,7 +4267,7 @@ var ts; Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), - Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), @@ -3894,6 +4311,8 @@ var ts; Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused."), 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."), @@ -3953,6 +4372,7 @@ var ts; 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."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), 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."), @@ -3973,14 +4393,20 @@ var ts; 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"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), 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}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), 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}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{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"), @@ -4017,6 +4443,33 @@ var ts; Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_this_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_this_to_all_unresolved_variables_matching_a_member_name_95037", "Add 'this.' to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), }; })(ts || (ts = {})); var ts; @@ -5623,6 +6076,13 @@ var ts; return token = 26; case 46: return token = 23; + case 96: + while (pos < end && text.charCodeAt(pos) !== 96) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 13; } if (isIdentifierStart(ch, 6)) { while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { @@ -5918,9 +6378,9 @@ var ts; return false; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; - function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 && + text.charCodeAt(start + 2) === 33; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { @@ -5948,18 +6408,15 @@ var ts; ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } - if (nodeIsMissing(node)) { - return ""; - } - var text = sourceFile.text; - return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; - function getTextOfNodeFromSourceText(sourceText, node) { + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -6034,8 +6491,7 @@ var ts; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 237 && - (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { @@ -6064,18 +6520,19 @@ var ts; } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { - if (!node || !isAmbientModule(node)) { - return false; - } + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { switch (node.parent.kind) { case 272: return ts.isExternalModule(node.parent); case 238: - return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } - ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -6141,6 +6598,10 @@ var ts; } } ts.isAnyImportSyntax = isAnyImportSyntax; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -6199,6 +6660,11 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, startNode.pos); + return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -6510,6 +6976,10 @@ var ts; return false; } ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 231 && node.parent.parent.kind === 212; @@ -6907,6 +7377,10 @@ var ts; return isInJavaScriptFile(file); } ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isSourceFileNotJavaScript(file) { + return !isInJavaScriptFile(file); + } + ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { return node && !!(node.flags & 65536); } @@ -6923,7 +7397,7 @@ var ts; (node.typeArguments[0].kind === 137 || node.typeArguments[0].kind === 134); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { if (callExpression.kind !== 185) { return false; } @@ -6935,7 +7409,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 || arg.kind === 13; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -6946,14 +7420,78 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 230) { - var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 190 || declaration.initializer.kind === 203); + function getJSInitializerSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return symbol; + } + var declaration = symbol.valueDeclaration; + var e = getDeclaredJavascriptInitializer(declaration) || getAssignedJavascriptInitializer(declaration); + return e && e.symbol ? e.symbol : symbol; + } + ts.getJSInitializerSymbol = getJSInitializerSymbol; + function getDeclaredJavascriptInitializer(node) { + if (node && ts.isVariableDeclaration(node) && node.initializer) { + return getJavascriptInitializer(node.initializer, false) || + ts.isIdentifier(node.name) && getDefaultedJavascriptInitializer(node.name, node.initializer, false); + } + } + ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + function getAssignedJavascriptInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + } + ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + function getJavascriptInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 190 || e.kind === 191 ? initializer : undefined; + } + if (initializer.kind === 190 || initializer.kind === 203) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getJavascriptInitializer = getJavascriptInitializer; + function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function getOuterNameOfJsInitializer(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 54 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 58 && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 99 || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); } return false; } - ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; function getRightMostAssignedExpression(node) { while (isAssignmentExpression(node, true)) { node = node.right; @@ -6970,64 +7508,73 @@ var ts; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr)) { - return 0; - } - if (expr.operatorToken.kind !== 58 || expr.left.kind !== 183) { + if (!isInJavaScriptFile(expr) || + expr.operatorToken.kind !== 58 || + !ts.isPropertyAccessExpression(expr.left)) { return 0; } var lhs = expr.left; - if (lhs.expression.kind === 71) { - var lhsId = lhs.expression; - if (lhsId.escapedText === "exports") { - return 1; - } - else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { - return 2; - } - else { - return 5; - } - } - else if (lhs.expression.kind === 99) { + if (lhs.expression.kind === 99) { return 4; } - else if (lhs.expression.kind === 183) { - var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 71) { - var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { - return 1; - } - if (innerPropertyAccess.name.escapedText === "prototype") { - return 3; - } + else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + return 2; + } + else if (isEntityNameExpression(lhs.expression)) { + if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(expr.right)) { + return 6; } + else if (isPrototypeAccess(lhs.expression)) { + return 3; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + return 1; + } + return 5; } return 0; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && expr.parent && expr.parent.kind === 214 && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function importFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 242: + case 248: + return node.parent; + case 252: + return node.parent.parent; + case 185: + return node.parent; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(node)); + } + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; function getExternalModuleName(node) { - if (node.kind === 242) { - return node.moduleSpecifier; - } - if (node.kind === 241) { - var reference = node.moduleReference; - if (reference.kind === 252) { - return reference.expression; - } - } - if (node.kind === 248) { - return node.moduleSpecifier; - } - if (isModuleWithStringLiteralName(node)) { - return node.name; + switch (node.kind) { + case 242: + case 248: + return node.moduleSpecifier; + case 241: + return node.moduleReference.kind === 252 ? node.moduleReference.expression : undefined; + default: + return ts.Debug.assertNever(node); } } ts.getExternalModuleName = getExternalModuleName; @@ -7077,6 +7624,14 @@ var ts; node.expression.operatorToken.kind === 58 && node.expression.right; } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getSpecialPropertyAssignmentKind(node.expression) !== 0 && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 54 && + node.expression.right.right; + } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { case 212: @@ -7110,7 +7665,8 @@ var ts; (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node) { + if (parent && parent.parent && parent.parent.parent && + (getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || @@ -7147,7 +7703,8 @@ var ts; ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { var host = getJSDocHost(node); - var decl = getSourceOfAssignment(host) || + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || @@ -7172,7 +7729,7 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined; + return node.dotDotDotToken !== undefined || node.type && node.type.kind === 281; } ts.isRestParameter = isRestParameter; function getAssignmentTargetKind(node) { @@ -7243,6 +7800,10 @@ var ts; return false; } ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -7257,6 +7818,13 @@ var ts; return walkUp(node, 189); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 189) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; function isDeleteTarget(node) { if (node.kind !== 183 && node.kind !== 184) { return false; @@ -7275,14 +7843,7 @@ var ts; } ts.isNodeDescendantOf = isNodeDescendantOf; function isDeclarationName(name) { - switch (name.kind) { - case 71: - case 9: - case 8: - return ts.isDeclaration(name.parent) && name.parent.name === name; - default: - return false; - } + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; function isAnyDeclarationName(name) { @@ -7361,6 +7922,12 @@ var ts; return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85); return heritageClause ? heritageClause.types : undefined; @@ -7395,38 +7962,6 @@ var ts; return undefined; } ts.getAncestor = getAncestor; - function getFileReferenceFromReferencePath(comment, commentRange) { - var simpleReferenceRegEx = /^\/\/\/\s*= 48 && lookAhead <= 57) { + return "\\x00"; + } + return "\\0"; + } return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { @@ -8142,37 +8678,26 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (ts.hasType(node)) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocType(node); - } + function getEffectiveTypeAnnotationNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; - function getEffectiveReturnTypeNode(node, checkJSDoc) { - if (node.type) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocReturnType(node); - } + function getEffectiveReturnTypeNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { - if (node.typeParameters) { - return node.typeParameters; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; - } + function getEffectiveTypeParameterDeclarations(node) { + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; - function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { + function getJSDocTypeParameterDeclarations(node) { + var templateTag = ts.getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + function getEffectiveSetAccessorTypeAnnotationNode(node) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); + return parameter && getEffectiveTypeAnnotationNode(parameter); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -8257,7 +8782,7 @@ var ts; } return currentDetachedCommentInfo; function isPinnedCommentLocal(comment) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } ts.emitDetachedComments = emitDetachedComments; @@ -8432,10 +8957,17 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 || - node.kind === 183 && isEntityNameExpression(node.expression); + return node.kind === 71 || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 145 && node.parent.right === node) || (node.parent.kind === 183 && node.parent.name === node); @@ -8515,6 +9047,73 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + output += String.fromCharCode(value); + } + else { + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -8828,6 +9427,40 @@ var ts; return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -8862,27 +9495,20 @@ var ts; } ts.textSpanContainsTextSpan = textSpanContainsTextSpan; function textSpanOverlapsWith(span, other) { - var overlapStart = Math.max(span.start, other.start); - var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); - return overlapStart < overlapEnd; + return textSpanOverlap(span, other) !== undefined; } ts.textSpanOverlapsWith = textSpanOverlapsWith; function textSpanOverlap(span1, span2) { - var overlapStart = Math.max(span1.start, span2.start); - var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (overlapStart < overlapEnd) { - return createTextSpanFromBounds(overlapStart, overlapEnd); - } - return undefined; + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; } ts.textSpanOverlap = textSpanOverlap; function textSpanIntersectsWithTextSpan(span, other) { - return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); } ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; function textSpanIntersectsWith(span, start, length) { - var end = start + length; - return start <= textSpanEnd(span) && end >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); } ts.textSpanIntersectsWith = textSpanIntersectsWith; function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { @@ -8896,12 +9522,9 @@ var ts; } ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; function textSpanIntersection(span1, span2) { - var intersectStart = Math.max(span1.start, span2.start); - var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (intersectStart <= intersectEnd) { - return createTextSpanFromBounds(intersectStart, intersectEnd); - } - return undefined; + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; } ts.textSpanIntersection = textSpanIntersection; function createTextSpan(start, length) { @@ -8914,6 +9537,12 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; + function createTextRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos); + return { pos: pos, end: end }; + } + ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -9164,6 +9793,10 @@ var ts; return declaration.name || nameForNamelessJSDocTypedef(declaration); } ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + function isNamedDeclaration(node) { + return !!node.name; + } + ts.isNamedDeclaration = isNamedDeclaration; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -9206,31 +9839,31 @@ var ts; 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; }); } - return undefined; + return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 287); + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285); + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 286); + return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 288); + return getFirstJSDocTag(node, ts.isJSDocReturnTag); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 290); + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getJSDocTypeTag(node) { - var tag = getFirstJSDocTag(node, 289); + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -9238,12 +9871,9 @@ var ts; } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 289); - if (!tag && node.kind === 148) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); } return tag && tag.typeExpression && tag.typeExpression.type; } @@ -9261,13 +9891,11 @@ var ts; return tags; } ts.getJSDocTags = getJSDocTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); } function getAllJSDocTagsOfKind(node, kind) { - var tags = getJSDocTags(node); - return ts.filter(tags, function (doc) { return doc.kind === kind; }); + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); @@ -9875,6 +10503,10 @@ var ts; return node.kind === 285; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 286; + } + ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { return node.kind === 287; } @@ -9973,6 +10605,14 @@ var ts; return false; } ts.isModifierKind = isModifierKind; + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 115; + } + ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { return isModifierKind(node.kind); } @@ -10555,6 +11195,43 @@ var ts; return !!node.type; } ts.hasType = hasType; + function couldHaveType(node) { + switch (node.kind) { + case 148: + case 150: + case 151: + case 152: + case 153: + case 154: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 162: + case 163: + case 172: + case 174: + case 176: + case 188: + case 190: + case 191: + case 206: + case 230: + case 232: + case 235: + case 274: + case 277: + case 278: + case 279: + case 280: + case 281: + return true; + } + return false; + } + ts.couldHaveType = couldHaveType; function hasInitializer(node) { return !!node.initializer; } @@ -10582,6 +11259,30 @@ var ts; return node.kind === 161 || node.kind === 205; } ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { return node.kind === 9 || node.kind === 13; } @@ -10625,6 +11326,12 @@ var ts; } } } + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 && + text.charCodeAt(start + 2) === 42 && + text.charCodeAt(start + 3) !== 47; + } + ts.isJSDocLikeText = isJSDocLikeText; function forEachChild(node, cbNode, cbNodes) { if (!node || node.kind <= 144) { return; @@ -10980,6 +11687,7 @@ var ts; case 254: case 255: return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); case 261: return visitNodes(cbNode, cbNodes, node.properties); @@ -11193,7 +11901,8 @@ var ts; sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; nextToken(); - processReferenceComments(sourceFile); + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); sourceFile.statements = parseList(0, parseStatement); ts.Debug.assert(token() === 1); sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); @@ -11206,6 +11915,9 @@ var ts; fixupParentReferences(sourceFile); } return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } } function addJSDocComment(node) { var comments = ts.getJSDocCommentRanges(node, sourceFile.text); @@ -11329,9 +12041,7 @@ var ts; return inContext(16384); } function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); } function parseErrorAtPosition(start, length, message, arg0) { var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -11340,9 +12050,14 @@ var ts; } parseErrorBeforeNextFinishedNode = true; } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); + parseErrorAtPosition(scanner.getTextPos(), length, message); } function getNodePos() { return scanner.getStartPos(); @@ -11572,24 +12287,25 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76) { - return nextToken() === 83; + switch (token()) { + case 76: + return nextToken() === 83; + case 84: + nextToken(); + if (token() === 79) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); + case 79: + return nextTokenCanFollowDefaultKeyword(); + case 115: + case 125: + case 136: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === 84) { - nextToken(); - if (token() === 79) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); - } - if (token() === 79) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === 115) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); @@ -12146,9 +12862,20 @@ var ts; nextToken(); return finishNode(node); } - function parseJSDocAllType() { + function parseJSDocAllType(postFixEquals) { var result = createNode(275); + if (postFixEquals) { + return createJSDocPostfixType(279, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(278); nextToken(); + result.type = parseNonArrayType(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { @@ -12186,14 +12913,21 @@ var ts; parameter.name = parseIdentifierName(); parseExpected(56); } - parameter.type = parseType(); + parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocNodeWithType(kind) { - var result = createNode(kind); - nextToken(); - result.type = parseNonArrayType(); - return finishNode(result); + function parseJSDocType() { + var dotdotdot = parseOptionalToken(24); + var type = parseType(); + if (dotdotdot) { + var variadic = createNode(281, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 58) { + return createJSDocPostfixType(279, type); + } + return type; } function parseTypeQuery() { var node = createNode(164); @@ -12521,13 +13255,15 @@ var ts; case 135: return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 39: - return parseJSDocAllType(); + return parseJSDocAllType(false); + case 61: + return parseJSDocAllType(true); case 55: return parseJSDocUnknownOrNullableType(); case 89: return parseJSDocFunctionType(); case 51: - return parseJSDocNodeWithType(278); + return parseJSDocNonNullableType(); case 13: case 9: case 8: @@ -12607,12 +13343,6 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 58: - if (!(contextFlags & 1048576)) { - return type; - } - type = createJSDocPostfixType(279, type); - break; case 51: type = createJSDocPostfixType(278, type); break; @@ -12673,12 +13403,6 @@ var ts; return parseTypeOperator(operator); case 126: return parseInferType(); - case 24: { - var result = createNode(281); - nextToken(); - result.type = parsePostfixTypeOrHigher(); - return finishNode(result); - } } return parsePostfixTypeOrHigher(); } @@ -13116,7 +13840,7 @@ var ts; function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); var consumeCurrentOperator = token() === 40 ? newPrecedence >= precedence : newPrecedence > precedence; @@ -13145,48 +13869,7 @@ var ts; if (inDisallowInContext() && token() === 92) { return false; } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54: - return 1; - case 53: - return 2; - case 49: - return 3; - case 50: - return 4; - case 48: - return 5; - case 32: - case 33: - case 34: - case 35: - return 6; - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: - return 7; - case 45: - case 46: - case 47: - return 8; - case 37: - case 38: - return 9; - case 39: - case 41: - case 42: - return 10; - case 40: - return 11; - } - return -1; + return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { var node = createNode(198, left.pos); @@ -13245,18 +13928,19 @@ var ts; if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); return token() === 40 ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; if (simpleUnaryExpression.kind === 188) { - 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); + parseErrorAt(pos, end, 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 { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; @@ -13373,7 +14057,7 @@ var ts; 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)); + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } @@ -13409,8 +14093,19 @@ var ts; currentToken = scanner.scanJsxToken(); return finishNode(node); } - function parseJsxChild() { - switch (token()) { + function parseJsxChild(openingTag, token) { + switch (token) { + case 1: + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 28: + case 7: + return undefined; case 10: case 11: return parseJsxText(); @@ -13418,8 +14113,9 @@ var ts; return parseJsxExpression(false); case 27: return parseJsxElementOrSelfClosingElementOrFragment(false); + default: + return ts.Debug.assertNever(token); } - ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTag) { var list = []; @@ -13427,27 +14123,10 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; - } - else if (token() === 1) { - 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) { - break; - } - var child = parseJsxChild(); - if (child) { - list.push(child); - } + list.push(child); } parsingContext = saveParsingContext; return createNodeArray(list, listPos); @@ -13461,11 +14140,12 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(27); if (token() === 29) { - parseExpected(29); var node_1 = createNode(258, fullStart); + scanJsxText(); return finishNode(node_1); } var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; if (token() === 29) { @@ -13484,6 +14164,7 @@ var ts; node = createNode(254, fullStart); } node.tagName = tagName; + node.typeArguments = typeArguments; node.attributes = attributes; return finishNode(node); } @@ -13501,7 +14182,9 @@ var ts; } function parseJsxExpression(inExpressionContext) { var node = createNode(263); - parseExpected(17); + if (!parseExpected(17)) { + return undefined; + } if (token() !== 18) { node.dotDotDotToken = parseOptionalToken(24); node.expression = parseAssignmentExpressionOrHigher(); @@ -13559,8 +14242,7 @@ var ts; var node = createNode(259); 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); + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { parseExpected(29); @@ -13925,7 +14607,7 @@ var ts; parseExpected(88); var awaitToken = parseOptionalToken(121); parseExpected(19); - var initializer = undefined; + var initializer; if (token() !== 25) { if (token() === 104 || token() === 110 || token() === 76) { initializer = parseVariableDeclarationList(true); @@ -14501,18 +15183,6 @@ var ts; node.body = parseFunctionBlockOrSemicolon(0); return finishNode(node); } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114: - case 112: - case 113: - case 115: - case 132: - return true; - default: - return false; - } - } function isClassMemberStart() { var idToken; if (token() === 57) { @@ -14520,7 +15190,7 @@ var ts; } while (ts.isModifierKind(token())) { idToken = token(); - if (isClassMemberModifier(idToken)) { + if (ts.isClassMemberModifier(idToken)) { return true; } nextToken(); @@ -14907,7 +15577,7 @@ var ts; node.name = identifierName; } if (kind === 246 && checkIdentifierIsKeyword) { - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } @@ -14939,84 +15609,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); - var referencedFiles = []; - var typeReferenceDirectives = []; - var amdDependencies = []; - var amdModuleName; - var checkJsDirective = undefined; - while (true) { - var kind = triviaScanner.scan(); - if (kind !== 2) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*= pos_2); pos_2 = child.end; - }); + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); ts.Debug.assert(pos_2 <= node.end); } } @@ -15795,6 +16391,12 @@ var ts; child._children = undefined; adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } @@ -15838,15 +16440,15 @@ var ts; var lastNodeEntirelyBeforePosition; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } } return bestResult; - function getLastChild(node) { + function getLastDescendant(node) { while (true) { - var lastChild = getLastChildWorker(node); + var lastChild = ts.getLastChild(node); if (lastChild) { node = lastChild; } @@ -15855,15 +16457,6 @@ var ts; } } } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } function visit(child) { if (ts.nodeIsMissing(child)) { return; @@ -15964,6 +16557,200 @@ var ts; function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); } + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, false, 0, sourceText); + var pragmas = []; + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { + var _b = _a.arguments, name = _b.name, path = _b.path; + return ({ name: name, path: path }); + }); + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; + default: ts.Debug.fail("Unhandled pragma kind"); + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2, singleLine); + } + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; + var multiLineMatch; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4, multiLineMatch); + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -16029,8 +16816,8 @@ var ts; var languageVersion; var parent; var container; + var thisParentContainer; var blockScopeContainer; - var inferenceContainer; var lastContainer; var seenThisKeyword; var currentFlow; @@ -16073,8 +16860,8 @@ var ts; languageVersion = undefined; parent = undefined; container = undefined; + thisParentContainer = undefined; blockScopeContainer = undefined; - inferenceContainer = undefined; lastContainer = undefined; seenThisKeyword = false; currentFlow = undefined; @@ -16104,19 +16891,14 @@ var ts; function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = [node]; - } - else { - symbol.declarations.push(node); - } + symbol.declarations = ts.append(symbol.declarations, node); if (symbolFlags & 1952 && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } if (symbolFlags & 6240 && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 107455) { + if (symbolFlags & 67216319) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 237)) { @@ -16142,7 +16924,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } - return ts.getEscapedTextOfIdentifierOrLiteral(name); + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { case 154: @@ -16169,7 +16951,7 @@ var ts; case 280: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); case 148: - ts.Debug.assert(node.parent.kind === 280); + ts.Debug.assert(node.parent.kind === 280, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -16179,7 +16961,7 @@ var ts; } } function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); } function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); @@ -16207,7 +16989,7 @@ var ts; symbolTable.set(name, symbol = createSymbol(0, name)); } else { - if (node.name) { + if (ts.isNamedDeclaration(node)) { node.name.parent = node; } var message_1 = symbol.flags & 2 @@ -16236,7 +17018,12 @@ var ts; } } addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { @@ -16254,7 +17041,7 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); var isJSDocTypedefInJSDocNamespace = ts.isJSDocTypedefTag(node) && node.name && node.name.kind === 71 && node.name.isInJSDocNamespace; if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = symbolFlags & 107455 ? 1048576 : 0; + var exportKind = symbolFlags & 67216319 ? 1048576 : 0; var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -16267,8 +17054,12 @@ var ts; } function bindContainer(node, containerFlags) { var saveContainer = container; + var saveThisParentContainer = thisParentContainer; var savedBlockScopeContainer = blockScopeContainer; if (containerFlags & 1) { + if (node.kind !== 191) { + thisParentContainer = container; + } container = blockScopeContainer = node; if (containerFlags & 32) { container.locals = ts.createSymbolTable(); @@ -16329,17 +17120,11 @@ var ts; bindChildren(node); node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; } - else if (containerFlags & 256) { - var saveInferenceContainer = inferenceContainer; - inferenceContainer = node; - node.locals = undefined; - bindChildren(node); - inferenceContainer = saveInferenceContainer; - } else { bindChildren(node); } container = saveContainer; + thisParentContainer = saveThisParentContainer; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { @@ -16359,12 +17144,17 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } - function bindEach(nodes) { + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 232 ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 232 ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } if (nodes === undefined) { return; } if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); + ts.forEach(nodes, bindFunction); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -16372,7 +17162,7 @@ var ts; var nodeArrayFlags = 0; for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { var node = nodes_2[_i]; - bind(node); + bindFunction(node); nodeArrayFlags |= node.transformFlags & ~536870912; } nodes.transformFlags = nodeArrayFlags | 536870912; @@ -16468,6 +17258,14 @@ var ts; case 291: bindJSDocTypedefTag(node); break; + case 272: + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + case 211: + case 238: + bindEachFunctionsFirst(node.statements); + break; default: bindEachChild(node); break; @@ -17085,8 +17883,6 @@ var ts; case 235: case 176: return 1 | 32; - case 170: - return 256; case 272: return 1 | 4 | 32; case 153: @@ -17201,7 +17997,7 @@ var ts; if (ts.hasModifier(node, 1)) { errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } - if (ts.isExternalModuleAugmentation(node)) { + if (ts.isModuleAugmentationExternal(node)) { declareModuleSymbol(node); } else { @@ -17215,10 +18011,8 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 67215503); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } else { @@ -17234,7 +18028,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 67215503 : 0); return state; } function bindFunctionOrConstructorType(node) { @@ -17263,8 +18057,8 @@ var ts; continue; } if (currentKind === 1 && existingKind === 1) { - 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)); + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -17302,7 +18096,7 @@ var ts; } } function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 107455); + bindBlockScopedDeclaration(node, 2, 67216319); } function checkStrictModeIdentifier(node) { if (inStrictMode && @@ -17336,8 +18130,8 @@ var ts; } function checkStrictModeDeleteExpression(node) { if (inStrictMode && node.expression.kind === 71) { - 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)); + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -17347,8 +18141,8 @@ var ts; if (name && name.kind === 71) { 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.idText(identifier))); + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -17472,7 +18266,7 @@ var ts; } } function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); return nodeText === '"use strict"' || nodeText === "'use strict'"; } function bindWorker(node) { @@ -17483,7 +18277,7 @@ var ts; while (parentNode && parentNode.kind !== 291) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288, 793064); + bindBlockScopedDeclaration(parentNode, 524288, 67901928); break; } case 99: @@ -17509,13 +18303,16 @@ var ts; bindModuleExportsAssignment(node); break; case 3: - bindPrototypePropertyAssignment(node); + bindPrototypePropertyAssignment(node.left, node); + break; + case 6: + bindPrototypeAssignment(node); break; case 4: bindThisPropertyAssignment(node); break; case 5: - bindStaticPropertyAssignment(node); + bindSpecialPropertyAssignment(node); break; case 0: break; @@ -17539,7 +18336,7 @@ var ts; seenThisKeyword = true; return; case 160: - return checkTypePredicate(node); + break; case 147: return bindTypeParameter(node); case 148: @@ -17556,22 +18353,22 @@ var ts; case 269: return bindPropertyOrMethodOrAccessor(node, 4, 0); case 271: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); + return bindPropertyOrMethodOrAccessor(node, 8, 68008959); case 157: case 158: case 159: return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 153: case 152: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67208127); case 232: return bindFunctionDeclaration(node); case 154: return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 155: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + return bindPropertyOrMethodOrAccessor(node, 32768, 67150783); case 156: - return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + return bindPropertyOrMethodOrAccessor(node, 65536, 67183551); case 162: case 280: case 163: @@ -17595,9 +18392,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 234: - return bindBlockScopedDeclaration(node, 64, 792968); + return bindBlockScopedDeclaration(node, 64, 67901832); case 235: - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 524288, 67901928); case 236: return bindEnumDeclaration(node); case 237: @@ -17641,7 +18438,7 @@ var ts; case 291: { var fullName = node.fullName; if (!fullName || fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 524288, 67901928); } break; } @@ -17653,16 +18450,6 @@ var ts; function bindAnonymousTypeWorker(node) { return bindAnonymousDeclaration(node, 2048, "__type"); } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 173) { - seenThisKeyword = true; - } - bind(type); - } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -17728,7 +18515,18 @@ var ts; } function bindExportsPropertyAssignment(node) { setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, function (id, original) { + if (!original) { + return undefined; + } + var s = ts.getJSInitializerSymbol(original); + addDeclarationToSymbol(s, id, 1536 | 67108864); + return s; + }); + if (symbol) { + declareSymbol(symbol.exports, symbol, lhs, 4 | 1048576, 0); + } } function bindModuleExportsAssignment(node) { var assignedExpression = ts.getRightMostAssignedExpression(node.right); @@ -17741,96 +18539,133 @@ var ts; } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, false); - switch (container.kind) { + var thisContainer = ts.getThisContainer(node, false); + switch (thisContainer.kind) { case 232: case 190: - container.symbol.members = container.symbol.members || ts.createSymbolTable(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + var constructorSymbol = thisContainer.symbol; + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = getJSInitializerSymbolFromName(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4, 0 & ~4); + } break; case 154: case 151: case 153: case 155: case 156: - var containingClass = container.parent; - var symbolTable = ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members; + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); break; + case 272: + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); } } 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 === 183) && - node.parent.parent.kind === 272) { - bindStaticPropertyAssignment(node); - } - } - function bindPrototypePropertyAssignment(node) { - var leftSideOfAssignment = node.left; - var classPrototype = leftSideOfAssignment.expression; - var constructorFunction = classPrototype.expression; - leftSideOfAssignment.parent = node; - constructorFunction.parent = classPrototype; - classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, true); - } - function bindStaticPropertyAssignment(node) { - var leftSideOfAssignment = node.kind === 183 ? node : node.left; - var target = leftSideOfAssignment.expression; - if (ts.isIdentifier(target)) { - target.parent = leftSideOfAssignment; - if (node.kind === 198) { - leftSideOfAssignment.parent = node; - } - if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { - bindExportsPropertyAssignment(node); + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 272) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); } else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + bindStaticPropertyAssignment(node); } } } - function lookupSymbolForName(name) { - return lookupSymbolForNameWorker(container, name); + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs, lhs, false); } - 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 === 198 || propertyAccess.parent.kind === 214); - var isLegalPosition; - if (propertyAccess.parent.kind === 198) { - var initializerKind = propertyAccess.parent.right.kind; - isLegalPosition = (initializerKind === 203 || initializerKind === 190) && - propertyAccess.parent.parent.parent.kind === 272; + function bindPrototypePropertyAssignment(lhs, parent) { + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, true); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + bindExportsPropertyAssignment(node); } else { - isLegalPosition = propertyAccess.parent.parent.kind === 272; + bindStaticPropertyAssignment(lhs); } - 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); - } + } + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, false); + } + function getJSInitializerSymbolFromName(name, lookupContainer) { + return ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(name, lookupContainer)); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var symbol = getJSInitializerSymbolFromName(name); + var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) + ? propertyAccess.parent.parent.parent.kind === 272 && + !!ts.getJavascriptInitializer(propertyAccess.parent.right, ts.isPrototypeAccess(propertyAccess.parent.left)) + : propertyAccess.parent.parent.kind === 272; + if (!isPrototypeProperty && (!symbol || !(symbol.flags & 1920)) && isToplevelNamespaceableInitializer) { + var flags_1 = 1536 | 67108864; + var excludeFlags_1 = 67215503 & ~67108864; + forEachIdentifierInEntityName(propertyAccess.expression, function (id, original) { + if (original) { + addDeclarationToSymbol(original, id, flags_1); + return original; + } + else { + return symbol = declareSymbol(symbol ? symbol.exports : container.locals, symbol, id, flags_1, excludeFlags_1); + } + }); } - if (!targetSymbol || !(targetSymbol.flags & (16 | 32 | 1024))) { + if (!symbol || !(symbol.flags & (16 | 32 | 1024 | 4096))) { return; } var symbolTable = isPrototypeProperty ? - (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : - (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); - declareSymbol(symbolTable, targetSymbol, propertyAccess, 4, 0); + (symbol.members || (symbol.members = ts.createSymbolTable())) : + (symbol.exports || (symbol.exports = ts.createSymbolTable())); + var symbolFlags = 4 | (isToplevelNamespaceableInitializer ? 67108864 : 0); + var symbolExcludes = 0 & ~(isToplevelNamespaceableInitializer ? 67108864 : 0); + declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(node.expression)); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e)); + } + else { + var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); + ts.Debug.assert(!!s && !!s.exports); + return action(e.name, s.exports.get(e.name.escapedText)); + } } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { @@ -17839,7 +18674,7 @@ var ts; } function bindClassLikeDeclaration(node) { if (node.kind === 233) { - bindBlockScopedDeclaration(node, 32, 899519); + bindBlockScopedDeclaration(node, 32, 68008383); } else { var bindingName = node.name ? node.name.escapedText : "__class"; @@ -17862,8 +18697,8 @@ var ts; } function bindEnumDeclaration(node) { return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128, 899967) - : bindBlockScopedDeclaration(node, 256, 899327); + ? bindBlockScopedDeclaration(node, 128, 68008831) + : bindBlockScopedDeclaration(node, 256, 68008191); } function bindVariableDeclarationOrBindingElement(node) { if (inStrictMode) { @@ -17874,10 +18709,10 @@ var ts; bindBlockScopedVariableDeclaration(node); } else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 107455); + declareSymbolAndAddToSymbolTable(node, 1, 67216319); } else { - declareSymbolAndAddToSymbolTable(node, 1, 107454); + declareSymbolAndAddToSymbolTable(node, 1, 67216318); } } } @@ -17889,7 +18724,7 @@ var ts; bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1, 107455); + declareSymbolAndAddToSymbolTable(node, 1, 67216319); } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; @@ -17905,10 +18740,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 106927); + bindBlockScopedDeclaration(node, 16, 67215791); } else { - declareSymbolAndAddToSymbolTable(node, 16, 106927); + declareSymbolAndAddToSymbolTable(node, 16, 67215791); } } function bindFunctionExpression(node) { @@ -17935,20 +18770,31 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + function getInferTypeContainer(node) { + while (node) { + var parent_2 = node.parent; + if (parent_2 && parent_2.kind === 170 && parent_2.extendsType === node) { + return parent_2; + } + node = parent_2; + } + return undefined; + } function bindTypeParameter(node) { if (node.parent.kind === 171) { - if (inferenceContainer) { - if (!inferenceContainer.locals) { - inferenceContainer.locals = ts.createSymbolTable(); + var container_1 = getInferTypeContainer(node.parent); + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); } - declareSymbol(inferenceContainer.locals, undefined, node, 262144, 530920); + declareSymbol(container_1.locals, undefined, node, 262144, 67639784); } else { bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144, 530920); + declareSymbolAndAddToSymbolTable(node, 262144, 67639784); } } function shouldReportErrorOnModuleDeclaration(node) { @@ -19065,8 +19911,10 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createMap(); - var moduleNameToDirectoryMap = ts.createMap(); + return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); @@ -19132,7 +19980,7 @@ var ts; } } } - ts.createModuleResolutionCache = createModuleResolutionCache; + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -19143,7 +19991,7 @@ var ts; var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } } else { @@ -19265,7 +20113,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); } - var matchedPattern = undefined; + var matchedPattern; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); @@ -19625,7 +20473,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -19677,6 +20525,7 @@ var ts; } return packageName; } + ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { @@ -19691,12 +20540,13 @@ var ts; typesPackageName; } ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { var result = cache && cache.get(containingDirectory); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } + failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } @@ -19715,7 +20565,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -19969,7 +20819,7 @@ var ts; node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (node) { node = ts.getParseTreeNode(node, ts.isParameter); return node ? isOptionalParameter(node) : false; @@ -20006,7 +20856,7 @@ var ts; resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals); }, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, @@ -20018,13 +20868,13 @@ var ts; node = ts.getParseTreeNode(node, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, + getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; }, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); - var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4, "unknown"); @@ -20086,6 +20936,7 @@ var ts; var anyArrayType; var autoArrayType; var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; var deferredGlobalESSymbolConstructorSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; @@ -20099,11 +20950,9 @@ var ts; var deferredGlobalAsyncIteratorType; var deferredGlobalAsyncIterableIteratorType; var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; var deferredNodes; var deferredUnusedIdentifierNodes; + var seenDeferredUnusedIdentifiers = ts.createMap(); var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -20128,6 +20977,18 @@ var ts; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); + var suggestionDiagnostics = ts.createMultiMap(); + function addSuggestionDiagnostic(diag) { + suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + function addErrorOrSuggestionDiagnostic(isError, diag) { + if (isError) { + diagnostics.add(diag); + } + else { + addSuggestionDiagnostic(diag); + } + } var typeofEQFacts = ts.createMapFromTemplate({ string: 1, number: 2, @@ -20156,11 +21017,6 @@ var ts; var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - var jsxTypes = ts.createUnderscoreEscapedMap(); var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var definitelyAssignableRelation = ts.createMap(); @@ -20305,7 +21161,23 @@ var ts; }; } } - function getJsxNamespace() { + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } if (!_jsxNamespace) { _jsxNamespace = "React"; if (compilerOptions.jsxFactory) { @@ -20342,35 +21214,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2) - result |= 107455; + result |= 67216319; if (flags & 1) - result |= 107454; + result |= 67216318; if (flags & 4) result |= 0; if (flags & 8) - result |= 900095; + result |= 68008959; if (flags & 16) - result |= 106927; + result |= 67215791; if (flags & 32) - result |= 899519; + result |= 68008383; if (flags & 64) - result |= 792968; + result |= 67901832; if (flags & 256) - result |= 899327; + result |= 68008191; if (flags & 128) - result |= 899967; + result |= 68008831; if (flags & 512) - result |= 106639; + result |= 67215503; if (flags & 8192) - result |= 99263; + result |= 67208127; if (flags & 32768) - result |= 41919; + result |= 67150783; if (flags & 65536) - result |= 74687; + result |= 67183551; if (flags & 262144) - result |= 530920; + result |= 67639784; if (flags & 524288) - result |= 793064; + result |= 67901928; if (flags & 2097152) result |= 2097152; return result; @@ -20399,7 +21271,7 @@ var ts; } function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - source.flags & 67108864 || target.flags & 67108864) { + (source.flags | target.flags) & 67108864) { if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; } @@ -20420,6 +21292,13 @@ var ts; target.exports = ts.createSymbolTable(); mergeSymbolTable(target.exports, source.exports); } + if ((source.flags | target.flags) & 67108864) { + var sourceInitializer = ts.getJSInitializerSymbol(source); + var targetInitializer = ts.getJSInitializerSymbol(target); + if (sourceInitializer !== source || targetInitializer !== target) { + mergeSymbol(targetInitializer, sourceInitializer); + } + } recordMergedSymbol(target, source); } else if (target.flags & 1024) { @@ -20432,10 +21311,12 @@ var ts; ? 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)); + var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); } } @@ -20538,8 +21419,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -20641,18 +21522,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 !== 282) { + if (meaning & result.flags & 67901928 && lastLocation.kind !== 282) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 148 || lastLocation.kind === 147 : false; } - if (meaning & 107455 && result.flags & 1) { + if (meaning & 67216319 && result.flags & 1) { useResult = lastLocation.kind === 148 || (lastLocation === location.type && - result.valueDeclaration.kind === 148); + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } else if (location.kind === 170) { @@ -20702,7 +21583,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 67216319)) { propertyWithInvalidInitializer = location; } } @@ -20711,7 +21592,7 @@ var ts; case 233: case 203: case 234: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064)) { + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -20733,7 +21614,7 @@ var ts; case 205: 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))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -20744,7 +21625,7 @@ var ts; case 146: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 234) { - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -20835,13 +21716,13 @@ var ts; } if (errorLocation && (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455))) { + ((meaning & 32 || meaning & 384) && (meaning & 67216319) === 67216319))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 107455) === 107455) { + if (result && isInExternalModule && (meaning & 67216319) === 67216319) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 240) { 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)); @@ -20926,8 +21807,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~1920, undefined, undefined, false)); + var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(errorLocation) ? 67216319 : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~namespaceMeaning, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -20946,12 +21828,12 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (107455 & ~1024)) { + if (meaning & (67216319 & ~1024)) { 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)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~67216319, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; @@ -20960,15 +21842,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 & (67216319 & ~1024 & ~67901928)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67216319, undefined, undefined, 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, (512 | 1024) & ~793064, undefined, undefined, false)); + else if (meaning & (67901928 & ~1024 & ~67216319)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67901928, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -21024,12 +21906,16 @@ var ts; ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512)); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { return false; } if (!file || file.isDeclarationFile) { - if (resolveExportByName(moduleSymbol, "default", dontResolveAlias)) { + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default", dontResolveAlias); + if (defaultExportSymbol && defaultExportSymbol.valueDeclaration && isSyntacticDefault(defaultExportSymbol.valueDeclaration)) { return false; } if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { @@ -21057,7 +21943,7 @@ var ts; if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && hasSyntheticDefault) { + else if (hasSyntheticDefault) { return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -21071,7 +21957,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (793064 | 1920)) { + if (valueSymbol.flags & (67901928 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -21123,7 +22009,15 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + var moduleName = getFullyQualifiedName(moduleSymbol); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } return symbol; } @@ -21141,7 +22035,7 @@ var ts; resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); + return resolveEntityName(node.expression, 67216319 | 67901928 | 1920, false, dontResolveAlias); } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { @@ -21154,7 +22048,7 @@ var ts; case 246: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 250: - return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67216319 | 67901928 | 1920, dontRecursivelyResolve); case 247: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 240: @@ -21162,7 +22056,7 @@ var ts; } } function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 107455 | 793064 | 1920; } + if (excludes === void 0) { excludes = 67216319 | 67901928 | 1920; } return symbol && (symbol.flags & (2097152 | excludes)) === 2097152; } function resolveSymbol(symbol, dontResolveAlias) { @@ -21194,7 +22088,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67216319) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -21226,7 +22120,7 @@ var ts; } else { ts.Debug.assert(entityName.parent.kind === 241); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 67216319 | 67901928 | 1920, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -21236,35 +22130,43 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } + var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(name) ? meaning & 67216319 : 0); var symbol; if (name.kind === 71) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === namespaceMeaning ? 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 (!symbol) { return undefined; } } else if (name.kind === 145 || name.kind === 183) { - var left = void 0; - if (name.kind === 145) { - left = name.left; - } - else if (name.kind === 183) { - left = name.expression; - } - else { - return undefined; - } + var left = name.kind === 145 ? name.left : name.expression; var right = name.kind === 145 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); + var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, 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); + if (ts.isInJavaScriptFile(name)) { + var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + if (initializer) { + namespace = getSymbolOfNode(initializer); + } + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { @@ -21308,6 +22210,9 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + } return getMergedSymbol(sourceFile.symbol); } if (moduleNotFoundError) { @@ -21326,10 +22231,8 @@ var ts; 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.packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + else { + addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); } return undefined; } @@ -21350,6 +22253,11 @@ var ts; } return undefined; } + function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)); + return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; } @@ -21510,7 +22418,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 107455); + return !!(symbol.flags & 67216319 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67216319); } function findConstructorDeclaration(node) { var members = node.members; @@ -21603,13 +22511,21 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; + return rightMeaning === 67216319 ? 67216319 : 1920; } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { return undefined; } - var visitedSymbolTables = []; + var id = "" + getSymbolId(symbol); + var visitedSymbolTables; + if (visitedSymbolTablesMap.has(id)) { + visitedSymbolTables = visitedSymbolTablesMap.get(id); + } + else { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { @@ -21621,7 +22537,7 @@ var ts; } function canQualifySymbol(symbolFromSymbolTable, meaning) { return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || - !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && @@ -21635,6 +22551,7 @@ var ts; return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 && symbolFromSymbolTable.escapedName !== "export=" + && symbolFromSymbolTable.escapedName !== "default" && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -21688,11 +22605,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928, false); return access.accessibility === 0; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319, false); return access.accessibility === 0; } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { @@ -21768,14 +22685,14 @@ var ts; if (entityName.parent.kind === 164 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 146) { - meaning = 107455 | 1048576; + meaning = 67216319 | 1048576; } else if (entityName.kind === 145 || entityName.kind === 183 || entityName.parent.kind === 241) { meaning = 1920; } else { - meaning = 793064; + meaning = 67901928; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); @@ -21825,6 +22742,7 @@ var ts; } } function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576; } if (writer === void 0) { writer = ts.createTextWriter(""); } var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); @@ -21907,7 +22825,8 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined + symbolStack: undefined, + inferTypeParameters: undefined }; } function typeToTypeNodeHelper(type, context) { @@ -21931,12 +22850,12 @@ var ts; } if (type.flags & 256 && !(type.flags & 131072)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 793064, false); + var parentName = symbolToName(parentSymbol, context, 67901928, false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 272) { - var name = symbolToName(type.symbol, context, 793064, false); + var name = symbolToName(type.symbol, context, 67901928, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { @@ -21950,6 +22869,9 @@ var ts; } if (type.flags & 1024) { if (!(context.flags & 1048576)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeQueryNode(symbolToName(type.symbol, context, 67216319, false)); + } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } @@ -21991,7 +22913,10 @@ var ts; return typeReferenceToTypeNode(type); } if (type.flags & 32768 || objectFlags & 3) { - var name = type.symbol ? symbolToName(type.symbol, context, 793064, false) : ts.createIdentifier("?"); + if (type.flags & 32768 && ts.contains(context.inferTypeParameters, type)) { + return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + } + var name = type.symbol ? symbolToName(type.symbol, context, 67901928, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { @@ -22029,13 +22954,16 @@ var ts; } if (type.flags & 2097152) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); - var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); - var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 4194304) { - return typeToTypeNodeHelper(type.typeParameter, context); + return typeToTypeNodeHelper(type.typeVariable, context); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { @@ -22053,12 +22981,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 203 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455); + return createTypeQueryNodeFromSymbol(symbol, 67216319); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, context, 793064, false); + var entityName = symbolToName(typeAlias, context, 67901928, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -22130,7 +23058,7 @@ var ts; return ts.createTypeQueryNode(entityName); } function symbolToTypeReferenceName(symbol) { - var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928, false) : ts.createIdentifier(""); return entityName; } function typeReferenceToTypeNode(type) { @@ -22158,7 +23086,8 @@ var ts; } else if (context.flags & 2048 && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 203) { + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } else { @@ -22189,7 +23118,7 @@ var ts; } } } - var entityName = undefined; + var entityName = void 0; var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); @@ -22264,12 +23193,12 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319); if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455); + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); } } - var propertyName = symbolToName(propertySymbol, context, 107455, true); + var propertyName = symbolToName(propertySymbol, context, 67216319, true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { @@ -22359,7 +23288,7 @@ var ts; if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } var savedContextFlags = context.flags; context.flags &= ~512; - var name = symbolToName(type.symbol, context, 793064, true); + var name = symbolToName(type.symbol, context, 67901928, true); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); @@ -22584,9 +23513,6 @@ var ts; node.parent.kind === 238 && ts.isExternalModuleAugmentation(node.parent.parent); } - function literalTypeToString(type) { - return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; - } function isDefaultBindingContext(location) { return location.kind === 272 || ts.isAmbientModule(location); } @@ -22617,8 +23543,8 @@ var ts; return "(Anonymous function)"; } } - if (symbol.syntheticLiteralTypeOrigin) { - var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (symbol.nameType && symbol.nameType.flags & 32) { + var stringValue = symbol.nameType.value; if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { return "\"" + ts.escapeString(stringValue, 34) + "\""; } @@ -22702,10 +23628,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 247) { - exportSymbol = resolveName(node, node.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, node, false); + exportSymbol = resolveName(node, node.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, node, false); } else if (node.parent.kind === 250) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 | 67901928 | 1920 | 2097152); } var result; if (exportSymbol) { @@ -22725,7 +23651,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { 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, 67216319 | 67901928 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -22880,8 +23806,7 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var propType = getTypeOfPropertyOfType(parentType, text); - var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); + var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); @@ -22950,7 +23875,8 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); if (declaredType) { return addOptionality(declaredType, isOptional); @@ -23003,12 +23929,18 @@ var ts; return undefined; } function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); + if (specialDeclaration) { + return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + } var types = []; + var constructorTypes; var definedInConstructor = false; var definedInMethod = false; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; + var declarationInConstructor = false; var expression = declaration.kind === 198 ? declaration : declaration.kind === 183 ? ts.getAncestor(declaration, 198) : undefined; @@ -23016,7 +23948,11 @@ var ts; return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { - if (ts.getThisContainer(expression, false).kind === 154) { + var thisContainer = ts.getThisContainer(expression, false); + declarationInConstructor = thisContainer.kind === 154 || + thisContainer.kind === 232 || + (thisContainer.kind === 190 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + if (declarationInConstructor) { definedInConstructor = true; } else { @@ -23036,11 +23972,33 @@ var ts; } } else if (!jsDocType) { - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); + var anyedType = type_2; + if (isEmptyArrayLiteralType(type_2)) { + anyedType = anyArrayType; + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + } + types.push(anyedType); + if (declarationInConstructor) { + (constructorTypes || (constructorTypes = [])).push(anyedType); + } } } - var type = jsDocType || getUnionType(types, 2); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + var type = jsDocType; + if (!type) { + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 | 16777216)); }) ? constructorTypes : types; + type = getUnionType(sourceTypes, 2); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~12288); }) === neverType) { + if (noImplicitAny) { + reportImplicitAnyError(symbol.valueDeclaration, anyType); + } + return anyType; + } + return widened; } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -23057,11 +24015,11 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var hasComputedProperties = false; + var objectFlags = 128; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (isComputedNonLiteralName(name)) { - hasComputedProperties = true; + objectFlags |= 512; return; } if (e.dotDotDotToken) { @@ -23076,12 +24034,11 @@ var ts; members.set(symbol.escapedName, symbol); }); var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 33554432; + result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; } - if (hasComputedProperties) { - result.objectFlags |= 512; - } return result; } function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { @@ -23303,7 +24260,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 107455 + links.type = targetSymbol.flags & 67216319 ? getTypeOfSymbol(targetSymbol) : unknownType; } @@ -23638,7 +24595,7 @@ 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); + var baseSymbol = resolveEntityName(node.expression, 67901928, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -23940,7 +24897,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 107455) { + if (symbolFlags & 67216319) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; @@ -23967,8 +24924,17 @@ var ts; error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); lateSymbol = createSymbol(0, memberName, 1024); } + var symbolLinks_1 = getSymbolLinks(lateSymbol); + if (!symbolLinks_1.nameType) { + symbolLinks_1.nameType = type; + } addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); - lateSymbol.parent = parent; + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } return links.resolvedSymbol = lateSymbol; } } @@ -24151,7 +25117,7 @@ var ts; } return [signature]; } - var result = undefined; + var result; for (var i = 0; i < signatureLists.length; i++) { var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); if (!match) { @@ -24163,7 +25129,7 @@ var ts; } function getUnionSignatures(types, kind) { var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); - var result = undefined; + var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; @@ -24279,7 +25245,7 @@ var ts; } else { var members = emptySymbols; - var stringIndexInfo = undefined; + var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); } @@ -24359,11 +25325,10 @@ var ts; if (typeof propertySymbolOrIndex === "object") { propertySymbol = propertySymbolOrIndex; } - var iterationMapper = createTypeMapper([typeParameter], [t]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = ts.escapeLeadingUnderscores(t.value); + var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 || !(templateModifiers & 8) && modifiersProp && modifiersProp.flags & 16777216); @@ -24377,7 +25342,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } - prop.syntheticLiteralTypeOrigin = t; + prop.nameType = t; members.set(propName, prop); } else if (t.flags & (1 | 2)) { @@ -24547,16 +25512,14 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getDefaultConstraintOfConditionalType(type) { - return getUnionType([type.trueType, type.falseType]); + return getUnionType([getInferredTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); } function getConstraintOfDistributiveConditionalType(type) { - if (isDistributiveConditionalType(type)) { + if (type.root.isDistributive) { var constraint = getConstraintOfType(type.checkType); if (constraint) { - var target = type.target || type; - var mapper = createTypeMapper([target.checkType], [constraint]); - var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper; - return instantiateType(target, combinedMapper); + var mapper = createTypeMapper([type.root.checkType], [constraint]); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); } } return undefined; @@ -24564,17 +25527,23 @@ var ts; function getConstraintOfConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } - function getBaseConstraintOfType(type) { + function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { if (type.flags & (7372800 | 393216)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 524288) { + } + function getBaseConstraintOfType(type) { + var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); + if (!constraint && type.flags & 524288) { return stringType; } - return undefined; + return constraint; + } + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; } function hasNonCircularBaseConstraint(type) { return getResolvedBaseConstraint(type) !== circularConstraintType; @@ -24609,8 +25578,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -24633,7 +25602,8 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 2097152) { - return getBaseConstraint(getConstraintOfConditionalType(t)); + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); } if (t.flags & 4194304) { return getBaseConstraint(t.substitute); @@ -24725,7 +25695,7 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; + var commonType; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; if (prop.declarations) { @@ -24841,23 +25811,11 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 279) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 279; - } - } - } - } + return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 279 + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 279; + })); } function tryFindAmbientModule(moduleName, withAugmentations) { if (ts.isExternalModuleNameRelative(moduleName)) { @@ -24941,16 +25899,20 @@ var ts; var parameters = []; var hasLiteralTypes = false; var minArgumentCount = 0; - var thisParameter = undefined; + var thisParameter = void 0; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJavaScriptFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); 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); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -24965,8 +25927,8 @@ var ts; } var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -24991,14 +25953,14 @@ var ts; return links.resolvedSignature; } function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (!containsArgumentsReference(declaration)) { + return false; + } var lastParam = ts.lastOrUndefined(declaration.parameters); - var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); var lastParamVariadicType = 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; @@ -25061,29 +26023,15 @@ var ts; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; - switch (node.kind) { - case 162: - case 163: - case 232: - case 153: - case 152: - case 154: - case 157: - case 158: - case 159: - case 155: - case 156: - case 190: - case 191: - case 280: - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); + if (!ts.isFunctionLike(node)) + continue; + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + continue; + } } + result.push(getSignatureFromDeclaration(node)); } return result; } @@ -25179,7 +26127,10 @@ var ts; return instantiation; } function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); } function getErasedSignature(signature) { return signature.typeParameters ? @@ -25435,20 +26386,19 @@ var ts; var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 32768 ? getConstrainedTypeParameter(res, node) : res : + res.flags & 32768 ? getConstrainedTypeVariable(res, node) : res : unknownType; } - if (!(symbol.flags & 107455 && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67216319 && isJSDocTypeReference(node))) { return unknownType; } + var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + var referenceType = valueType.symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType || assignedType) { + return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; } - resolveTypeReferenceName(getTypeReferenceName(node), 793064); + resolveTypeReferenceName(getTypeReferenceName(node), 67901928); return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -25464,24 +26414,33 @@ var ts; return getInferredClassType(symbol); } } - function getSubstitutionType(typeParameter, substitute) { + function getSubstitutionType(typeVariable, substitute) { var result = createType(4194304); - result.typeParameter = typeParameter; + result.typeVariable = typeVariable; result.substitute = substitute; return result; } - function getConstrainedTypeParameter(typeParameter, node) { + function isUnaryTupleTypeNode(node) { + return node.kind === 167 && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { var constraints; while (ts.isPartOfTypeNode(node)) { var parent = node.parent; if (parent.kind === 170 && node === parent.trueType) { - if (getTypeFromTypeNode(parent.checkType) === typeParameter) { - constraints = ts.append(constraints, getTypeFromTypeNode(parent.extendsType)); + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); } } node = parent; } - return constraints ? getSubstitutionType(typeParameter, getIntersectionType(ts.append(constraints, typeParameter))) : typeParameter; + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { return node.flags & 1048576 && node.kind === 161; @@ -25549,10 +26508,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 793064; + var meaning = 67901928; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 107455; + meaning |= 67216319; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -25601,10 +26560,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67216319, 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, 67901928, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name, false); @@ -25654,14 +26613,9 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064, undefined); + var symbol = getGlobalSymbol(name, 67901928, undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } - function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); - return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); - } function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; } @@ -25761,6 +26715,8 @@ var ts; } else if (flags & 1) { includes |= 1; + if (type === wildcardType) + includes |= 4096; } else if (!strictNullChecks && flags & 12288) { if (flags & 4096) @@ -25868,7 +26824,7 @@ var ts; var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); if (includes & 1) { - return anyType; + return includes & 4096 ? wildcardType : anyType; } switch (unionReduction) { case 1: @@ -25952,6 +26908,8 @@ var ts; } else if (flags & 1) { includes |= 1; + if (type === wildcardType) + includes |= 4096; } else if (flags & 16384) { includes |= 8; @@ -25990,7 +26948,7 @@ var ts; return neverType; } if (includes & 1) { - return anyType; + return includes & 4096 ? wildcardType : anyType; } if (includes & 1024 && !(includes & 512)) { typeSet.push(emptyObjectType); @@ -26030,19 +26988,29 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ? - neverType : - getLiteralType(ts.symbolName(prop)); + var links = getSymbolLinks(getLateBoundSymbol(prop)); + if (!links.nameType) { + if (links.target && links.target !== unknownSymbol && links.target !== resolvingSymbol && links.target.escapedName === prop.escapedName) { + links.nameType = getLiteralTypeFromPropertyName(links.target); + } + else { + links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ? + neverType : + getLiteralType(ts.symbolName(prop)); + } + } + return links.nameType; } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 7372800) ? getIndexTypeForGenericType(type) : - ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : - type === wildcardType ? wildcardType : - type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : - getLiteralTypeFromPropertyNames(type); + return type.flags & 262144 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) : + maybeTypeOfKind(type, 7372800) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); @@ -26105,6 +27073,9 @@ var ts; } return indexInfo.type; } + if (indexType.flags & 16384) { + return neverType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (getIndexTypeOfType(objectType, 1)) { @@ -26188,10 +27159,13 @@ var ts; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper; + var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 184) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; @@ -26221,7 +27195,13 @@ var ts; function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 1048576 && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; } return links.resolvedType; } @@ -26237,57 +27217,57 @@ var ts; } return links.resolvedType; } - function getActualTypeParameter(type) { - return type.flags & 4194304 ? type.typeParameter : type; + function getActualTypeVariable(type) { + return type.flags & 4194304 ? type.typeVariable : type; } - function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) { - var type = createType(2097152); - type.checkType = checkType; - type.extendsType = extendsType; - type.trueType = trueType; - type.falseType = falseType; - type.inferTypeParameters = inferTypeParameters; - type.target = target; - type.mapper = mapper; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - return type; - } - function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) { - var extendsType = instantiateType(baseExtendsType, mapper); - if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) { - return instantiateType(baseFalseType, mapper); + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; } + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088); var combinedMapper; - if (inferTypeParameters) { - var inferences = ts.map(inferTypeParameters, createInferenceInfo); - inferTypes(inferences, checkType, extendsType, 8 | 16); - var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; }); - var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes); - combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, undefined, 0); + if (!isDeferred) { + inferTypes(context.inferences, checkType, extendsType, 32 | 64); + } + combinedMapper = combineTypeMappers(mapper, context); } - if (checkType.flags & 1 || (checkType.flags & 16384 && !(extendsType.flags & 16384))) { - return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]); + if (!isDeferred) { + if (checkType.flags & 1) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } } - var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType; - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) { - return instantiateType(baseTrueType, combinedMapper || mapper); - } - var erasedCheckType = getActualTypeParameter(checkType); - var trueType = instantiateType(baseTrueType, mapper); - var falseType = instantiateType(baseFalseType, mapper); - var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 ? 1 : 0; - var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive; - var cached = conditionalTypes.get(id); - if (cached) { - return cached; - } - var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper)); - conditionalTypes.set(id, result); + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(2097152); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); return result; } - function isDistributiveConditionalType(type) { - return !!((type.target || type).checkType.flags & 32768); + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferredTrueTypeFromConditionalType(type) { + return type.combinedMapper ? + type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper)) : + getTrueTypeFromConditionalType(type); } function getInferTypeParameters(node) { var result; @@ -26303,7 +27283,28 @@ var ts; function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), undefined, undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var checkType = getTypeFromTypeNode(node.checkType); + var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var allOuterTypeParameters = getOuterTypeParameters(node, true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 32768), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: getAliasSymbolForTypeNode(node), + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } } return links.resolvedType; } @@ -26547,9 +27548,10 @@ var ts; return getTypeFromIntersectionTypeNode(node); case 277: return getTypeFromJSDocNullableTypeNode(node); + case 279: + return addOptionality(getTypeFromTypeNode(node.type)); case 172: case 278: - case 279: case 274: return getTypeFromTypeNode(node.type); case 281: @@ -26630,14 +27632,18 @@ var ts; return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { - return !!mapper.signature; + return !!mapper.typeParameters; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { @@ -26738,8 +27744,8 @@ var ts; } 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 === 211 ? "quit" : n === container_1; })) { + var container_2 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 211 ? "quit" : n === container_2; })) { return ts.forEachChild(node, containsReference); } } @@ -26789,19 +27795,29 @@ var ts; return result; } function getConditionalTypeInstantiation(type, mapper) { - var target = type.target || type; - var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - if (isDistributiveConditionalType(target)) { - var checkType_1 = target.checkType; - var instantiatedType = combinedMapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072) { - return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); }); + var root = type.root; + if (root.outerTypeParameters) { + var typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 | 16384)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } - return instantiateConditionalType(target, combinedMapper); - } - function instantiateConditionalType(type, mapper) { - return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments); + return getConditionalType(root, mapper); } function instantiateType(type, mapper) { if (type && mapper && mapper !== identityMapper) { @@ -26839,10 +27855,10 @@ var ts; return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } if (type.flags & 2097152) { - return getConditionalTypeInstantiation(type, mapper); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } if (type.flags & 4194304) { - return mapper(type.typeParameter); + return instantiateType(type.typeVariable, mapper); } } return type; @@ -26900,7 +27916,8 @@ var ts; return node.body.kind === 211 ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { if (type.flags & 65536) { @@ -27306,10 +28323,10 @@ var ts; target = target.regularType; } if (source.flags & 4194304) { - source = relation === definitelyAssignableRelation ? source.typeParameter : source.substitute; + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } if (target.flags & 4194304) { - target = target.typeParameter; + target = target.typeVariable; } if (source === target) return -1; @@ -27414,11 +28431,11 @@ var ts; } } if (flags & 2097152) { - if (result = isRelatedTo(source.checkType, target.checkType, false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result &= isRelatedTo(source.trueType, target.trueType, false)) { - if (result &= isRelatedTo(source.falseType, target.falseType, false)) { - if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result = isRelatedTo(source.checkType, target.checkType, false)) { + if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { return result; } } @@ -27764,20 +28781,11 @@ var ts; } } else if (source.flags & 2097152) { - if (relation !== definitelyAssignableRelation) { - var constraint = getConstraintOfDistributiveConditionalType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } if (target.flags & 2097152) { - if (isTypeIdenticalTo(source.checkType, target.checkType) && - isTypeIdenticalTo(source.extendsType, target.extendsType)) { - if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { - result &= isRelatedTo(source.falseType, target.falseType, reportErrors); + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -27785,9 +28793,21 @@ var ts; } } } - else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } } else { @@ -28075,6 +29095,10 @@ var ts; if (isIgnoredJsxProperty(source, prop, undefined)) { continue; } + var nameType = getLiteralTypeFromPropertyName(prop); + if (nameType !== undefined && !(isRelatedTo(nameType, stringType) || isRelatedTo(nameType, numberType))) { + continue; + } if (kind === 0 || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -28509,8 +29533,17 @@ var ts; ts.Debug.assert(strictNullChecks); return type.flags & 4096 ? type : getUnionType([type, undefinedType]); } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288, undefined) || unknownSymbol; + } + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 524288); + } function getNonNullableType(type) { - return strictNullChecks ? getTypeWithFacts(type, 524288) : type; + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; } function isObjectTypeWithInferableIndex(type) { return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 && @@ -28603,6 +29636,10 @@ var ts; } var result = createSymbol(4 | 16777216, name); result.type = undefinedType; + var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name)); + if (associatedKeyType.flags & 32) { + result.nameType = associatedKeyType; + } undefinedProperties.set(name, result); return result; } @@ -28689,6 +29726,7 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 198: case 151: case 150: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; @@ -28749,9 +29787,10 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, compareTypes, baseInferences) { - var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); var context = mapper; + context.typeParameters = typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -28858,7 +29897,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return getTypeFromInference(inference) || emptyObjectType; + return getTypeFromInference(inference); } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -28873,21 +29912,33 @@ var ts; } return undefined; } + function typesDefinitelyUnrelated(source, target) { + return isTupleType(source) && isTupleType(target) && getTypeReferenceArity(source) !== getTypeReferenceArity(target) || + !!getUnmatchedProperty(source, target, false) && !!getUnmatchedProperty(target, source, false); + } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : - undefined; + emptyObjectType; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; var contravariant = false; + var propagationType; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; } + if (source === wildcardType) { + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { var sourceTypes = source.aliasTypeArguments; var targetTypes = target.aliasTypeArguments; @@ -28937,14 +29988,15 @@ var ts; inference.priority = priority; } if (priority === inference.priority) { + var candidate = propagationType || source; if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, source); + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, source); + inference.candidates = ts.append(inference.candidates, candidate); } } - if (!(priority & 4) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -28973,7 +30025,10 @@ var ts; else if ((isLiteralType(source) || source.flags & 2) && target.flags & 524288) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; + var savePriority = priority; + priority |= 16; inferFromTypes(empty, target.type); + priority = savePriority; contravariant = !contravariant; } else if (source.flags & 1048576 && target.flags & 1048576) { @@ -28983,8 +30038,8 @@ var ts; else if (source.flags & 2097152 && target.flags & 2097152) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(source.trueType, target.trueType); - inferFromTypes(source.falseType, target.falseType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else if (target.flags & 393216) { var targetTypes = target.types; @@ -29015,7 +30070,7 @@ var ts; } } else { - if (!(priority && 8 && source.flags & (262144 | 7897088))) { + if (!(priority & 32 && source.flags & (262144 | 7897088))) { source = getApparentType(source); } if (source.flags & (65536 | 262144)) { @@ -29042,7 +30097,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 16) { + if (strictFunctionTypes || priority & 64) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -29083,12 +30138,15 @@ var ts; return; } if (constraintType.flags & 32768) { + var savePriority = priority; + priority |= 4; inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); return; } } - if (!getUnmatchedProperty(source, target, false) || !getUnmatchedProperty(target, source, false)) { + if (!typesDefinitelyUnrelated(source, target)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0); inferFromSignatures(source, target, 1); @@ -29182,43 +30240,54 @@ var ts; } return candidates; } + function getContravariantInference(inference) { + return inference.priority & 28 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, context, signature) { + var candidates = widenObjectLiteralCandidates(inference.candidates); + var widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var unwidenedType = context.flags & 1 || inference.priority & 28 ? + getUnionType(baseCandidates, 2) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } 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(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = context.flags & 1 || inference.priority & 4 ? - getUnionType(baseCandidates, 2) : - getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unwidenedType); - if (inferredType.flags & 16384 && inference.contraCandidates) { - inferredType = getCommonSubtype(inference.contraCandidates); + var signature = context.signature; + if (signature) { + if (inference.candidates) { + inferredType = getCovariantInference(inference, context, signature); + if (inferredType.flags & 16384 && inference.contraCandidates) { + inferredType = getContravariantInference(inference); + } } - } - else if (inference.contraCandidates) { - inferredType = getCommonSubtype(inference.contraCandidates); - } - else if (context.flags & 2) { - inferredType = silentNeverType; - } - else { - var defaultType = getDefaultFromTypeParameter(inference.typeParameter); - if (defaultType) { - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + else if (inference.contraCandidates) { + inferredType = getContravariantInference(inference); + } + else if (context.flags & 2) { + inferredType = silentNeverType; } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + } } } + else { + inferredType = getTypeFromInference(inference); + } inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -29242,7 +30311,7 @@ var ts; 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), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 67216319 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -29252,7 +30321,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -29461,8 +30530,8 @@ var ts; } if (flags & 65536) { return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; + strictNullChecks ? 1970144 : 4181984 : + strictNullChecks ? 1972176 : 4184016; } if (flags & (2048 | 4096)) { return 2457472; @@ -29474,7 +30543,7 @@ var ts; return strictNullChecks ? 1981320 : 4193160; } if (flags & 134217728) { - return strictNullChecks ? 6166480 : 8378320; + return strictNullChecks ? 1972176 : 4184016; } if (flags & 7897088) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); @@ -29482,7 +30551,7 @@ var ts; if (flags & 393216) { return getTypeFactsOfTypes(type.types); } - return 8388607; + return 4194303; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -29496,7 +30565,7 @@ var ts; } function getTypeOfDestructuredProperty(type, name) { var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || getIndexTypeOfType(type, 0) || unknownType; @@ -29672,6 +30741,9 @@ var ts; return f(type) ? type : neverType; } function mapType(type, mapper, noReductions) { + if (type.flags & 16384) { + return type; + } if (!(type.flags & 131072)) { return mapper(type); } @@ -30395,25 +31467,24 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } - function isApparentTypePosition(node) { + function isConstraintPosition(node) { var parent = node.parent; return parent.kind === 183 || parent.kind === 185 && parent.expression === node || parent.kind === 184 && parent.expression === node || - parent.kind === 207 || parent.kind === 180 && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 7372800 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288); } - function getApparentTypeForLocation(type, node) { - if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getApparentType); + function getConstraintForLocation(type, node) { + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); } return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, 67216319) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -30471,7 +31542,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3)) { @@ -30888,46 +31959,46 @@ var ts; } function getContextuallyTypedParameterType(parameter) { var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = func.parameters.indexOf(parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = func.parameters.indexOf(parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); + indexOfParameter -= 1; + } + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + if (funcHasRestParameters && + indexOfParameter === (func.parameters.length - 1) && + isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } - return undefined; } function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; @@ -31036,7 +32107,8 @@ var ts; return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; case 54: var type = getContextualType(binaryExpression); - return !type && node === right ? getTypeOfExpression(left, true) : type; + return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? + getTypeOfExpression(left, true) : type; case 53: case 26: return node === right ? getContextualType(binaryExpression) : undefined; @@ -31055,6 +32127,7 @@ var ts; case 2: case 3: case 4: + case 6: return false; default: ts.Debug.assertNever(kind); @@ -31106,7 +32179,7 @@ var ts; } function getContextualTypeForChildJsxExpression(node) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); - var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; } function getContextualTypeForJsxExpression(node) { @@ -31232,20 +32305,14 @@ var ts; return anyType; } var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } - function getJsxSignaturesParameterTypes(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, false); - } - function getJsxSignaturesParameterTypesJs(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, true); - } - function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + function getJsxSignaturesParameterTypes(valueType, isJs, context) { if (valueType.flags & 2) { return anyType; } else if (valueType.flags & 32) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = valueType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -31268,21 +32335,24 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0); + if (context.typeArguments) { + signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + } + return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0); } - function getJsxPropsTypeFromCallSignature(sig) { + function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignature(sig); - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { propsType = intersectTypes(intrinsicAttribs, propsType); } return propsType; } - function getJsxPropsTypeFromClassType(hostClassType, isJs) { + function getJsxPropsTypeFromClassType(hostClassType, isJs, context) { if (isTypeAny(hostClassType)) { return hostClassType; } - var propsName = getJsxElementPropertiesName(); + var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context)); if (propsName === undefined) { return anyType; } @@ -31299,14 +32369,14 @@ var ts; } else { var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); if (intrinsicClassAttribs !== unknownType) { var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); apparentAttributesType = intersectTypes(typeParams ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) : intrinsicClassAttribs, apparentAttributesType); } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); } @@ -31314,18 +32384,12 @@ var ts; } } } - function getJsxPropsTypeFromConstructSignatureJs(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, true); - } - function getJsxPropsTypeFromConstructSignature(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, false); - } - function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + function getJsxPropsTypeFromConstructSignature(sig, isJs, context) { var hostClassType = getReturnTypeOfSignature(sig); if (hostClassType) { - return getJsxPropsTypeFromClassType(hostClassType, isJs); + return getJsxPropsTypeFromClassType(hostClassType, isJs, context); } - return getJsxPropsTypeFromCallSignature(sig); + return getJsxPropsTypeFromCallSignature(sig, context); } function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0); @@ -31365,7 +32429,16 @@ var ts; } function getContextualSignature(node) { ts.Debug.assert(node.kind !== 153 || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); + var type; + if (ts.isInJavaScriptFile(node)) { + var jsdoc = ts.getJSDocType(node); + if (jsdoc) { + type = getTypeFromTypeNode(jsdoc); + } + } + if (!type) { + type = getContextualTypeForFunctionLikeDeclaration(node); + } if (!type) { return undefined; } @@ -31512,19 +32585,28 @@ var ts; function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createSymbolTable(); + var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; var propagatedFlags = 8388608; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 178 || contextualType.pattern.kind === 182); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node); + var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - var isInJSFile = ts.isInJavaScriptFile(node); + if (isInJSFile && node.properties.length === 0) { + var symbol = getSymbolOfNode(node); + if (symbol.exports) { + propertiesTable = symbol.exports; + symbol.exports.forEach(function (symbol) { return propertiesArray.push(getMergedSymbol(symbol)); }); + return createObjectLiteralType(); + } + } + propertiesTable = ts.createSymbolTable(); var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; @@ -31560,9 +32642,13 @@ var ts; } typeFlags |= type.flags; var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; - var prop = nameType && isTypeUsableAsLateBoundName(nameType) + var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType); + var prop = hasLateBoundName ? createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024) : createSymbol(4 | member.flags, literalName || member.escapedName); + if (hasLateBoundName) { + prop.nameType = nameType; + } if (inDestructuringPattern) { var isOptional = (memberDecl.kind === 268 && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 269 && memberDecl.objectAssignmentInitializer); @@ -31675,7 +32761,7 @@ var ts; } function checkJsxSelfClosingElement(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxElement(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); @@ -31685,14 +32771,16 @@ var ts; else { checkExpression(node.closingElement.tagName); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxFragment(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); - if (compilerOptions.jsx === 2 && compilerOptions.jsxFactory) { - error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + if (compilerOptions.jsx === 2 && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function isUnhyphenatedJsxName(name) { return !ts.stringContains(name, "-"); @@ -31720,7 +32808,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -31781,7 +32869,10 @@ var ts; if (hasSpreadAnyType) { return anyType; } - return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + if (typeToIntersect && spread !== emptyObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); result.flags |= 33554432; @@ -31807,20 +32898,19 @@ var ts; function checkJsxAttributes(node, checkMode) { return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67901928); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType; } function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); if (intrinsicElementsType !== unknownType) { if (!ts.isIdentifier(node.tagName)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); if (intrinsicProp) { links.jsxFlags |= 1; @@ -31857,23 +32947,66 @@ var ts; } } var instantiatedSignatures = []; + var candidateForTypeArgumentError; + var hasTypeArgumentError = !!node.typeArguments; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, false); + if (typeArgumentInstantiated) { + hasTypeArgumentError = false; + instantiatedSignatures.push(typeArgumentInstantiated); + } + else { + if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + candidateForTypeArgumentError = signature; + } + var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 4 : 0); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } } else { instantiatedSignatures.push(signature); } } + if (node.typeArguments && hasTypeArgumentError) { + if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true); + } + else if (node.typeArguments.length !== 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); + } + } return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); } - function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); + function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (!node.typeArguments) { + return; + } + if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + return; + } + var args = checkTypeArguments(signature, node.typeArguments, reportErrors); + if (!args) { + return; + } + return getSignatureInstantiation(signature, args, isJavascript); + } + function getJsxNamespaceAt(location) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920, undefined, namespaceName, false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920); + if (candidate) { + return candidate; + } + } + return getGlobalSymbol(JsxNames.JSX, 1920, undefined); + } + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928); var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); if (propertiesOfJsxElementAttribPropInterface) { @@ -31889,19 +33022,11 @@ var ts; } return undefined; } - function getJsxElementPropertiesName() { - if (!_hasComputedJsxElementPropertiesName) { - _hasComputedJsxElementPropertiesName = true; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } - function getJsxElementChildrenPropertyName() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - return _jsxElementChildrenPropertyName; + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } function getApparentTypeOfJsxPropsType(propsType) { if (!propsType) { @@ -31920,7 +33045,7 @@ var ts; function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 131072)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); if (callSignature !== unknownSignature) { @@ -31928,7 +33053,7 @@ var ts; var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { paramType = intersectTypes(intrinsicAttributes, paramType); } @@ -31942,7 +33067,7 @@ var ts; function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 131072)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { var candidatesOutArray = []; getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); @@ -31973,7 +33098,7 @@ var ts; if (!result) { result = allMatchingAttributesType; } - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { result = intersectTypes(intrinsicAttributes, result); } @@ -31993,7 +33118,7 @@ var ts; return anyType; } else if (elementType.flags & 32) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -32018,7 +33143,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); @@ -32038,7 +33163,7 @@ var ts; return links.resolvedJsxElementAttributesType; } function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -32061,36 +33186,30 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.escapedText); return prop || unknownSymbol; } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === unknownType) + return undefined; + return type; } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); } - return deferredJsxStatelessElementType; } - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; } function checkJsxPreconditions(errorNode) { if ((compilerOptions.jsx || 0) === 0) { error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); } - if (getJsxGlobalElementType() === undefined) { + if (getJsxElementTypeAt(errorNode) === undefined) { if (noImplicitAny) { error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); } @@ -32103,9 +33222,9 @@ var ts; } checkJsxPreconditions(node); var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = getJsxNamespace(); + var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 107455, reactRefErr, reactNamespace, true); + var reactSym = resolveName(reactLocation, reactNamespace, 67216319, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = 67108863; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -32145,7 +33264,7 @@ var ts; getCustomJsxElementAttributesType(openingLikeElement, false); var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement)))); } else { var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); @@ -32184,7 +33303,9 @@ var ts; return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || + ts.getCheckFlags(symbol) & 4 || + ts.isInJavaScriptFile(symbol.valueDeclaration) && ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(symbol.valueDeclaration))); } function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); @@ -32315,7 +33436,7 @@ var ts; return unknownType; } } - propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } if (node.kind !== 183 || assignmentKind === 1 || @@ -32413,7 +33534,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455); + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 67216319); return suggestion && ts.symbolName(suggestion); } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { @@ -32425,6 +33546,10 @@ var ts; }); return result && ts.symbolName(result); } + function getSuggestionForNonexistentModule(name, targetModule) { + var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475); + return suggestion && ts.symbolName(suggestion); + } function getSpellingSuggestionForName(name, symbols, meaning) { var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; @@ -32434,7 +33559,8 @@ var ts; for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; var candidateName = ts.symbolName(candidate); - if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + if (candidateName.charCodeAt(0) === 34 + || !(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { continue; } var candidateNameLowerCase = candidateName.toLowerCase(); @@ -32522,15 +33648,23 @@ var ts; return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) && (!(property.flags & 8192) || isValidMethodAccess(property, type)); } - function isValidMethodAccess(method, type) { + function isValidMethodAccess(method, actualThisType) { var propType = getTypeOfFuncClassEnumModule(method); var signatures = getSignaturesOfType(getNonNullableType(propType), 0); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { - var thisType = getThisTypeOfSignature(sig); - return !thisType || isTypeAssignableTo(type, thisType); + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); }); } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type === unknownType || isTypeAny(type)) { return true; @@ -32737,11 +33871,7 @@ var ts; typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } - var numTypeParameters = ts.length(signature.typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { + if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { return false; } if (spreadArgIndex >= 0) { @@ -32754,6 +33884,12 @@ var ts; var hasEnoughArguments = argCount >= signature.minArgumentCount; return callIsIncomplete || hasEnoughArguments; } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } function getSingleCallSignature(type) { if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); @@ -32765,12 +33901,12 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature, 1, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 1, compareTypes); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { 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)); } @@ -32799,7 +33935,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); @@ -33077,6 +34213,17 @@ var ts; return arg; } } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 187; var isDecorator = node.kind === 149; @@ -33132,21 +34279,13 @@ var ts; 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; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); - } - var paramCount = min < max ? min + "-" + max : min; - diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { - var sig = signatures_6[_a]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -33210,7 +34349,7 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + createInferenceContext(originalCandidate.typeParameters, originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : undefined; while (true) { candidate = originalCandidate; @@ -33535,19 +34674,49 @@ var ts; return false; } function getJavaScriptClassType(symbol) { - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + var initializer = ts.getDeclaredJavascriptInitializer(symbol.valueDeclaration); + if (initializer) { + symbol = getSymbolOfNode(initializer); } + var inferred; if (isJavaScriptConstructor(symbol.valueDeclaration)) { - return getInferredClassType(symbol); + inferred = getInferredClassType(symbol); } - if (symbol.flags & 3) { - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { - return getInferredClassType(valueType.symbol); + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + if (assignmentSymbol) { + var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); + if (prototype) { + return checkExpression(prototype); } } } + function getAssignedJavascriptPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 183) { + parent = parent.parent; + } + return parent && ts.isBinaryExpression(parent) && + ts.isPrototypeAccess(parent.left) && + parent.operatorToken.kind === 58 && + ts.isObjectLiteralExpression(parent.right) && + parent.right; + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -33611,7 +34780,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 107455, undefined, undefined, false); + return globalESSymbol === resolveName(left, "Symbol", 67216319, undefined, undefined, false); } function checkImportCallExpression(node) { if (!checkGrammarArguments(node.arguments)) @@ -33665,8 +34834,8 @@ var ts; return false; } if (!ts.isIdentifier(node.expression)) - throw ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined, true); + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319, undefined, undefined, true); if (!resolvedRequire) { return true; } @@ -33907,24 +35076,20 @@ var ts; } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); + var isAsync = (ts.getFunctionFlags(func) & 2) !== 0; ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); - } - if (functionFlags & 2) { - 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); - } - ts.pushIfUnique(aggregatedTypes, type); - } + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); }); return aggregatedTypes; } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpressionCached(node.expression, checkMode) : undefinedWideningType; + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.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); + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; @@ -33972,7 +35137,8 @@ var ts; if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -34024,7 +35190,6 @@ var ts; function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 153 || ts.isObjectLiteralMethod(node)); if (checkMode === 1 && isContextSensitive(node)) { - checkNodeDeferred(node); return anyFunctionType; } var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); @@ -34500,6 +35665,9 @@ var ts; return (target.flags & 12288) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + return checkExpression(node.right, checkMode); + } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { @@ -34691,42 +35859,28 @@ var ts; error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); } } - if (node.expression) { - var func = ts.getContainingFunction(node); - var functionFlags = func && ts.getFunctionFlags(func); - if (node.asteriskToken) { - if ((functionFlags & 3) === 3 && - languageVersion < 6) { - checkExternalEmitHelpers(node, 26624); - } - if ((functionFlags & 3) === 1 && - languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256); - } + var func = ts.getContainingFunction(node); + var functionFlags = func ? ts.getFunctionFlags(func) : 0; + if (!(functionFlags & 1)) { + return anyType; + } + if (node.asteriskToken) { + if ((functionFlags & 3) === 3 && + languageVersion < 6) { + checkExternalEmitHelpers(node, 26624); } - if (functionFlags & 1) { - var expressionType = checkExpressionCached(node.expression); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); - } - var returnType = ts.getEffectiveReturnTypeNode(func); - if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2) !== 0) || anyType; - if (nodeIsYieldStar) { - checkTypeAssignableTo(functionFlags & 2 - ? 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); - } - else { - checkTypeAssignableTo(functionFlags & 2 - ? 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); - } - } + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256); } } + var isAsync = (functionFlags & 2) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + var returnType = ts.getEffectiveReturnTypeNode(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; + checkTypeAssignableTo(yieldedType, signatureElementType, node.expression || node, undefined); + } return anyType; } function checkConditionalExpression(node, checkMode) { @@ -34778,10 +35932,27 @@ var ts; return node.kind === 188 || node.kind === 206; } function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, true); - return ts.getCombinedNodeFlags(declaration) & 2 || + var inJs = ts.isInJavaScriptFile(declaration); + var initializer = inJs && ts.getDeclaredJavascriptInitializer(declaration) || declaration.initializer; + var type = getTypeOfExpression(initializer, true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 || (ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (inJs) { + if (widened.flags & 12288) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyType); + } + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyArrayType); + } + return anyArrayType; + } + } + return widened; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { @@ -35936,7 +37107,7 @@ 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, 67216319, true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; if (promiseConstructorType === unknownType) { if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { @@ -35956,7 +37127,7 @@ var ts; return unknownType; } var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; @@ -36004,7 +37175,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 ? 793064 : 1920) | 2097152; + var meaning = (typeName.kind === 71 ? 67901928 : 1920) | 2097152; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 @@ -36133,7 +37304,17 @@ var ts; 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 === 145 ? node.name.right : node.name)); + var decl = ts.getHostSignatureFromJSDoc(node); + if (decl) { + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 145 ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 145 ? node.name.right : node.name)); + } + } } } function checkJSDocAugmentsTag(node) { @@ -36142,7 +37323,7 @@ var ts; error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } - var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 285); + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); 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); @@ -36298,14 +37479,14 @@ var ts; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); + diagnostics.add(ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 && ts.idText(node).charCodeAt(0) === 95; + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { @@ -36360,18 +37541,59 @@ var ts; } function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { + var unusedImports_1 = ts.createMap(); 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.symbolName(local)); + if (local.isReferenced || local.exportSymbol) + return; + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + var importClause = importClauseFromImported(declaration); + var key = String(getNodeId(importClause)); + var group_1 = unusedImports_1.get(key); + if (group_1) { + group_1[1].push(declaration); } + else { + unusedImports_1.set(key, [importClause, [declaration]]); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local)); } } }); + unusedImports_1.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name)); + } + } + else if (unuseds.length === 1) { + error(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)); + } + else { + error(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)); + } + }); } } + function isImportedDeclaration(node) { + return node.kind === 243 || node.kind === 246 || node.kind === 244; + } + function importClauseFromImported(decl) { + return decl.kind === 243 ? decl : decl.kind === 244 ? decl.parent : decl.parent.parent; + } + function forEachImportedDeclaration(importClause, cb) { + var defaultName = importClause.name, namedBindings = importClause.namedBindings; + return (defaultName && cb(importClause)) || + namedBindings && (namedBindings.kind === 244 ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); + } function checkBlock(node) { if (node.kind === 211) { checkGrammarStatementInAmbientContext(node); @@ -36389,7 +37611,7 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasRestParameter(node) || node.flags & 2097152 || ts.nodeIsMissing(node.body)) { + if (languageVersion >= 2 || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 2097152 || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -36420,12 +37642,12 @@ var ts; return true; } function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { + if (languageVersion <= 1 && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_this")) { potentialThisCollisions.push(node); } } function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + if (languageVersion <= 1 && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_newTarget")) { potentialNewTargetCollisions.push(node); } } @@ -36458,6 +37680,9 @@ var ts; }); } function checkCollisionWithCapturedSuperVariable(node, name) { + if (languageVersion >= 2 || compilerOptions.noEmit) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } @@ -36476,7 +37701,7 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { - if (modulekind >= ts.ModuleKind.ES2015) { + if (modulekind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { return; } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { @@ -36491,7 +37716,7 @@ var ts; } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1) { @@ -36512,7 +37737,7 @@ var ts; var symbol = getSymbolOfNode(node); if (symbol.flags & 1) { if (!ts.isIdentifier(node.name)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && @@ -36549,7 +37774,7 @@ var ts; return visit(n.expression); } else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined, false); + var symbol = resolveName(n, n.escapedText, 67216319 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -36646,7 +37871,8 @@ var ts; var type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 219) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); + var initializer = ts.isInJavaScriptFile(node) && ts.getDeclaredJavascriptInitializer(node) || node.initializer; + checkTypeAssignableTo(checkExpressionCached(initializer), type, node, undefined); checkParameterInitializer(node); } } @@ -37126,8 +38352,7 @@ var ts; return "quit"; } if (current.kind === 226 && 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)); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } }); @@ -37445,7 +38670,7 @@ var ts; var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && baseProp) { - var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) { issuedMemberError = true; } @@ -37997,7 +39222,10 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { + if (ts.nodeIsMissing(moduleName)) { + return false; + } + if (!ts.isStringLiteral(moduleName)) { error(moduleName, ts.Diagnostics.String_literal_expected); return false; } @@ -38008,7 +39236,7 @@ var ts; ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { if (!isTopLevelInExternalModuleAugmentation(node)) { error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); return false; @@ -38020,8 +39248,8 @@ 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) | + var excludedMeanings = (symbol.flags & (67216319 | 1048576) ? 67216319 : 0) | + (symbol.flags & 67901928 ? 67901928 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 250 ? @@ -38031,7 +39259,7 @@ var ts; } if (compilerOptions.isolatedModules && node.kind === 250 - && !(target.flags & 107455) + && !(target.flags & 67216319) && !(node.flags & 2097152)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -38080,13 +39308,13 @@ var ts; if (node.moduleReference.kind !== 252) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 107455) { + if (target.flags & 67216319) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 67216319 | 1920).flags & 1920)) { 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 & 67901928) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -38140,7 +39368,7 @@ var ts; } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined, true); + var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 | 67901928 | 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.idText(exportedName)); } @@ -38403,6 +39631,12 @@ var ts; checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } @@ -38425,15 +39659,19 @@ var ts; 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)) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { return createArrayType(type); } } } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } return addOptionality(type); } function checkNodeDeferred(node) { @@ -38488,6 +39726,7 @@ var ts; checkUnusedIdentifiers(); } deferredNodes = undefined; + seenDeferredUnusedIdentifiers.clear(); deferredUnusedIdentifierNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); @@ -38569,7 +39808,7 @@ var ts; case 233: case 234: if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928); } break; case 190: @@ -38697,7 +39936,7 @@ var ts; } } if (entityName.parent.kind === 247 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 2097152); + return resolveEntityName(entityName, 67216319 | 67901928 | 1920 | 2097152); } if (entityName.kind !== 183 && isInRightSideOfImportOrExportAssignment(entityName)) { var importEqualsDeclaration = ts.getAncestor(entityName, 241); @@ -38710,9 +39949,9 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 205) { - meaning = 793064; + meaning = 67901928; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455; + meaning |= 67216319; } } else { @@ -38741,7 +39980,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 107455, false, true); + return resolveEntityName(entityName, 67216319, false, true); } else if (entityName.kind === 183 || entityName.kind === 145) { var links = getNodeLinks(entityName); @@ -38758,7 +39997,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 161 ? 793064 : 1920; + var meaning = entityName.parent.kind === 161 ? 67901928 : 1920; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 260) { @@ -38846,14 +40085,14 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 269) { - return resolveEntityName(location.name, 107455 | 2097152); + return resolveEntityName(location.name, 67216319 | 2097152); } return undefined; } 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, 67216319 | 67901928 | 1920 | 2097152); } function getTypeOfNode(node) { if (node.flags & 4194304) { @@ -38999,13 +40238,13 @@ var ts; var symbolLinks = getSymbolLinks(moduleSymbol); if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 107455) + ? !!(moduleSymbol.flags & 67216319) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 107455); + return s && !!(s.flags & 67216319); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -39041,7 +40280,7 @@ var ts; node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); - if (isNonLocalAlias(symbol, 107455)) { + if (isNonLocalAlias(symbol, 67216319)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -39054,7 +40293,7 @@ var ts; 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, 67216319, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } else if (nodeLinks_1.flags & 131072) { @@ -39126,7 +40365,7 @@ var ts; if (target === unknownSymbol) { return true; } - return target.flags & 107455 && + return target.flags & 67216319 && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -39139,7 +40378,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 && target.flags & 107455) { + if (target && ts.getModifierFlags(node) & 1 && target.flags & 67216319) { return true; } } @@ -39150,6 +40389,8 @@ var ts; } function isImplementationOfOverload(node) { if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); return signaturesOfSymbol.length > 1 || @@ -39209,8 +40450,8 @@ var ts; if (!location) return ts.TypeReferenceSerializationKind.Unknown; } - var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); - var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); + var valueSymbol = resolveEntityName(typeName, 67216319, true, false, location); + var typeSymbol = resolveEntityName(typeName, 67901928, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -39259,7 +40500,11 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { + declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(119); + } var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 | 131072)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) @@ -39268,18 +40513,26 @@ var ts; type.symbol === symbol) { flags |= 1048576; } - if (flags & 131072) { + if (addUndefined) { type = getOptionalType(type); } - typeToString(type, enclosingDeclaration, flags | 1024, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { + signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(119); + } var signature = getSignatureFromDeclaration(signatureDeclaration); - typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, writer); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, tracker); } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { + expr = ts.getParseTreeNode(expr, ts.isExpression); + if (!expr) { + return ts.createToken(119); + } var type = getWidenedType(getRegularTypeOfExpression(expr)); - typeToString(type, enclosingDeclaration, flags | 1024, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -39296,7 +40549,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined, true); + return resolveName(location, reference.escapedText, 67216319 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -39317,9 +40570,12 @@ var ts; } return false; } - function writeLiteralConstValue(node, writer) { + function literalTypeToNode(type) { + return ts.createLiteral(type.value); + } + function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); + return literalTypeToNode(type); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -39357,9 +40613,10 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -39381,16 +40638,15 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024); }, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } }; function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { return undefined; } var meaning = (node.kind === 183) || (node.kind === 71 && isInTypeQuery(node)) - ? 107455 | 1048576 - : 793064 | 1920; + ? 67216319 | 1048576 + : 67901928 | 1920; var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -39445,7 +40701,7 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 237 ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); if (!moduleSymbol) { return undefined; @@ -39530,7 +40786,7 @@ var ts; for (var helper = 1; helper <= 65536; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319); 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); } @@ -40137,6 +41393,7 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; @@ -40499,8 +41756,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } } @@ -40628,8 +41885,8 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { 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)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), 0, message, arg0, arg1, arg2)); return true; } } @@ -40712,14 +41969,14 @@ var ts; } ts.updateNode = updateNode; function createNodeArray(elements, hasTrailingComma) { - if (elements) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else { if (ts.isNodeArray(elements)) { return elements; } } - else { - elements = []; - } var array = elements; array.pos = -1; array.end = -1; @@ -40743,7 +42000,7 @@ var ts; return clone; } ts.getSynthesizedClone = getSynthesizedClone; - function createLiteral(value) { + function createLiteral(value, isSingleQuote) { if (typeof value === "number") { return createNumericLiteral(value + ""); } @@ -40751,7 +42008,10 @@ var ts; return value ? createTrue() : createFalse(); } if (ts.isString(value)) { - return createStringLiteral(value); + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; } return createLiteralFromNode(value); } @@ -40822,6 +42082,14 @@ var ts; return name; } ts.createUniqueName = createUniqueName; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 5; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateFlags = 4; @@ -40858,6 +42126,48 @@ var ts; return createSynthesizedNode(86); } ts.createFalse = createFalse; + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1) { + result.push(createModifier(84)); + } + if (flags & 2) { + result.push(createModifier(124)); + } + if (flags & 512) { + result.push(createModifier(79)); + } + if (flags & 2048) { + result.push(createModifier(76)); + } + if (flags & 4) { + result.push(createModifier(114)); + } + if (flags & 8) { + result.push(createModifier(112)); + } + if (flags & 16) { + result.push(createModifier(113)); + } + if (flags & 128) { + result.push(createModifier(117)); + } + if (flags & 32) { + result.push(createModifier(115)); + } + if (flags & 64) { + result.push(createModifier(132)); + } + if (flags & 256) { + result.push(createModifier(120)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; function createQualifiedName(left, right) { var node = createSynthesizedNode(145); node.left = left; @@ -40872,9 +42182,15 @@ var ts; : node; } ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26) || + expression.kind === 296 ? + createParen(expression) : + expression; + } function createComputedPropertyName(expression) { var node = createSynthesizedNode(146); - node.expression = expression; + node.expression = parenthesizeForComputedName(expression); return node; } ts.createComputedPropertyName = createComputedPropertyName; @@ -42493,31 +43809,35 @@ var ts; : node; } ts.updateJsxElement = updateJsxElement; - function createJsxSelfClosingElement(tagName, attributes) { + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(254); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxSelfClosingElement = createJsxSelfClosingElement; - function updateJsxSelfClosingElement(node, tagName, attributes) { + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxSelfClosingElement(tagName, attributes), node) + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; - function createJsxOpeningElement(tagName, attributes) { + function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(255); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxOpeningElement = createJsxOpeningElement; - function updateJsxOpeningElement(node, tagName, attributes) { + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxOpeningElement(tagName, attributes), node) + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxOpeningElement = updateJsxOpeningElement; @@ -42657,7 +43977,7 @@ var ts; var node = createSynthesizedNode(268); node.name = asName(name); node.questionToken = undefined; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); return node; } ts.createPropertyAssignment = createPropertyAssignment; @@ -42708,8 +44028,11 @@ var ts; : node; } ts.updateEnumMember = updateEnumMember; - function updateSourceFileNode(node, statements) { - if (node.statements !== statements) { + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences)) { var updated = createSynthesizedNode(272); updated.flags |= node.flags; updated.statements = createNodeArray(statements); @@ -42717,18 +44040,15 @@ var ts; updated.fileName = node.fileName; updated.path = node.path; updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; - if (node.referencedFiles !== undefined) - updated.referencedFiles = node.referencedFiles; - if (node.typeReferenceDirectives !== undefined) - updated.typeReferenceDirectives = node.typeReferenceDirectives; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; - if (node.isDeclarationFile !== undefined) - updated.isDeclarationFile = node.isDeclarationFile; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; if (node.hasNoDefaultLib !== undefined) @@ -42765,6 +44085,12 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; return updateNode(updated, node); } return node; @@ -43186,7 +44512,8 @@ var ts; requestEmitHelper: ts.noop, resumeLexicalEnvironment: ts.noop, startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, }; function createTypeCheck(value, tag) { return tag === "undefined" @@ -43307,7 +44634,7 @@ var ts; var valuesHelper = { name: "typescript:values", scoped: false, - text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };\n " + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" }; function createValuesHelper(context, expression, location) { context.requestEmitHelper(valuesHelper); @@ -43317,7 +44644,7 @@ var ts; var readHelper = { name: "typescript:read", scoped: false, - text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };\n " + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" }; function createReadHelper(context, iteratorRecord, count, location) { context.requestEmitHelper(readHelper); @@ -43372,7 +44699,7 @@ var ts; } ts.restoreEnclosingLabel = restoreEnclosingLabel; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { - var target = skipParentheses(node); + var target = ts.skipParentheses(node); switch (target.kind) { case 71: return cacheIdentifiers; @@ -43956,7 +45283,7 @@ var ts; do { previousNode = node; if (kinds & 1) { - node = skipParentheses(node); + node = ts.skipParentheses(node); } if (kinds & 2) { node = skipAssertions(node); @@ -43968,13 +45295,6 @@ var ts; return node; } ts.skipOuterExpressions = skipOuterExpressions; - function skipParentheses(node) { - while (node.kind === 189) { - node = node.expression; - } - return node; - } - ts.skipParentheses = skipParentheses; function skipAssertions(node) { while (ts.isAssertionExpression(node) || node.kind === 207) { node = node.expression; @@ -44578,9 +45898,9 @@ var ts; case 253: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 254: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 255: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 256: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 257: @@ -45084,9 +46404,10 @@ var ts; var Debug; (function (Debug) { var isDebugInfoEnabled = false; - Debug.failBadSyntaxKind = Debug.shouldAssert(1) - ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } - : ts.noop; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; Debug.assertEachNode = Debug.shouldAssert(1) ? 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; @@ -45186,7 +46507,7 @@ var ts; var uniqueExports = ts.createMap(); var exportedNames; var hasExportDefault = false; - var exportEquals = undefined; + var exportEquals; var hasExportStarsToExportValues = false; var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -45825,8 +47146,7 @@ var ts; case 210: return node; default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { @@ -45934,8 +47254,7 @@ var ts; case 241: return visitImportEqualsDeclaration(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitSourceFile(node) { @@ -46174,7 +47493,7 @@ var ts; ts.setEmitFlags(propertyName, 1536 | 48); var localName = ts.getMutableClone(name); ts.setEmitFlags(localName, 1536); - return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1))); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536)); } function getInitializedProperties(node, isStatic) { return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); @@ -46543,10 +47862,8 @@ var ts; case 86: return ts.createIdentifier("Boolean"); default: - ts.Debug.failBadSyntaxKind(node.literal); - break; + return ts.Debug.failBadSyntaxKind(node.literal); } - break; case 134: return ts.createIdentifier("Number"); case 138: @@ -46567,8 +47884,7 @@ var ts; case 173: break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } @@ -47757,12 +49073,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: "\n const _super = name => super[name];\n " + text: "\n const _super = name => super[name];" }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - 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 " + 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);" }; })(ts || (ts = {})); var ts; @@ -48250,7 +49566,7 @@ var ts; var awaitHelper = { name: "typescript:await", scoped: false, - text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" }; function createAwaitHelper(context, expression) { context.requestEmitHelper(awaitHelper); @@ -48259,7 +49575,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -48274,7 +49590,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -48284,7 +49600,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -48341,8 +49657,7 @@ var ts; case 257: return visitJsxFragment(node, true); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxElement(node, isChild) { @@ -48373,14 +49688,14 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } return element; } function visitJsxOpeningFragment(node, children, isChild, location) { - var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -48410,7 +49725,7 @@ var ts; return visitJsxExpression(node); } else { - ts.Debug.failBadSyntaxKind(node); + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxText(node) { @@ -49350,11 +50665,11 @@ var ts; 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)); + ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536)) + ]), parameter), 1 | 32 | 384 | 1536)); ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 | 32 | 1048576); + ts.setEmitFlags(statement, 384 | 32 | 1048576 | 1536); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -49418,8 +50733,7 @@ var ts; 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: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } var captureNewTargetStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration("_newTarget", undefined, newTarget) @@ -49859,23 +51173,22 @@ var ts; statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); } } - var bodyLocation; - var statementsLocation; if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); } else { var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); } else { statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); } } - return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), true), 48 | 384); } function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); @@ -50306,18 +51619,15 @@ var ts; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286, 65); var updated; - if (node.transformFlags & 32768) { - var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = transformFunctionBody(node); - if (node.kind === 155) { - updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); - } - else { - updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); - } + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (32768 | 128) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 155) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { - updated = ts.visitEachChild(node, visitor, context); + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 49152, 0); convertedLoopState = savedConvertedLoopState; @@ -50542,10 +51852,10 @@ var ts; } 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)); - if (span_6.literal.text.length !== 0) { - expressions.push(ts.createLiteral(span_6.literal.text)); + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); } } } @@ -50946,8 +52256,7 @@ var ts; case 190: return visitFunctionExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitFunctionDeclaration(node) { @@ -53219,7 +54528,7 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" }; function createExportStarHelper(context, module) { var compilerOptions = context.getCompilerOptions(); @@ -53235,12 +54544,12 @@ var ts; var importStarHelper = { name: "typescript:commonjsimportstar", scoped: false, - text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" }; var importDefaultHelper = { name: "typescript:commonjsimportdefault", scoped: false, - text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" }; })(ts || (ts = {})); var ts; @@ -53429,11 +54738,11 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_1 = dependencyGroups_1[_i]; - var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var group_2 = dependencyGroups_1[_i]; + var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -54175,6 +55484,1323 @@ var ts; ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + 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 === 233) { + 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 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 === 233) { + 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; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 230 || node.kind === 180) { + 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 === 151 || node.kind === 150 || + (node.kind === 148 && ts.hasModifier(node.parent, 8))) { + 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 === 233 || node.kind === 148) { + 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 getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 156) { + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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_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; + } + } + else { + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + 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_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: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 158: + 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 157: + 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 159: + 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 153: + case 152: + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + 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 === 233) { + 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 : + 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 { + 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 232: + 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 : + 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; + break; + default: + ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 154: + 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 158: + case 163: + 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 157: + 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 159: + 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 153: + case 152: + if (ts.hasModifier(node.parent, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + 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 === 233) { + 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 : + 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 { + 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 232: + case 162: + 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 : + 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; + default: + ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + var diagnosticMessage; + switch (node.parent.kind) { + case 233: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 234: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 158: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 157: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 153: + case 152: + 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 === 233) { + 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 232: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 235: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + if (node.parent.parent.kind === 233) { + diagnosticMessage = node.parent.token === 108 ? + 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 { + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJavaScript(file)) { + return []; + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 | 2048 | 4096 | 8 | 524288; + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var enclosingDeclaration; + var necessaryTypeRefernces; + var possibleImports; + var importDeclarationMap; + var suppressNewDiagnosticContexts; + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + }; + var errorNameNode; + var currentSourceFile; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + var host = context.getEmitHost(); + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeRefernces.set(ref, true); + } + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0) { + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!possibleImports) { + possibleImports = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(possibleImports, ref); + } + } + } + } + else { + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(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) { + context.addDiagnostic(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 transformRoot(node) { + if (node.kind === 272 && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + return node; + } + if (node.kind === 273) { + isBundledEmit = true; + var refs_1 = ts.createMap(); + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + return; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + possibleImports = undefined; + suppressNewDiagnosticContexts = false; + importDeclarationMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + collectReferences(sourceFile, refs_1); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; + needsDeclare = false; + var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], true, [], []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, updated, true, [], []); + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs_1.forEach(referenceVisitor_1); + return bundle; + } + needsDeclare = true; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + possibleImports = undefined; + importDeclarationMap = ts.createMap(); + necessaryTypeRefernces = undefined; + var refs = collectReferences(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + refs.forEach(referenceVisitor); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + if (ts.isExternalModule(node) && !resultHasExternalModuleIndicator) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences()); + return updated; + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeRefernces ? ts.map(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; + var paths = ts.getOutputPathsFor(file, host, true); + declFileName = paths.declarationFilePath || paths.jsFilePath; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getNodeId(elem), elem); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 71) { + return name; + } + else { + if (name.kind === 179) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 204) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55)) : undefined, ensureType(p, p.type, true), ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8)) { + return; + } + if (shouldPrintWithInitializer(node)) { + return; + } + var shouldUseResolverType = node.kind === 148 && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119); + } + if (node.kind === 156) { + return ts.createKeywordTypeNode(119); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 230 || node.kind === 180) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 148 + || node.kind === 151 + || node.kind === 150) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(119); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 232: + case 237: + case 234: + case 233: + case 235: + case 236: + return !resolver.isDeclarationVisible(node); + case 230: + return !getBindingNameVisible(node); + case 241: + case 242: + case 248: + case 247: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + return ts.forEach(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8)) { + return undefined; + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237; + if (input.kind === 9 && isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 252) { + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + return ts.updateImportDeclaration(decl, undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + return visibleDefaultBinding && ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 244) { + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + } + function filterCandidateImports(statements) { + var unconsideredImports = []; + while (ts.length(possibleImports)) { + var i = possibleImports.shift(); + if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { + unconsideredImports.push(i); + continue; + } + if (i.kind === 241) { + var result_3 = transformImportEqualsDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result_3); + continue; + } + var result = transformImportDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result); + } + possibleImports = unconsideredImports; + return ts.mapDefined(statements, function (statement) { + if (ts.isImportDeclaration(statement) || ts.isImportEqualsDeclaration(statement)) { + var key = "" + ts.getNodeId(statement); + if (importDeclarationMap.has(key)) { + var result = importDeclarationMap.get(key); + importDeclarationMap.delete(key); + return result; + } + else { + return undefined; + } + } + else { + return statement; + } + }); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; + return cleanup(ts.createProperty(undefined, input.modifiers, input.name, undefined, undefined, undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 165 || input.kind === 176) && input.parent.kind !== 235); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 205: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 161: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 158: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 154: { + var isPrivate = ts.hasModifier(input, 8); + var ctor = ts.createSignatureDeclaration(154, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0), undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 153: { + var sig = ts.createSignatureDeclaration(152, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 155: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 156: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 151: + return cleanup(ts.updateProperty(input, undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 150: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 152: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 157: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 159: { + return cleanup(ts.updateIndexSignature(input, undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119))); + } + case 230: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 147: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, undefined, undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 170: { + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 162: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 163: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 153 && ts.hasModifier(node.parent, 8); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + return ts.updateExportDeclaration(input, undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 247: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + if (input.expression.kind === 71) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124)] : [], ts.createVariableDeclarationList([varDecl], 2)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + case 241: + case 242: { + possibleImports = possibleImports || []; + ts.pushIfUnique(possibleImports, input); + return input; + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var previousNeedsDeclare; + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var oldPossibleImports; + switch (input.kind) { + case 235: + return cleanup(ts.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 234: { + return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 232: { + return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + } + case 237: { + previousNeedsDeclare = needsDeclare; + needsDeclare = false; + oldPossibleImports = possibleImports; + possibleImports = undefined; + var inner = input.body; + if (inner && inner.kind === 238) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + return cleanup(ts.updateModuleDeclaration(input, undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + needsDeclare = false; + return cleanup(ts.updateModuleDeclaration(input, undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + } + } + case 233: { + var modifiers = ts.createNodeArray(ensureModifiers(input)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 71) { + return preserveJsDoc(ts.createProperty(undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty(undefined, ensureModifiers(param), elem.name, undefined, ensureType(elem, undefined), undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95) { + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124)] : [], ts.createVariableDeclarationList([varDecl], 2)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 85) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 212: { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return cleanup(ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes))); + } + case 236: { + return cleanup(ts.updateEnumDeclaration(input, undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(returnValue) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (input.kind === 237) { + needsDeclare = previousNeedsDeclare; + possibleImports = ts.concatenate(oldPossibleImports, possibleImports); + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (returnValue) { + if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1) && ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 204) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, undefined), undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function ensureModifiers(node) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node) { + var mask = 3071 ^ (4 | 256); + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0; + var parentIsFile = node.parent.kind === 272; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((isBundledEmit && parentIsFile ? 0 : 1) | 512 | 2); + additions = 0; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_6 = function (range) { + if (range.kind === 3) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_6(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 85 && t.expression.kind === 95); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 234) { + return true; + } + return false; + } + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 ^ 4; } + if (modifierAdditions === void 0) { modifierAdditions = 0; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 && flags & 2) { + flags ^= 2; + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 155 + ? accessor.type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 230: + case 151: + case 150: + case 148: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 232: + case 237: + case 241: + case 234: + case 233: + case 235: + case 236: + case 212: + case 242: + case 248: + case 247: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 158: + case 154: + case 153: + case 155: + case 156: + case 151: + case 150: + case 152: + case 157: + case 159: + case 230: + case 147: + case 205: + case 161: + case 170: + case 162: + case 163: + return true; + } + return false; + } +})(ts || (ts = {})); +var ts; (function (ts) { function getModuleTransformer(moduleKind) { switch (moduleKind) { @@ -54230,6 +56856,7 @@ var ts; var onSubstituteNode = function (_, node) { return node; }; var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; var state = 0; + var diagnostics = []; var context = { getCompilerOptions: function () { return options; }, getEmitResolver: function () { return resolver; }, @@ -54257,6 +56884,9 @@ var ts; ts.Debug.assert(state < 1, "Cannot modify transformation hooks after initialization has completed."); ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); } }; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -54274,7 +56904,8 @@ var ts; transformed: transformed, substituteNode: substituteNode, emitNodeWithNotification: emitNodeWithNotification, - dispose: dispose + dispose: dispose, + diagnostics: diagnostics }; function transformRoot(node) { return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; @@ -54422,8 +57053,8 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); + function createSourceMapWriter(host, writer, compilerOptions) { + if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSource; var currentSourceText; @@ -54433,11 +57064,11 @@ var ts; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; + var sourceMapDataList; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, - getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitNodeWithSourceMap: emitNodeWithSourceMap, @@ -54448,13 +57079,14 @@ var ts; function skipSourceTrivia(pos) { return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); } - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) { + function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { if (disabled) { return; } if (sourceMapData) { reset(); } + sourceMapDataList = outputSourceMapDataList; currentSource = undefined; currentSourceText = undefined; sourceMapSourceIndex = -1; @@ -54498,6 +57130,9 @@ var ts; if (disabled) { return; } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMapData); + } currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -54505,6 +57140,7 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + sourceMapDataList = undefined; } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -54669,7 +57305,7 @@ var ts; return; } if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.convertToBase64(getText()); + var base64SourceMapText = ts.base64encode(ts.sys, getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; } else { @@ -54895,7 +57531,15 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -54922,6 +57566,8 @@ var ts; forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!writer.isAtStartOfLine()) { writer.write(" "); } @@ -55014,6 +57660,8 @@ var ts; } } function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (emitPos) emitPos(commentPos); ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); @@ -55027,1683 +57675,6 @@ var ts; ts.createCommentWriter = createCommentWriter; })(ts || (ts = {})); var ts; -(function (ts) { - function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var declarationDiagnostics = ts.createDiagnosticCollection(); - ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); - return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); - function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) { - var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, false); - } - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 273; - var newLine = host.getNewLine(); - var compilerOptions = host.getCompilerOptions(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer; - createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var resultHasExternalModuleIndicator; - var currentText; - var currentLineMap; - var currentIdentifiers; - var isCurrentFileExternalModule; - var reportedDeclarationError = false; - var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; - var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var needsDeclare = true; - var moduleElementDeclarationEmitInfo = []; - var asynchronousSubModuleDeclarationEmitInfo; - var referencesOutput = ""; - var usedTypeDirectiveReferences; - var emittedReferencedFiles = []; - var addedGlobalFileReference = false; - var allSourcesModuleElementDeclarationEmitInfo = []; - ts.forEach(sourceFiles, function (sourceFile) { - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { - addedGlobalFileReference = true; - } - emittedReferencedFiles.push(referencedFile); - } - }); - } - resultHasExternalModuleIndicator = false; - if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - needsDeclare = true; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - needsDeclare = false; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - } - if (moduleElementDeclarationEmitInfo.length) { - var oldWriter = writer; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 242); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - increaseIndent(); - } - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - decreaseIndent(); - } - } - }); - setWriter(oldWriter); - allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { - write("export {};"); - writeLine(); - } - }); - if (usedTypeDirectiveReferences) { - ts.forEachKey(usedTypeDirectiveReferences, function (directive) { - referencesOutput += "/// " + newLine; - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput, - }; - function hasInternalAnnotation(range) { - var comment = currentText.substring(range.pos, range.end); - return ts.stringContains(comment, "@internal"); - } - function stripInternal(node) { - if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); - if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { - return; - } - emitNode(node); - } - } - function createAndSetNewTextWriterWithSymbolWriter() { - 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; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeProperty = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsynchronousModuleElements(nodes) { - var oldWriter = writer; - ts.forEach(nodes, function (declaration) { - var nodeToCheck; - if (declaration.kind === 230) { - nodeToCheck = declaration.parent.parent; - } - else if (declaration.kind === 245 || declaration.kind === 246 || declaration.kind === 243) { - ts.Debug.fail("We should be getting ImportDeclaration instead to write"); - } - else { - nodeToCheck = declaration; - } - var moduleElementEmitInfo = ts.forEach(moduleElementDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) { - moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - } - if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 242) { - moduleElementEmitInfo.isVisible = true; - } - else { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - if (nodeToCheck.kind === 237) { - ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); - asynchronousSubModuleDeclarationEmitInfo = []; - } - writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 237) { - moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; - asynchronousSubModuleDeclarationEmitInfo = undefined; - } - moduleElementEmitInfo.asynchronousOutput = writer.getText(); - } - } - }); - setWriter(oldWriter); - } - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { - if (!typeReferenceDirectives) { - return; - } - if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); - } - for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { - var directive = typeReferenceDirectives_1[_i]; - if (!usedTypeDirectiveReferences.has(directive)) { - usedTypeDirectiveReferences.set(directive, directive); - } - } - } - function handleSymbolAccessibilityError(symbolAccessibilityResult) { - if (symbolAccessibilityResult.accessibility === 0) { - if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); - } - } - else { - reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); - if (errorInfo) { - if (errorInfo.typeName) { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - else { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); - } - function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - reportedDeclarationError = true; - 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_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); - } - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - var shouldUseResolverType = declaration.kind === 148 && - (resolver.isRequiredInitializedParameter(declaration) || - resolver.isOptionalUninitializedParameterProperty(declaration)); - if (type && !shouldUseResolverType) { - emitType(type); - } - else { - errorNameNode = declaration.name; - var format = 4096 | 8 | - 2048 | - (shouldUseResolverType ? 131072 : 0); - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); - errorNameNode = undefined; - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - emitType(signature.type); - } - else { - errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048, writer); - errorNameNode = undefined; - } - } - function emitLines(nodes) { - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var node = nodes_6[_i]; - emit(node); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; - if (!canEmitFn || canEmitFn(node)) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(node); - } - } - } - function emitCommaList(nodes, eachNodeEmitFn, canEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); - } - function writeJsDocComments(declaration) { - 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); - } - } - function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 119: - case 137: - case 134: - case 122: - case 135: - case 138: - case 105: - case 140: - case 95: - case 131: - case 173: - case 177: - return writeTextOfNode(currentText, type); - case 205: - return emitExpressionWithTypeArguments(type); - case 161: - return emitTypeReference(type); - case 164: - return emitTypeQuery(type); - case 166: - return emitArrayType(type); - case 167: - return emitTupleType(type); - case 168: - return emitUnionType(type); - case 169: - return emitIntersectionType(type); - case 170: - return emitConditionalType(type); - case 171: - return emitInferType(type); - case 172: - return emitParenType(type); - case 174: - return emitTypeOperator(type); - case 175: - return emitIndexedAccessType(type); - case 176: - return emitMappedType(type); - case 162: - case 163: - return emitSignatureDeclarationWithJsDocComments(type); - case 165: - return emitTypeLiteral(type); - case 71: - return emitEntityName(type); - case 145: - return emitEntityName(type); - case 160: - return emitTypePredicate(type); - } - function writeEntityName(entityName) { - if (entityName.kind === 71) { - writeTextOfNode(currentText, entityName); - } - else { - var left = entityName.kind === 145 ? entityName.left : entityName.expression; - var right = entityName.kind === 145 ? entityName.right : entityName.name; - writeEntityName(left); - write("."); - writeTextOfNode(currentText, right); - } - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 241 ? 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 === 183); - emitEntityName(node.expression); - if (node.typeArguments) { - write("<"); - emitCommaList(node.typeArguments, emitType); - write(">"); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypePredicate(type) { - writeTextOfNode(currentText, type.parameterName); - write(" is "); - emitType(type.type); - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitIntersectionType(type) { - emitSeparatedList(type.types, " & ", emitType); - } - function emitConditionalType(node) { - emitType(node.checkType); - write(" extends "); - emitType(node.extendsType); - write(" ? "); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node.trueType; - emitType(node.trueType); - enclosingDeclaration = prevEnclosingDeclaration; - write(" : "); - emitType(node.falseType); - } - function emitInferType(node) { - write("infer "); - writeTextOfNode(currentText, node.typeParameter.name); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeOperator(type) { - write(ts.tokenToString(type.operator)); - write(" "); - emitType(type.type); - } - function emitIndexedAccessType(node) { - emitType(node.objectType); - write("["); - emitType(node.indexType); - write("]"); - } - function emitMappedType(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write("{"); - writeLine(); - increaseIndent(); - if (node.readonlyToken) { - write(node.readonlyToken.kind === 37 ? "+readonly " : - node.readonlyToken.kind === 38 ? "-readonly " : - "readonly "); - } - write("["); - writeEntityName(node.typeParameter.name); - write(" in "); - emitType(node.typeParameter.constraint); - write("]"); - if (node.questionToken) { - write(node.questionToken.kind === 37 ? "+?" : - node.questionToken.kind === 38 ? "-?" : - "?"); - } - write(": "); - emitType(node.type); - write(";"); - writeLine(); - decreaseIndent(); - write("}"); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentText = node.text; - currentLineMap = ts.getLineStarts(node); - currentIdentifiers = node.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(node); - enclosingDeclaration = node; - ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); - emitLines(node.statements); - } - function getExportTempVariableName(baseName) { - if (!currentIdentifiers.has(baseName)) { - return baseName; - } - var count = 0; - while (true) { - count++; - var name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; - } - } - } - function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { - var tempVarName = getExportTempVariableName(baseName); - if (needsDeclare) { - write("declare "); - } - write("const "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048, writer); - write(";"); - writeLine(); - return tempVarName; - } - function emitExportAssignment(node) { - if (ts.isSourceFile(node.parent)) { - resultHasExternalModuleIndicator = true; - } - if (node.expression.kind === 71) { - write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentText, node.expression); - } - else { - var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }, needsDeclare); - write(node.isExportEquals ? "export = " : "export default "); - write(tempVarName); - } - write(";"); - writeLine(); - if (node.expression.kind === 71) { - var nodes = resolver.collectLinkedAliases(node.expression); - writeAsynchronousModuleElements(nodes); - } - } - function isModuleElementVisible(node) { - return resolver.isDeclarationVisible(node); - } - function emitModuleElement(node, isModuleElementVisible) { - if (isModuleElementVisible) { - writeModuleElement(node); - } - else if (node.kind === 241 || - (node.parent.kind === 272 && isCurrentFileExternalModule)) { - var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 272) { - asynchronousSubModuleDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - else { - if (node.kind === 242) { - var importDeclaration = node; - if (importDeclaration.importClause) { - isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || - isVisibleNamedBinding(importDeclaration.importClause.namedBindings); - } - } - moduleElementDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - } - } - function writeModuleElement(node) { - switch (node.kind) { - case 232: - return writeFunctionDeclaration(node); - case 212: - return writeVariableStatement(node); - case 234: - return writeInterfaceDeclaration(node); - case 233: - return writeClassDeclaration(node); - case 235: - return writeTypeAliasDeclaration(node); - case 236: - return writeEnumDeclaration(node); - case 237: - return writeModuleDeclaration(node); - case 241: - return writeImportEqualsDeclaration(node); - case 242: - return writeImportDeclaration(node); - default: - ts.Debug.fail("Unknown symbol kind"); - } - } - function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 272) { - var modifiers = ts.getModifierFlags(node); - if (modifiers & 1) { - resultHasExternalModuleIndicator = true; - write("export "); - } - if (modifiers & 512) { - write("default "); - } - else if (node.kind !== 234 && needsDeclare) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(flags) { - if (flags & 8) { - write("private "); - } - else if (flags & 16) { - write("protected "); - } - if (flags & 32) { - write("static "); - } - if (flags & 64) { - write("readonly "); - } - if (flags & 128) { - write("abstract "); - } - } - function writeImportEqualsDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1)) { - write("export "); - } - write("import "); - writeTextOfNode(currentText, node.name); - write(" = "); - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - emitExternalModuleSpecifier(node); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function isVisibleNamedBinding(namedBindings) { - if (namedBindings) { - if (namedBindings.kind === 244) { - return resolver.isDeclarationVisible(namedBindings); - } - else { - return namedBindings.elements.some(function (namedImport) { return resolver.isDeclarationVisible(namedImport); }); - } - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1)) { - write("export "); - } - write("import "); - if (node.importClause) { - var currentWriterPos = writer.getTextPos(); - if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentText, node.importClause.name); - } - if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { - if (currentWriterPos !== writer.getTextPos()) { - write(", "); - } - if (node.importClause.namedBindings.kind === 244) { - write("* as "); - writeTextOfNode(currentText, node.importClause.namedBindings.name); - } - else { - write("{ "); - emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); - write(" }"); - } - } - write(" from "); - } - emitExternalModuleSpecifier(node); - write(";"); - writer.writeLine(); - } - function emitExternalModuleSpecifier(parent) { - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237; - var moduleSpecifier = parent.kind === 241 ? ts.getExternalModuleImportEqualsDeclarationExpression(parent) : - parent.kind === 237 ? parent.name : parent.moduleSpecifier; - if (moduleSpecifier.kind === 9 && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); - if (moduleName) { - write('"'); - write(moduleName); - write('"'); - return; - } - } - writeTextOfNode(currentText, moduleSpecifier); - } - function emitImportOrExportSpecifier(node) { - if (node.propertyName) { - writeTextOfNode(currentText, node.propertyName); - write(" as "); - } - writeTextOfNode(currentText, node.name); - } - function emitExportSpecifier(node) { - emitImportOrExportSpecifier(node); - var nodes = resolver.collectLinkedAliases(node.propertyName || node.name); - writeAsynchronousModuleElements(nodes); - } - function emitExportDeclaration(node) { - resultHasExternalModuleIndicator = true; - emitJsDocComments(node); - write("export "); - if (node.exportClause) { - write("{ "); - emitCommaList(node.exportClause.elements, emitExportSpecifier); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitExternalModuleSpecifier(node); - } - write(";"); - writer.writeLine(); - } - function writeModuleDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isGlobalScopeAugmentation(node)) { - write("global "); - } - else { - if (node.flags & 16) { - write("namespace "); - } - else { - write("module "); - } - if (ts.isExternalModuleAugmentation(node)) { - emitExternalModuleSpecifier(node); - } - else { - writeTextOfNode(currentText, node.name); - } - } - while (node.body && node.body.kind !== 238) { - node = node.body; - write("."); - writeTextOfNode(currentText, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - if (node.body) { - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - else { - write(";"); - } - } - function writeTypeAliasDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function writeEnumDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentText, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentText, node.name); - var enumMemberValue = resolver.getConstantValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(ts.getTextOfConstantValue(enumMemberValue)); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 153 && ts.hasModifier(node.parent, 8); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - emitJsDocComments(node); - decreaseIndent(); - writeTextOfNode(currentText, node.name); - if (node.constraint && !isPrivateMethodTypeParameter(node)) { - write(" extends "); - if (node.parent.kind === 162 || - node.parent.kind === 163 || - (node.parent.parent && node.parent.parent.kind === 165)) { - ts.Debug.assert(node.parent.kind === 153 || - node.parent.kind === 152 || - node.parent.kind === 162 || - node.parent.kind === 163 || - node.parent.kind === 157 || - node.parent.kind === 158); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - if (node.default && !isPrivateMethodTypeParameter(node)) { - write(" = "); - if (node.parent.kind === 162 || - node.parent.kind === 163 || - (node.parent.parent && node.parent.parent.kind === 165)) { - ts.Debug.assert(node.parent.kind === 153 || - node.parent.kind === 152 || - node.parent.kind === 162 || - node.parent.kind === 163 || - node.parent.kind === 157 || - node.parent.kind === 158); - emitType(node.default); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError); - } - } - function getTypeParameterConstraintVisibilityError() { - var diagnosticMessage; - switch (node.parent.kind) { - case 233: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 234: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 158: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 157: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 153: - case 152: - 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 === 233) { - 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 232: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - case 235: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - } - else if (!isImplementsList && node.expression.kind === 95) { - write("null"); - } - function getHeritageClauseVisibilityError() { - var diagnosticMessage; - if (node.parent.parent.kind === 233) { - 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 { - diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: ts.getNameOfDeclaration(node.parent.parent) - }; - } - } - } - function writeClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (ts.hasModifier(param, 92)) { - emitPropertyDeclaration(param); - } - }); - } - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - var tempVarName; - if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { - tempVarName = baseTypeNode.expression.kind === 95 ? - "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 === 237; })); - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.hasModifier(node, 128)) { - write("abstract "); - } - write("class "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - if (baseTypeNode) { - if (!ts.isEntityNameExpression(baseTypeNode.expression)) { - write(" extends "); - write(tempVarName); - if (baseTypeNode.typeArguments) { - write("<"); - emitCommaList(baseTypeNode.typeArguments, emitType); - write(">"); - } - } - else { - emitHeritageClause([baseTypeNode], false); - } - } - emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(ts.getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function writeInterfaceDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); - if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, false); - } - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - emitJsDocComments(node); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - emitVariableDeclaration(node); - 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 !== 230 || isVariableDeclarationVisible(node)) { - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); - if ((node.kind === 151 || node.kind === 150 || - (node.kind === 148 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 151 || node.kind === 150) && node.parent.kind === 165) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (resolver.isLiteralConstDeclaration(node)) { - write(" = "); - resolver.writeLiteralConstValue(node, writer); - } - else if (!ts.hasModifier(node, 8)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 230) { - 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 === 151 || node.kind === 150 || - (node.kind === 148 && ts.hasModifier(node.parent, 8))) { - 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 === 233 || node.kind === 148) { - 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 getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function emitBindingPattern(bindingPattern) { - var elements = []; - for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.kind !== 204 && isVariableDeclarationVisible(element)) { - elements.push(element); - } - } - emitCommaList(elements, emitBindingElement); - } - function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - writeTextOfNode(currentText, bindingElement.name); - writeTypeOfDeclaration(bindingElement, undefined, getBindingElementTypeVisibilityError); - } - } - } - } - function emitTypeOfVariableDeclarationFromTypeLiteral(node) { - if (ts.hasType(node)) { - write(": "); - emitType(node.type); - } - } - function isVariableStatementVisible(node) { - 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); })) { - return; - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isLet(node.declarationList)) { - write("let "); - } - else if (ts.isConst(node.declarationList)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); - write(";"); - writeLine(); - } - function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - var accessorWithTypeAnnotation; - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64)); - writeNameOfDeclaration(node, getAccessorNameVisibilityError); - if (!ts.hasModifier(node, 8)) { - accessorWithTypeAnnotation = node; - var type = getTypeAnnotationFromAccessor(node); - if (!type) { - var anotherAccessor = node.kind === 155 ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 155 - ? 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 === 233) { - 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 === 156) { - if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - 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_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; - } - } - else { - if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? - 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_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: accessorWithTypeAnnotation.name - }; - } - } - function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - if (!resolver.isImplementationOfOverload(node)) { - emitJsDocComments(node); - if (node.kind === 232) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 153 || node.kind === 154) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - } - if (node.kind === 232) { - write("function "); - writeTextOfNode(currentText, node.name); - } - else if (node.kind === 154) { - write("constructor"); - } - else { - 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 === 233) { - 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); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var closeParenthesizedFunctionType = false; - if (node.kind === 159) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - write("["); - } - else { - if (node.kind === 154 && ts.hasModifier(node, 8)) { - write("();"); - writeLine(); - return; - } - if (node.kind === 158 || node.kind === 163) { - write("new "); - } - else if (node.kind === 162) { - var currentOutput = writer.getText(); - if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { - closeParenthesizedFunctionType = true; - write("("); - } - } - emitTypeParameters(node.typeParameters); - write("("); - } - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 159) { - write("]"); - } - else { - write(")"); - } - var isFunctionTypeOrConstructorType = node.kind === 162 || node.kind === 163; - if (isFunctionTypeOrConstructorType || node.parent.kind === 165) { - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 154 && !ts.hasModifier(node, 8)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - else if (closeParenthesizedFunctionType) { - write(")"); - } - function getReturnTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 158: - 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 157: - 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 159: - 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 153: - case 152: - if (ts.hasModifier(node, 32)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? - 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 === 233) { - 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 : - 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 { - 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 232: - 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 : - 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; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - writeTextOfNode(currentText, node.name); - } - if (resolver.isOptionalParameter(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 162 || - node.parent.kind === 163 || - node.parent.parent.kind === 165) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!ts.hasModifier(node.parent, 8)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - switch (node.parent.kind) { - case 154: - 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 158: - 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 157: - 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 159: - 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 153: - case 152: - if (ts.hasModifier(node.parent, 32)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? - 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 === 233) { - 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 : - 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 { - 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 232: - 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 : - 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; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - } - function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 178) { - write("{"); - emitCommaList(bindingPattern.elements, emitBindingElement); - write("}"); - } - else if (bindingPattern.kind === 179) { - write("["); - var elements = bindingPattern.elements; - emitCommaList(elements, emitBindingElement); - if (elements && elements.hasTrailingComma) { - write(", "); - } - write("]"); - } - } - function emitBindingElement(bindingElement) { - if (bindingElement.kind === 204) { - write(" "); - } - else if (bindingElement.kind === 180) { - if (bindingElement.propertyName) { - writeTextOfNode(currentText, bindingElement.propertyName); - write(": "); - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - ts.Debug.assert(bindingElement.name.kind === 71); - if (bindingElement.dotDotDotToken) { - write("..."); - } - writeTextOfNode(currentText, bindingElement.name); - } - } - } - } - } - function emitNode(node) { - switch (node.kind) { - case 232: - case 237: - case 241: - case 234: - case 233: - case 235: - case 236: - return emitModuleElement(node, isModuleElementVisible(node)); - case 212: - return emitModuleElement(node, isVariableStatementVisible(node)); - case 242: - return emitModuleElement(node, !node.importClause); - case 248: - return emitExportDeclaration(node); - case 154: - case 153: - case 152: - return writeFunctionDeclaration(node); - case 158: - case 157: - case 159: - return emitSignatureDeclarationWithJsDocComments(node); - case 155: - case 156: - return emitAccessorDeclaration(node); - case 151: - case 150: - return emitPropertyDeclaration(node); - case 271: - return emitEnumMemberDeclaration(node); - case 247: - return emitExportAssignment(node); - case 272: - return emitSourceFile(node); - } - } - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { - var declFileName; - var addedBundledEmitReference = false; - if (referencedFile.isDeclarationFile) { - declFileName = referencedFile.fileName; - } - else { - ts.forEachEmittedFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); - } - if (declFileName) { - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); - referencesOutput += "/// " + newLine; - } - return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFileOrBundle) { - var isBundledEmit = sourceFileOrBundle.kind === 273; - if (isBundledEmit && !addBundledFileReference) { - return; - } - ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); - declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; - addedBundledEmitReference = isBundledEmit; - } - } - } - 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 || emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var declarationOutput = emitDeclarationResult.referencesOutput - + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); - } - return emitSkipped; - function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { - var appliedSyncOutputPos = 0; - var declarationOutput = ""; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.asynchronousOutput) { - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); - declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); - return declarationOutput; - } - } - ts.writeDeclarationFile = writeDeclarationFile; -})(ts || (ts = {})); -var ts; (function (ts) { var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { @@ -56711,10 +57682,8 @@ var ts; var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var bundle = ts.createBundle(sourceFiles); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; } @@ -56723,10 +57692,7 @@ var ts; else { for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { var sourceFile = sourceFiles_1[_a]; - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); if (result) { return result; } @@ -56734,8 +57700,27 @@ var ts; } } ts.forEachEmittedFile = forEachEmittedFile; + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 273) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + else { + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var isJs = ts.isSourceFileJavaScript(sourceFile); + var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; } function getOutputExtension(sourceFile, options) { if (options.jsx === 1) { @@ -56750,41 +57735,28 @@ var ts; } return ".js"; } - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 273) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); - } - return ts.getOriginalSourceFile(sourceFileOrBundle); - } function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { var compilerOptions = host.getCompilerOptions(); var moduleKind = ts.getEmitModuleKind(compilerOptions); - var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); var writer = ts.createTextWriter(newLine); var sourceMap = ts.createSourceMapWriter(host, writer); + var declarationSourceMap = ts.createSourceMapWriter(host, writer, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); var currentSourceFile; var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; - var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, false); - var printer = createPrinter(compilerOptions, { - hasGlobalName: resolver.hasGlobalName, - onEmitNode: transform.emitNodeWithNotification, - substituteNode: transform.substituteNode, - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - onEmitHelpers: emitHelpers, - onSetSourceFile: setSourceFile, - }); ts.performance.mark("beforePrint"); - forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); - transform.dispose(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -56792,18 +57764,9 @@ var ts; sourceMaps: sourceMapDataList }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { - if (!emitOnlyDtsFiles) { - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); - } - } - else { - emitSkipped = true; - } - if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; - } + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { emittedFilesList.push(jsFilePath); @@ -56816,11 +57779,64 @@ var ts; } } } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + emitSkipped = true; + return; + } + if (emitOnlyDtsFiles) { + return; + } + var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, false); + var printer = createPrinter(compilerOptions, { + hasGlobalName: resolver.hasGlobalName, + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: sourceMap.emitPos, + onEmitHelpers: emitHelpers, + onSetSourceFile: setSourceFile, + }); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true }), { + hasGlobalName: resolver.hasGlobalName, + onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: declarationSourceMap.emitPos, + onSetSourceFile: setSourceFileForDeclarationSourceMaps, + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + } + declarationTransform.dispose(); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 273 ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 272 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); + mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { bundledHelpers = ts.createMap(); isOwnFileEmit = false; @@ -56831,18 +57847,15 @@ var ts; printer.writeFile(sourceFile, writer); } writer.writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); + var sourceMappingURL = mapRecorder.getSourceMappingURL(); if (sourceMappingURL) { writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); } - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); - } - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); + if (sourceMapFilePath) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), false, sourceFiles); } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); - sourceMap.reset(); + mapRecorder.reset(); writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; @@ -56852,6 +57865,10 @@ var ts; currentSourceFile = node; sourceMap.setSourceFile(node); } + function setSourceFileForDeclarationSourceMaps(node) { + currentSourceFile = node; + declarationSourceMap.setSourceFile(node); + } function emitHelpers(node, writeLines) { var helpersEmitted = false; var bundle = node.kind === 273 ? node : undefined; @@ -56981,6 +57998,7 @@ var ts; emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpersIndirect(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { var sourceFile = _b[_a]; print(0, sourceFile, sourceFile); @@ -57484,7 +58502,7 @@ var ts; else { emitTypeAnnotation(node.type); } - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); } function emitDecorator(decorator) { writePunctuation("@"); @@ -57503,8 +58521,9 @@ var ts; emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); + emitIfPresent(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { @@ -57620,7 +58639,7 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; + var flags = ts.getEmitFlags(node) & 1 ? 384 : 16449; emitList(node, node.members, flags | 262144); writePunctuation("}"); } @@ -57635,7 +58654,7 @@ var ts; } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 336); + emitList(node, node.elementTypes, 272); writePunctuation("]"); } function emitUnionType(node) { @@ -57743,7 +58762,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } function emitArrayLiteralExpression(node) { var elements = node.elements; @@ -57777,7 +58796,10 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - writePunctuation(shouldEmitDotDot ? ".." : "."); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(23, node.expression.end, writePunctuation, node); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -57798,9 +58820,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - writePunctuation("["); + var openPos = emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - writePunctuation("]"); + emitTokenWithComment(22, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); @@ -57808,7 +58830,7 @@ var ts; emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { - writeKeyword("new"); + emitTokenWithComment(94, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); @@ -57826,9 +58848,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - writePunctuation("("); + var openParenPos = emitTokenWithComment(19, node.pos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -57846,22 +58868,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - writeKeyword("delete"); + emitTokenWithComment(80, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - writeKeyword("typeof"); + emitTokenWithComment(103, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - writeKeyword("void"); + emitTokenWithComment(105, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - writeKeyword("await"); + emitTokenWithComment(121, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -57917,7 +58939,7 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - writeKeyword("yield"); + emitTokenWithComment(116, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } @@ -57955,16 +58977,13 @@ var ts; emit(node.literal); } function emitBlock(node) { - writeToken(17, node.pos, writePunctuation, node); emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18, node.statements.end, writePunctuation, node); } function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(17, node.pos, writePunctuation, node); var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; emitList(node, node.statements, format); + emitTokenWithComment(18, node.statements.end, writePunctuation, node, !!(format & 1)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -57979,15 +58998,15 @@ var ts; writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(90, node.pos, writeKeyword, node); writeSpace(); - writeToken(19, openParenPos, writePunctuation, node); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20, node.expression.end, writePunctuation, node); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82, node.thenStatement.end, writeKeyword, node); + emitTokenWithComment(82, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 215) { writeSpace(); emit(node.elseStatement); @@ -57997,8 +59016,15 @@ var ts; } } } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(106, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); + } function emitDoStatement(node) { - writeKeyword("do"); + emitTokenWithComment(81, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -58006,55 +59032,48 @@ var ts; else { writeLineOrSpace(node); } - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(");"); + emitWhileClause(node, node.statement.end); + writePunctuation(";"); } function emitWhileStatement(node) { - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(")"); + emitWhileClause(node, node.pos); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); writeSpace(); - writeToken(19, openParenPos, writePunctuation, node); + var pos = emitTokenWithComment(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); - writeSemicolon(); + pos = emitTokenWithComment(25, node.initializer ? node.initializer.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.condition); - writeSemicolon(); + pos = emitTokenWithComment(25, node.condition ? node.condition.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.incrementor); - writePunctuation(")"); + emitTokenWithComment(20, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); writeSpace(); - writeToken(19, openParenPos, writePunctuation); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("in"); + emitTokenWithComment(92, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end, writePunctuation); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - writeToken(19, openParenPos, writePunctuation); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("of"); + emitTokenWithComment(144, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end, writePunctuation); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -58068,22 +59087,34 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77, node.pos, writeKeyword); + emitTokenWithComment(77, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72, node.pos, writeKeyword); + emitTokenWithComment(72, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } - function emitTokenWithComment(token, pos, writer, contextNode) { - var node = contextNode && ts.getParseTreeNode(contextNode); - if (node && node.kind === contextNode.kind) { + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, writer, contextNode); - if (node && node.kind === contextNode.kind) { + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { emitTrailingCommentsOfPosition(pos, true); } return pos; @@ -58094,35 +59125,35 @@ var ts; writeSemicolon(); } function emitWithStatement(node) { - writeKeyword("with"); + var openParenPos = emitTokenWithComment(107, node.pos, writeKeyword, node); writeSpace(); - writePunctuation("("); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(98, node.pos, writeKeyword, node); writeSpace(); - writeToken(19, openParenPos, writePunctuation); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20, node.expression.end, writePunctuation); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - writePunctuation(":"); + emitTokenWithComment(56, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - writeKeyword("throw"); + emitTokenWithComment(100, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); writeSemicolon(); } function emitTryStatement(node) { - writeKeyword("try"); + emitTokenWithComment(102, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -58131,7 +59162,7 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - writeKeyword("finally"); + emitTokenWithComment(87, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } @@ -58143,7 +59174,7 @@ var ts; function emitVariableDeclaration(node) { emit(node.name); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); @@ -58274,7 +59305,7 @@ var ts; increaseIndent(); } emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256); + emitList(node, node.heritageClauses, 0); writeSpace(); writePunctuation("{"); emitList(node, node.members, 65); @@ -58327,6 +59358,8 @@ var ts; } emit(node.name); var body = node.body; + if (!body) + return writeSemicolon(); while (body.kind === 237) { writePunctuation("."); emit(body.name); @@ -58337,23 +59370,21 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); - writePunctuation("{"); emitBlockStatements(node, isEmptyBlock(node)); - writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17, node.pos, writePunctuation); + emitTokenWithComment(17, node.pos, writePunctuation, node); emitList(node, node.clauses, 65); - writeToken(18, node.clauses.end, writePunctuation); + emitTokenWithComment(18, node.clauses.end, writePunctuation, node, true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - writePunctuation("="); + emitTokenWithComment(58, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); writeSemicolon(); @@ -58368,12 +59399,12 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - writeKeyword("from"); + emitTokenWithComment(142, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -58382,15 +59413,15 @@ var ts; function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - writePunctuation(","); + emitTokenWithComment(26, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - writePunctuation("*"); + var asPos = emitTokenWithComment(39, node.pos, writePunctuation, node); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -58401,41 +59432,42 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - writeOperator("="); + emitTokenWithComment(58, nextPos, writeOperator, node); } else { - writeKeyword("default"); + emitTokenWithComment(79, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); writeSemicolon(); } function emitExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - writePunctuation("*"); + nextPos = emitTokenWithComment(39, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); - writeKeyword("from"); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(142, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); writeSpace(); - writeKeyword("as"); + nextPos = emitTokenWithComment(118, nextPos, writeKeyword, node); writeSpace(); - writeKeyword("namespace"); + nextPos = emitTokenWithComment(130, nextPos, writeKeyword, node); writeSpace(); emit(node.name); writeSemicolon(); @@ -58448,14 +59480,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 432); + emitList(node, node.elements, 262576); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -58475,9 +59507,7 @@ var ts; writePunctuation("<"); emitJsxTagName(node.tagName); writeSpace(); - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); - } + emit(node.attributes); writePunctuation("/>"); } function emitJsxFragment(node) { @@ -58491,8 +59521,8 @@ var ts; emitJsxTagName(node.tagName); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); - emit(node.attributes); } + emit(node.attributes); } writePunctuation(">"); } @@ -58536,30 +59566,29 @@ var ts; } } function emitCaseClause(node) { - writeKeyword("case"); + emitTokenWithComment(73, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - writeKeyword("default"); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + var pos = emitTokenWithComment(79, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); } - function emitCaseOrDefaultClauseStatements(parentNode, statements) { + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { var emitAsSingleStatement = statements.length === 1 && (ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); - if (statements.length > 0) { - emitTrailingCommentsOfPosition(statements.pos); - } var format = 81985; if (emitAsSingleStatement) { + writeToken(56, colonPos, writePunctuation, parentNode); writeSpace(); format &= ~(1 | 64); } + else { + emitTokenWithComment(56, colonPos, writePunctuation, parentNode); + } emitList(parentNode, statements, format); } function emitHeritageClause(node) { @@ -58569,12 +59598,12 @@ var ts; emitList(node, node.types, 272); } function emitCatchClause(node) { - var openParenPos = writeToken(74, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(74, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - writeToken(19, openParenPos, writePunctuation); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration.end, writePunctuation); + emitTokenWithComment(20, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -58607,7 +59636,7 @@ var ts; } function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } function emitSourceFile(node) { writeLine(); @@ -58623,11 +59652,31 @@ var ts; } emitSourceFileWorker(node); } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.referencedFiles, node.typeReferenceDirectives); + } + function emitTripleSlashDirectives(files, types) { + for (var _a = 0, files_1 = files; _a < files_1.length; _a++) { + var directive = files_1[_a]; + write("/// "); + writeLine(); + } + for (var _b = 0, types_18 = types; _b < types_18.length; _b++) { + var directive = types_18[_b]; + write("/// "); + writeLine(); + } + } function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); emitList(node, statements, 1, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -58709,10 +59758,10 @@ var ts; emit(node); } } - function emitInitializer(node) { + function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - writeOperator("="); + emitTokenWithComment(58, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -58837,6 +59886,9 @@ var ts; } if (format & 7680) { writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + emitTrailingCommentsOfPosition(children.pos, true); + } } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -58920,6 +59972,9 @@ var ts; onAfterEmitNodeArray(children); } if (format & 7680) { + if (isEmpty && !isUndefined) { + emitLeadingCommentsOfPosition(children.end); + } writePunctuation(getClosingBracket(format)); } } @@ -59016,9 +60071,9 @@ var ts; } function writeLines(text) { var lines = text.split(/\r\n?|\n/g); - var indentation = guessIndentation(lines); - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var lineText = lines_1[_a]; + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var lineText = lines_2[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); @@ -59027,21 +60082,6 @@ var ts; } } } - function guessIndentation(lines) { - var indentation; - 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) { - indentation = i; - break; - } - } - } - } - return indentation; - } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { increaseIndent(); @@ -59239,7 +60279,7 @@ var ts; 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)) { + if (local && local.flags & (67216319 | 1048576 | 2097152)) { return false; } } @@ -59273,7 +60313,13 @@ var ts; } } } - function makeUniqueName(baseName) { + function makeUniqueName(baseName, optimistic) { + if (optimistic) { + if (isUniqueName(baseName)) { + generatedNames.set(baseName, true); + return baseName; + } + } if (baseName.charCodeAt(baseName.length - 1) !== 95) { baseName += "_"; } @@ -59341,6 +60387,8 @@ var ts; return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 16)); case 3: return makeUniqueName(ts.idText(name)); + case 5: + return makeUniqueName(ts.idText(name), true); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -59551,7 +60599,7 @@ var ts; var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); ts.mutateMap(missingFileWatches, newMissingFilePathMap, { createNewValue: createMissingFileWatch, - onDeleteValue: closeFileWatcher + onDeleteValue: ts.closeFileWatcher }); } ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; @@ -59583,75 +60631,74 @@ var ts; return program.isEmittedFile(file); } ts.isEmittedFileOfProgram = isEmittedFileOfProgram; - function addFileWatcher(host, file, cb) { - return host.watchFile(file, cb); + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); } - 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); + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); } - 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); + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); return { close: function () { - if (!logOnlyTrigger) { - log(watcherCaption + "Close: " + info); - } + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); watcher.close(); } }; } - function closeFileWatcher(watcher) { - watcher.close(); + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : ""); } - ts.closeFileWatcher = closeFileWatcher; function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } @@ -59829,8 +60876,7 @@ var ts; } 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(); + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " 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; @@ -59854,8 +60900,9 @@ var ts; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } @@ -59885,8 +60932,8 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; @@ -59920,9 +60967,7 @@ var ts; output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); output += " - "; } - var categoryColor = getCategoryFormat(diagnostic.category); - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { @@ -60168,8 +61213,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var sourceFile = files_1[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -60181,13 +61226,13 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } var unknownModuleNames; var result; @@ -60701,14 +61746,16 @@ var ts; case 185: case 186: case 205: + case 254: + case 255: if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return; } break; } - for (var _b = 0, nodes_8 = nodes; _b < nodes_8.length; _b++) { - var node = nodes_8[_b]; + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; walk(node); } } @@ -60787,9 +61834,9 @@ var ts; 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 === 71 + ? b.kind === 71 && a.escapedText === b.escapedText + : b.kind === 9 && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -60804,7 +61851,7 @@ var ts; && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); - var importDecl = ts.createImportDeclaration(undefined, undefined, undefined); + var importDecl = ts.createImportDeclaration(undefined, undefined, undefined, externalHelpersModuleReference); ts.addEmitFlags(importDecl, 67108864); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; @@ -60822,49 +61869,39 @@ var ts; file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { - switch (node.kind) { - case 242: - case 241: - case 248: - var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { - break; + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); } - if (!moduleNameExpr.text) { - break; - } - if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { - (imports || (imports = [])).push(moduleNameExpr); - } - break; - case 237: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { - var moduleName = node.name; - var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { - (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + (ambientModules || (ambientModules = [])).push(nameText); } - else if (!inAmbientModule) { - if (file.isDeclarationFile) { - (ambientModules || (ambientModules = [])).push(nameText); - } - var body = node.body; - if (body) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, true); - } + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); } } } + } } } function collectDynamicImportOrRequireCalls(node) { if (ts.isRequireCall(node, true)) { - (imports || (imports = [])).push(node.arguments[0]); + imports = ts.append(imports, node.arguments[0]); } - else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9) { - (imports || (imports = [])).push(node.arguments[0]); + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); } else { ts.forEachChild(node, collectDynamicImportOrRequireCalls); @@ -61220,8 +62257,8 @@ var ts; if (options.out && options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } - if (options.mapRoot && !options.sourceMap) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { if (!options.declaration) { @@ -61231,6 +62268,9 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } + if (options.declarationMap && !options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } @@ -61246,21 +62286,21 @@ var ts; } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { - 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)); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } 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"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - 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")); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -61279,7 +62319,7 @@ var ts; } if (options.emitDeclarationOnly) { if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -61372,18 +62412,18 @@ var ts; } return ts.emptyArray; } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(true, option1, option2, message, option1, option2); + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(true, option1, option2, message, option1, option2, option3); } function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(false, option1, undefined, message, arg0); } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } function getCompilerOptionsObjectLiteralSyntax() { @@ -61401,11 +62441,11 @@ var ts; } return _compilerOptionsObjectLiteralSyntax; } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { var props = ts.getPropertyAssignment(objectLiteral, key1, key2); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); } return !!props.length; } @@ -61991,12 +63031,14 @@ var ts; 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 cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var nonRelaticeModuleNameCache = ts.createMap(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); @@ -62057,6 +63099,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); + nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); } function finishCachingPerDirectoryResolution() { @@ -62070,7 +63113,7 @@ var ts; clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); if (!resolutionHost.getGlobalCache) { return primaryResult; } @@ -62110,15 +63153,8 @@ var ts; 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) { + watchFailedLookupLocationOfResolution(resolution); + if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { @@ -62189,8 +63225,9 @@ var ts; if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { return { dir: rootDir, dirPath: rootPath }; } - var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); - var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { while (ts.stringContains(dirPath, "/node_modules/")) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); @@ -62213,69 +63250,87 @@ var ts; 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; - } + function watchFailedLookupLocationOfResolution(resolution) { + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + 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]; + if (resolution.refCount !== undefined) { + resolution.refCount++; + return; + } + resolution.refCount = 1; + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_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; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; if (!ignore) { - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - if (dirWatcher) { - dirWatcher.refCount++; + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + if (dirPath === rootPath) { + setAtRoot = true; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + setDirectoryWatcher(dir, dirPath); } } } + if (setAtRoot) { + setDirectoryWatcher(rootDir, rootPath); + } + } + function setDirectoryWatcher(dir, dirPath) { + 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); + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + return; } - } - function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { - var failedLookupLocations = _a.failedLookupLocations; - for (var i = startIndex; i < failedLookupLocations.length; i++) { - var failedLookupLocation = failedLookupLocations[i]; + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + if (!ignore) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; - if (!ignore) { - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - dirWatcher.refCount--; - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + dirWatcher.refCount--; } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { @@ -62349,7 +63404,8 @@ var ts; } else { var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); - if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { isChangedFailedLookupLocation = function (location) { var locationPath = resolutionHost.toPath(location); return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); @@ -62373,13 +63429,27 @@ var ts; function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); } - function createTypeRootsWatch(_typeRootPath, typeRoot) { + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } resolutionHost.onChangedAutomaticTypeDirectiveNames(); + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } }, 1); } function updateTypeRootsWatch() { @@ -62433,6 +63503,7 @@ var ts; ts.createDiagnosticReporter = createDiagnosticReporter; function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && + !options.preserveWatchOutput && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code && !options.extendedDiagnostics && !options.diagnostics) { @@ -62641,16 +63712,15 @@ var ts; parseConfigFile(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); - var writeLog = loggingEnabled ? trace : ts.noop; - var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; - var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; - var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectoryWorker = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var newLine = updateNewLine(); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, writeLog); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High); } var compilerHost = { getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, @@ -62720,7 +63790,7 @@ var ts; if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { return builderProgram; } - if (loggingEnabled) { + if (watchLogLevel !== ts.WatchLogLevel.None) { writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); @@ -62790,7 +63860,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); } } else { @@ -62803,7 +63873,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -62851,6 +63921,9 @@ var ts; (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); } else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } sourceFilesCache.delete(oldSourceFile.path); resolutionCache.removeResolutionsOfFile(oldSourceFile.path); } @@ -62928,10 +64001,10 @@ var ts; } } function watchDirectory(directory, cb, flags) { - return watchDirectoryWorker(host, directory, cb, flags, writeLog); + return watchDirectoryWorker(host, directory, cb, flags); } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -63048,6 +64121,13 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, { name: "watch", shortName: "w", @@ -63125,9 +64205,10 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "es2018.promise": "lib.es2018.promise.d.ts", + "es2018.regexp": "lib.es2018.regexp.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, @@ -63167,6 +64248,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, { name: "emitDeclarationOnly", type: "boolean", @@ -64089,7 +65177,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_6 = function (name) { + var _loop_7 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; @@ -64113,7 +65201,7 @@ var ts; } }; for (var name in options) { - _loop_6(name); + _loop_7(name); } return result; } @@ -64585,7 +65673,7 @@ var ts; function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); - var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; @@ -64723,12 +65811,6 @@ var ts; wildcardFiles.delete(lowerPriorityPath); } } - function caseSensitiveKeyMapper(key) { - return key; - } - function caseInsensitiveKeyMapper(key) { - return key.toLowerCase(); - } function convertCompilerOptionsForTelemetry(opts) { var out = {}; for (var key in opts) { @@ -65089,4 +66171,7 @@ if (ts.Debug.isDebugging) { if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { ts.sys.tryEnableSourceMapsForHost(); } +if (ts.sys.setBlocking) { + ts.sys.setBlocking(); +} ts.executeCommandLine(ts.sys.args); diff --git a/lib/tsserver.js b/lib/tsserver.js index 103918e21dc..315a4e74829 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -426,6 +426,7 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -447,6 +448,7 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["OptimisticUnique"] = 5] = "OptimisticUnique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; @@ -633,28 +635,28 @@ var ts; SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "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["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -826,10 +828,13 @@ var ts; var InferencePriority; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; - InferencePriority[InferencePriority["NoConstraints"] = 8] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 16] = "AlwaysStrict"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -852,13 +857,21 @@ var ts; SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; - DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; @@ -1219,9 +1232,9 @@ var ts; 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["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; @@ -1237,12 +1250,12 @@ var ts; ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; @@ -1254,6 +1267,46 @@ var ts; ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + function _contextuallyTypePragmas(args) { + return args; + } + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 + }, + "ts-check": { + kind: 2 + }, + "ts-nocheck": { + kind: 2 + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 + }, + }); })(ts || (ts = {})); var ts; (function (ts) { @@ -1314,7 +1367,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.8"; + ts.versionMajorMinor = "2.9"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { @@ -1329,6 +1382,10 @@ var ts; })(ts || (ts = {})); (function (ts) { ts.emptyArray = []; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -1831,18 +1888,6 @@ var ts; }; } ts.singleIterator = singleIterator; - function span(array, f) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (!f(array[i], i)) { - return [array.slice(0, i), array.slice(i)]; - } - } - return [array.slice(0), []]; - } - return undefined; - } - ts.span = span; function spanMap(array, keyfn, mapfn) { var result; if (array) { @@ -2181,7 +2226,7 @@ var ts; } ts.elementAt = elementAt; function firstOrUndefined(array) { - return elementAt(array, 0); + return array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -2190,7 +2235,7 @@ var ts; } ts.first = first; function lastOrUndefined(array) { - return elementAt(array, -1); + return array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -2373,19 +2418,21 @@ var ts; } ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } var result = createMap(); 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); + result.set(makeKey(value), makeValue(value)); } return result; } ts.arrayToMap = arrayToMap; function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } 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; + result[makeKey(value)] = makeValue(value); } return result; } @@ -2394,6 +2441,20 @@ var ts; return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } ts.arrayToSet = arrayToSet; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -2451,15 +2512,6 @@ var ts; } } } - function group(values, getGroupId) { - var groupIdToGroup = createMultiMap(); - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - groupIdToGroup.add(getGroupId(value), value); - } - return arrayFrom(groupIdToGroup.values()); - } - ts.group = group; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -2567,7 +2619,6 @@ var ts; return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.formatStringFromArgs = formatStringFromArgs; - ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } @@ -2909,6 +2960,10 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAreDeclarationMapsEnabled(options) { + return !!(options.declaration && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined @@ -3269,7 +3324,6 @@ 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); }); @@ -3300,7 +3354,7 @@ var ts; } } }; - for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + for (var _i = 0, _b = sort(files, compareStringsCaseSensitive); _i < _b.length; _i++) { var current = _b[_i]; _loop_1(current); } @@ -3310,7 +3364,7 @@ var ts; return; } } - for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -3333,7 +3387,7 @@ var ts; } includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -3690,7 +3744,7 @@ var ts; } ts.matchedText = matchedText; function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; + var matchedValue; var longestMatchPrefixLength = -1; for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { var v = values_2[_i]; @@ -3772,6 +3826,38 @@ var ts; return t === undefined ? undefined : [t]; } ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(ts || (ts = {})); var ts; (function (ts) { @@ -3787,6 +3873,269 @@ var ts; FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + function getPriorityValues(highPriorityValue) { + var mediumPriorityValue = highPriorityValue * 2; + var lowPriorityValue = mediumPriorityValue * 4; + return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; + } + function pollingInterval(watchPriority) { + return pollingIntervalsForPriority[watchPriority]; + } + var pollingIntervalsForPriority = getPriorityValues(250); + function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { + return host.watchFile(fileName, callback, pollingInterval(watchPriority)); + } + ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; + ts.missingFileModifiedTime = new Date(0); + function createPollingIntervalBasedLevels(levels) { + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + var _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + pollQueue(changedFilesInLastPoll, PollingInterval.Low, 0, changedFilesInLastPoll.length); + pollPollingIntervalQueue(queue); + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + var eventKind = oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + watchedFile.callback(watchedFile.fileName, eventKind); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + function createRecursiveDirectoryWatcher(host) { + return createDirectoryWatcher; + function createDirectoryWatcher(dirName, callback) { + var watcher = host.watchDirectory(dirName, function (fileName) { + callback(fileName); + updateChildWatches(result, callback); + }); + var result = { + close: function () { + watcher.close(); + result.childWatches.forEach(ts.closeFileWatcher); + result = undefined; + }, + dirName: dirName, + childWatches: ts.emptyArray + }; + updateChildWatches(result, callback); + return result; + } + function updateChildWatches(watcher, callback) { + if (watcher) { + watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + } + } + function watchChildDirectories(parentDir, existingChildWatches, callback) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(ts.getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(ts.getNormalizedAbsolutePath(childName, parentDir), callback); + addChildDirectoryWatcher(result); + } + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -3815,75 +4164,109 @@ var ts; catch (_a) { _crypto = undefined; } - var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } - function createMD5HashUsingNativeCrypto(data) { - var hash = _crypto.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - } - function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - var fileWatcherCallbacks = ts.createMultiMap(); - return { addFile: addFile, removeFile: removeFile }; - function reduceDirWatcherRefCountForFile(fileName) { - var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers.get(dirName); - if (watcher) { - watcher.referenceCount -= 1; - if (watcher.referenceCount <= 0) { - watcher.close(); - dirWatchers.delete(dirName); - } - } - } - function addDirWatcher(dirPath) { - var watcher = dirWatchers.get(dirPath); - if (watcher) { - watcher.referenceCount += 1; - return; - } - watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); - watcher.referenceCount = 1; - dirWatchers.set(dirPath, watcher); - return; - } - function addFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.add(filePath, callback); - } - function addFile(fileName, callback) { - addFileWatcherCallback(fileName, callback); - addDirWatcher(ts.getDirectoryPath(fileName)); - return { fileName: fileName, callback: callback }; - } - function removeFile(watchedFile) { - removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback); - reduceDirWatcherRefCountForFile(watchedFile.fileName); - } - function removeFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.remove(filePath, callback); - } - function fileEventHandler(eventName, relativeFileName, baseDirPath) { - var fileName = !ts.isString(relativeFileName) - ? undefined - : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename")) { - var callbacks = fileWatcherCallbacks.get(fileName); - if (callbacks) { - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); - } - } - } - } - } - var watchedFileSet = createWatchedFileSet(); + var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (_a) { } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: function (path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + base64decode: Buffer.from ? function (input) { + return Buffer.from(input, "base64").toString("utf8"); + } : function (input) { + return new Buffer(input, "base64").toString("utf8"); + }, + base64encode: Buffer.from ? function (input) { + return Buffer.from(input).toString("base64"); + } : function (input) { + return new Buffer(input).toString("base64"); + } + }; + return nodeSystem; function isFileSystemCaseSensitive() { if (platform === "win32" || platform === "win64") { return false; @@ -3896,40 +4279,154 @@ var ts; return ch === up ? ch.toLowerCase() : up; }); } - var platform = _os.platform(); - var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + return fsWatchFile; + case "DynamicPriorityPolling": + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + filePathComparer: useCaseSensitiveFileNames ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive, + directoryExists: directoryExists, + getAccessileSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + var fileName = !ts.isString(relativeFileName) + ? undefined + : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } function fsWatchFile(fileName, callback, pollingInterval) { _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; 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) { + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + else if (+curr.mtime === +prev.mtime) { return; } + else { + eventKind = FileWatcherEventKind.Changed; + } callback(fileName, eventKind); } } - function fsWatchDirectory(directoryName, callback, recursive) { + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + if (eventName === "rename") { + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { var options; - var watcher = !directoryExists(directoryName) ? - watchMissingDirectory() : - watchPresentDirectory(); + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); return { close: function () { watcher.close(); + watcher = undefined; } }; - function watchPresentDirectory() { + function invokeCallbackAndUpdateWatcher(createWatcher) { + callback("rename", ""); + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + function watchPresentFileSystemEntry() { if (options === undefined) { if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; @@ -3938,24 +4435,40 @@ var ts; options = { persistent: true }; } } - var dirWatcher = _fs.watch(directoryName, options, callback); - dirWatcher.on("error", function () { - if (!directoryExists(directoryName)) { - watcher = watchMissingDirectory(); - callback("rename", ""); - } - }); - return dirWatcher; + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + return watchPresentFileSystemEntryWithFsWatchFile(); + } } - function watchMissingDirectory() { - return fsWatchFile(directoryName, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { - watcher.close(); - watcher = watchPresentDirectory(); - callback("rename", ""); - } - }); + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); } + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { @@ -4029,11 +4542,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); @@ -4055,103 +4563,23 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - var nodeSystem = { - clearScreen: function () { - process.stdout.write("\x1Bc"); - }, - args: process.argv.slice(2), - newLine: _os.EOL, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - write: function (s) { - process.stdout.write(s); - }, - readFile: readFile, - writeFile: writeFile, - watchFile: function (fileName, callback, pollingInterval) { - if (useNonPollingWatchers) { - var watchedFile_1 = watchedFileSet.addFile(fileName, callback); - return { - close: function () { return watchedFileSet.removeFile(watchedFile_1); } - }; - } - else { - return fsWatchFile(fileName, callback, pollingInterval); - } - }, - watchDirectory: function (directoryName, callback, recursive) { - 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, - directoryExists: directoryExists, - createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { - _fs.mkdirSync(directoryName); - } - }, - getExecutingFilePath: function () { - return __filename; - }, - getCurrentDirectory: function () { - return process.cwd(); - }, - getDirectories: getDirectories, - getEnvironmentVariable: function (name) { - return process.env[name] || ""; - }, - readDirectory: readDirectory, - getModifiedTime: function (path) { - try { - return _fs.statSync(path).mtime; - } - catch (e) { - return undefined; - } - }, - createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, - getMemoryUsage: function () { - if (global.gc) { - global.gc(); - } - return process.memoryUsage().heapUsed; - }, - getFileSize: function (path) { - try { - var stat = _fs.statSync(path); - if (stat.isFile()) { - return stat.size; - } - } - catch (_a) { } - return 0; - }, - exit: function (exitCode) { - process.exit(exitCode); - }, - realpath: function (path) { - try { - return _fs.realpathSync(path); - } - catch (_a) { - return path; - } - }, - debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), - tryEnableSourceMapsForHost: function () { - try { - require("source-map-support").install(); - } - catch (_a) { - } - }, - setTimeout: setTimeout, - clearTimeout: clearTimeout - }; - return nodeSystem; + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -4215,6 +4643,7 @@ var ts; return sys; })(); if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) ? 1 : 0; @@ -4808,6 +5237,7 @@ var ts; Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), 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}'."), @@ -4879,7 +5309,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), 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."), @@ -4919,6 +5349,8 @@ var ts; 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."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), 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."), @@ -5052,7 +5484,7 @@ var ts; Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), - Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), @@ -5096,6 +5528,8 @@ var ts; Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused."), 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."), @@ -5155,6 +5589,7 @@ var ts; 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."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), 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."), @@ -5175,14 +5610,20 @@ var ts; 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"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), 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}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), 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}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{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"), @@ -5219,6 +5660,33 @@ var ts; Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_this_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_this_to_all_unresolved_variables_matching_a_member_name_95037", "Add 'this.' to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), }; })(ts || (ts = {})); var ts; @@ -5430,8 +5898,10 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createMap(); - var moduleNameToDirectoryMap = ts.createMap(); + return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); @@ -5497,7 +5967,7 @@ var ts; } } } - ts.createModuleResolutionCache = createModuleResolutionCache; + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -5508,7 +5978,7 @@ var ts; var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } } else { @@ -5630,7 +6100,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); } - var matchedPattern = undefined; + var matchedPattern; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); @@ -5990,7 +6460,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -6042,6 +6512,7 @@ var ts; } return packageName; } + ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { @@ -6056,12 +6527,13 @@ var ts; typesPackageName; } ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { var result = cache && cache.get(containingDirectory); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } + failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } @@ -6080,7 +6552,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -6327,9 +6799,9 @@ var ts; return false; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; - function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 && + text.charCodeAt(start + 2) === 33; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { @@ -6357,18 +6829,15 @@ var ts; ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } - if (nodeIsMissing(node)) { - return ""; - } - var text = sourceFile.text; - return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; - function getTextOfNodeFromSourceText(sourceText, node) { + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -6443,8 +6912,7 @@ var ts; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 237 && - (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { @@ -6473,18 +6941,19 @@ var ts; } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { - if (!node || !isAmbientModule(node)) { - return false; - } + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { switch (node.parent.kind) { case 272: return ts.isExternalModule(node.parent); case 238: - return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } - ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -6550,6 +7019,10 @@ var ts; } } ts.isAnyImportSyntax = isAnyImportSyntax; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -6608,6 +7081,11 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, startNode.pos); + return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -6919,6 +7397,10 @@ var ts; return false; } ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 231 && node.parent.parent.kind === 212; @@ -7316,6 +7798,10 @@ var ts; return isInJavaScriptFile(file); } ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isSourceFileNotJavaScript(file) { + return !isInJavaScriptFile(file); + } + ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { return node && !!(node.flags & 65536); } @@ -7332,7 +7818,7 @@ var ts; (node.typeArguments[0].kind === 137 || node.typeArguments[0].kind === 134); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { if (callExpression.kind !== 185) { return false; } @@ -7344,7 +7830,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 || arg.kind === 13; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -7355,14 +7841,78 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 230) { - var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 190 || declaration.initializer.kind === 203); + function getJSInitializerSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return symbol; + } + var declaration = symbol.valueDeclaration; + var e = getDeclaredJavascriptInitializer(declaration) || getAssignedJavascriptInitializer(declaration); + return e && e.symbol ? e.symbol : symbol; + } + ts.getJSInitializerSymbol = getJSInitializerSymbol; + function getDeclaredJavascriptInitializer(node) { + if (node && ts.isVariableDeclaration(node) && node.initializer) { + return getJavascriptInitializer(node.initializer, false) || + ts.isIdentifier(node.name) && getDefaultedJavascriptInitializer(node.name, node.initializer, false); + } + } + ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + function getAssignedJavascriptInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + } + ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + function getJavascriptInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 190 || e.kind === 191 ? initializer : undefined; + } + if (initializer.kind === 190 || initializer.kind === 203) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getJavascriptInitializer = getJavascriptInitializer; + function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function getOuterNameOfJsInitializer(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 54 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 58 && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 99 || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); } return false; } - ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; function getRightMostAssignedExpression(node) { while (isAssignmentExpression(node, true)) { node = node.right; @@ -7379,64 +7929,73 @@ var ts; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr)) { - return 0; - } - if (expr.operatorToken.kind !== 58 || expr.left.kind !== 183) { + if (!isInJavaScriptFile(expr) || + expr.operatorToken.kind !== 58 || + !ts.isPropertyAccessExpression(expr.left)) { return 0; } var lhs = expr.left; - if (lhs.expression.kind === 71) { - var lhsId = lhs.expression; - if (lhsId.escapedText === "exports") { - return 1; - } - else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { - return 2; - } - else { - return 5; - } - } - else if (lhs.expression.kind === 99) { + if (lhs.expression.kind === 99) { return 4; } - else if (lhs.expression.kind === 183) { - var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 71) { - var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { - return 1; - } - if (innerPropertyAccess.name.escapedText === "prototype") { - return 3; - } + else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + return 2; + } + else if (isEntityNameExpression(lhs.expression)) { + if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(expr.right)) { + return 6; } + else if (isPrototypeAccess(lhs.expression)) { + return 3; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + return 1; + } + return 5; } return 0; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && expr.parent && expr.parent.kind === 214 && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function importFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 242: + case 248: + return node.parent; + case 252: + return node.parent.parent; + case 185: + return node.parent; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(node)); + } + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; function getExternalModuleName(node) { - if (node.kind === 242) { - return node.moduleSpecifier; - } - if (node.kind === 241) { - var reference = node.moduleReference; - if (reference.kind === 252) { - return reference.expression; - } - } - if (node.kind === 248) { - return node.moduleSpecifier; - } - if (isModuleWithStringLiteralName(node)) { - return node.name; + switch (node.kind) { + case 242: + case 248: + return node.moduleSpecifier; + case 241: + return node.moduleReference.kind === 252 ? node.moduleReference.expression : undefined; + default: + return ts.Debug.assertNever(node); } } ts.getExternalModuleName = getExternalModuleName; @@ -7486,6 +8045,14 @@ var ts; node.expression.operatorToken.kind === 58 && node.expression.right; } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getSpecialPropertyAssignmentKind(node.expression) !== 0 && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 54 && + node.expression.right.right; + } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { case 212: @@ -7519,7 +8086,8 @@ var ts; (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node) { + if (parent && parent.parent && parent.parent.parent && + (getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || @@ -7556,7 +8124,8 @@ var ts; ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { var host = getJSDocHost(node); - var decl = getSourceOfAssignment(host) || + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || @@ -7581,7 +8150,7 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined; + return node.dotDotDotToken !== undefined || node.type && node.type.kind === 281; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -7658,6 +8227,10 @@ var ts; return false; } ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -7672,6 +8245,13 @@ var ts; return walkUp(node, 189); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 189) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; function isDeleteTarget(node) { if (node.kind !== 183 && node.kind !== 184) { return false; @@ -7690,14 +8270,7 @@ var ts; } ts.isNodeDescendantOf = isNodeDescendantOf; function isDeclarationName(name) { - switch (name.kind) { - case 71: - case 9: - case 8: - return ts.isDeclaration(name.parent) && name.parent.name === name; - default: - return false; - } + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; function isAnyDeclarationName(name) { @@ -7776,6 +8349,12 @@ var ts; return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85); return heritageClause ? heritageClause.types : undefined; @@ -7810,38 +8389,6 @@ var ts; return undefined; } ts.getAncestor = getAncestor; - function getFileReferenceFromReferencePath(comment, commentRange) { - var simpleReferenceRegEx = /^\/\/\/\s*= 48 && lookAhead <= 57) { + return "\\x00"; + } + return "\\0"; + } return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { @@ -8570,37 +9118,26 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (ts.hasType(node)) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocType(node); - } + function getEffectiveTypeAnnotationNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; - function getEffectiveReturnTypeNode(node, checkJSDoc) { - if (node.type) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocReturnType(node); - } + function getEffectiveReturnTypeNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { - if (node.typeParameters) { - return node.typeParameters; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; - } + function getEffectiveTypeParameterDeclarations(node) { + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; - function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { + function getJSDocTypeParameterDeclarations(node) { + var templateTag = ts.getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + function getEffectiveSetAccessorTypeAnnotationNode(node) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); + return parameter && getEffectiveTypeAnnotationNode(parameter); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -8685,7 +9222,7 @@ var ts; } return currentDetachedCommentInfo; function isPinnedCommentLocal(comment) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } ts.emitDetachedComments = emitDetachedComments; @@ -8860,10 +9397,17 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 || - node.kind === 183 && isEntityNameExpression(node.expression); + return node.kind === 71 || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 145 && node.parent.right === node) || (node.parent.kind === 183 && node.parent.name === node); @@ -8943,6 +9487,73 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + output += String.fromCharCode(value); + } + else { + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -9262,6 +9873,40 @@ var ts; return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9296,27 +9941,20 @@ var ts; } ts.textSpanContainsTextSpan = textSpanContainsTextSpan; function textSpanOverlapsWith(span, other) { - var overlapStart = Math.max(span.start, other.start); - var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); - return overlapStart < overlapEnd; + return textSpanOverlap(span, other) !== undefined; } ts.textSpanOverlapsWith = textSpanOverlapsWith; function textSpanOverlap(span1, span2) { - var overlapStart = Math.max(span1.start, span2.start); - var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (overlapStart < overlapEnd) { - return createTextSpanFromBounds(overlapStart, overlapEnd); - } - return undefined; + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; } ts.textSpanOverlap = textSpanOverlap; function textSpanIntersectsWithTextSpan(span, other) { - return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); } ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; function textSpanIntersectsWith(span, start, length) { - var end = start + length; - return start <= textSpanEnd(span) && end >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); } ts.textSpanIntersectsWith = textSpanIntersectsWith; function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { @@ -9330,12 +9968,9 @@ var ts; } ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; function textSpanIntersection(span1, span2) { - var intersectStart = Math.max(span1.start, span2.start); - var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (intersectStart <= intersectEnd) { - return createTextSpanFromBounds(intersectStart, intersectEnd); - } - return undefined; + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; } ts.textSpanIntersection = textSpanIntersection; function createTextSpan(start, length) { @@ -9348,6 +9983,12 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; + function createTextRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos); + return { pos: pos, end: end }; + } + ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -9598,6 +10239,10 @@ var ts; return declaration.name || nameForNamelessJSDocTypedef(declaration); } ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + function isNamedDeclaration(node) { + return !!node.name; + } + ts.isNamedDeclaration = isNamedDeclaration; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -9640,31 +10285,31 @@ var ts; 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; }); } - return undefined; + return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 287); + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285); + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 286); + return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 288); + return getFirstJSDocTag(node, ts.isJSDocReturnTag); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 290); + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getJSDocTypeTag(node) { - var tag = getFirstJSDocTag(node, 289); + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -9672,12 +10317,9 @@ var ts; } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 289); - if (!tag && node.kind === 148) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); } return tag && tag.typeExpression && tag.typeExpression.type; } @@ -9695,13 +10337,11 @@ var ts; return tags; } ts.getJSDocTags = getJSDocTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); } function getAllJSDocTagsOfKind(node, kind) { - var tags = getJSDocTags(node); - return ts.filter(tags, function (doc) { return doc.kind === kind; }); + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); @@ -10309,6 +10949,10 @@ var ts; return node.kind === 285; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 286; + } + ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { return node.kind === 287; } @@ -10407,6 +11051,14 @@ var ts; return false; } ts.isModifierKind = isModifierKind; + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 115; + } + ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { return isModifierKind(node.kind); } @@ -10989,6 +11641,43 @@ var ts; return !!node.type; } ts.hasType = hasType; + function couldHaveType(node) { + switch (node.kind) { + case 148: + case 150: + case 151: + case 152: + case 153: + case 154: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 162: + case 163: + case 172: + case 174: + case 176: + case 188: + case 190: + case 191: + case 206: + case 230: + case 232: + case 235: + case 274: + case 277: + case 278: + case 279: + case 280: + case 281: + return true; + } + return false; + } + ts.couldHaveType = couldHaveType; function hasInitializer(node) { return !!node.initializer; } @@ -11016,6 +11705,30 @@ var ts; return node.kind === 161 || node.kind === 205; } ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { return node.kind === 9 || node.kind === 13; } @@ -12625,6 +13338,13 @@ var ts; return token = 26; case 46: return token = 23; + case 96: + while (pos < end && text.charCodeAt(pos) !== 96) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 13; } if (isIdentifierStart(ch, 6)) { while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { @@ -12757,6 +13477,12 @@ var ts; } } } + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 && + text.charCodeAt(start + 2) === 42 && + text.charCodeAt(start + 3) !== 47; + } + ts.isJSDocLikeText = isJSDocLikeText; function forEachChild(node, cbNode, cbNodes) { if (!node || node.kind <= 144) { return; @@ -13112,6 +13838,7 @@ var ts; case 254: case 255: return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); case 261: return visitNodes(cbNode, cbNodes, node.properties); @@ -13325,7 +14052,8 @@ var ts; sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; nextToken(); - processReferenceComments(sourceFile); + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); sourceFile.statements = parseList(0, parseStatement); ts.Debug.assert(token() === 1); sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); @@ -13338,6 +14066,9 @@ var ts; fixupParentReferences(sourceFile); } return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } } function addJSDocComment(node) { var comments = ts.getJSDocCommentRanges(node, sourceFile.text); @@ -13461,9 +14192,7 @@ var ts; return inContext(16384); } function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); } function parseErrorAtPosition(start, length, message, arg0) { var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -13472,9 +14201,14 @@ var ts; } parseErrorBeforeNextFinishedNode = true; } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); + parseErrorAtPosition(scanner.getTextPos(), length, message); } function getNodePos() { return scanner.getStartPos(); @@ -13704,24 +14438,25 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76) { - return nextToken() === 83; + switch (token()) { + case 76: + return nextToken() === 83; + case 84: + nextToken(); + if (token() === 79) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); + case 79: + return nextTokenCanFollowDefaultKeyword(); + case 115: + case 125: + case 136: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === 84) { - nextToken(); - if (token() === 79) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); - } - if (token() === 79) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === 115) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); @@ -14278,9 +15013,20 @@ var ts; nextToken(); return finishNode(node); } - function parseJSDocAllType() { + function parseJSDocAllType(postFixEquals) { var result = createNode(275); + if (postFixEquals) { + return createJSDocPostfixType(279, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(278); nextToken(); + result.type = parseNonArrayType(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { @@ -14318,14 +15064,21 @@ var ts; parameter.name = parseIdentifierName(); parseExpected(56); } - parameter.type = parseType(); + parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocNodeWithType(kind) { - var result = createNode(kind); - nextToken(); - result.type = parseNonArrayType(); - return finishNode(result); + function parseJSDocType() { + var dotdotdot = parseOptionalToken(24); + var type = parseType(); + if (dotdotdot) { + var variadic = createNode(281, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 58) { + return createJSDocPostfixType(279, type); + } + return type; } function parseTypeQuery() { var node = createNode(164); @@ -14653,13 +15406,15 @@ var ts; case 135: return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 39: - return parseJSDocAllType(); + return parseJSDocAllType(false); + case 61: + return parseJSDocAllType(true); case 55: return parseJSDocUnknownOrNullableType(); case 89: return parseJSDocFunctionType(); case 51: - return parseJSDocNodeWithType(278); + return parseJSDocNonNullableType(); case 13: case 9: case 8: @@ -14739,12 +15494,6 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 58: - if (!(contextFlags & 1048576)) { - return type; - } - type = createJSDocPostfixType(279, type); - break; case 51: type = createJSDocPostfixType(278, type); break; @@ -14805,12 +15554,6 @@ var ts; return parseTypeOperator(operator); case 126: return parseInferType(); - case 24: { - var result = createNode(281); - nextToken(); - result.type = parsePostfixTypeOrHigher(); - return finishNode(result); - } } return parsePostfixTypeOrHigher(); } @@ -15248,7 +15991,7 @@ var ts; function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); var consumeCurrentOperator = token() === 40 ? newPrecedence >= precedence : newPrecedence > precedence; @@ -15277,48 +16020,7 @@ var ts; if (inDisallowInContext() && token() === 92) { return false; } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54: - return 1; - case 53: - return 2; - case 49: - return 3; - case 50: - return 4; - case 48: - return 5; - case 32: - case 33: - case 34: - case 35: - return 6; - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: - return 7; - case 45: - case 46: - case 47: - return 8; - case 37: - case 38: - return 9; - case 39: - case 41: - case 42: - return 10; - case 40: - return 11; - } - return -1; + return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { var node = createNode(198, left.pos); @@ -15377,18 +16079,19 @@ var ts; if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); return token() === 40 ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; if (simpleUnaryExpression.kind === 188) { - 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); + parseErrorAt(pos, end, 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 { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; @@ -15505,7 +16208,7 @@ var ts; 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)); + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } @@ -15541,8 +16244,19 @@ var ts; currentToken = scanner.scanJsxToken(); return finishNode(node); } - function parseJsxChild() { - switch (token()) { + function parseJsxChild(openingTag, token) { + switch (token) { + case 1: + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 28: + case 7: + return undefined; case 10: case 11: return parseJsxText(); @@ -15550,8 +16264,9 @@ var ts; return parseJsxExpression(false); case 27: return parseJsxElementOrSelfClosingElementOrFragment(false); + default: + return ts.Debug.assertNever(token); } - ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTag) { var list = []; @@ -15559,27 +16274,10 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; - } - else if (token() === 1) { - 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) { - break; - } - var child = parseJsxChild(); - if (child) { - list.push(child); - } + list.push(child); } parsingContext = saveParsingContext; return createNodeArray(list, listPos); @@ -15593,11 +16291,12 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(27); if (token() === 29) { - parseExpected(29); var node_1 = createNode(258, fullStart); + scanJsxText(); return finishNode(node_1); } var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; if (token() === 29) { @@ -15616,6 +16315,7 @@ var ts; node = createNode(254, fullStart); } node.tagName = tagName; + node.typeArguments = typeArguments; node.attributes = attributes; return finishNode(node); } @@ -15633,7 +16333,9 @@ var ts; } function parseJsxExpression(inExpressionContext) { var node = createNode(263); - parseExpected(17); + if (!parseExpected(17)) { + return undefined; + } if (token() !== 18) { node.dotDotDotToken = parseOptionalToken(24); node.expression = parseAssignmentExpressionOrHigher(); @@ -15691,8 +16393,7 @@ var ts; var node = createNode(259); 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); + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { parseExpected(29); @@ -16057,7 +16758,7 @@ var ts; parseExpected(88); var awaitToken = parseOptionalToken(121); parseExpected(19); - var initializer = undefined; + var initializer; if (token() !== 25) { if (token() === 104 || token() === 110 || token() === 76) { initializer = parseVariableDeclarationList(true); @@ -16633,18 +17334,6 @@ var ts; node.body = parseFunctionBlockOrSemicolon(0); return finishNode(node); } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114: - case 112: - case 113: - case 115: - case 132: - return true; - default: - return false; - } - } function isClassMemberStart() { var idToken; if (token() === 57) { @@ -16652,7 +17341,7 @@ var ts; } while (ts.isModifierKind(token())) { idToken = token(); - if (isClassMemberModifier(idToken)) { + if (ts.isClassMemberModifier(idToken)) { return true; } nextToken(); @@ -17039,7 +17728,7 @@ var ts; node.name = identifierName; } if (kind === 246 && checkIdentifierIsKeyword) { - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } @@ -17071,84 +17760,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); - var referencedFiles = []; - var typeReferenceDirectives = []; - var amdDependencies = []; - var amdModuleName; - var checkJsDirective = undefined; - while (true) { - var kind = triviaScanner.scan(); - if (kind !== 2) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*= pos_2); pos_2 = child.end; - }); + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); ts.Debug.assert(pos_2 <= node.end); } } @@ -17971,6 +18586,12 @@ var ts; child._children = undefined; adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } @@ -18014,15 +18635,15 @@ var ts; var lastNodeEntirelyBeforePosition; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } } return bestResult; - function getLastChild(node) { + function getLastDescendant(node) { while (true) { - var lastChild = getLastChildWorker(node); + var lastChild = ts.getLastChild(node); if (lastChild) { node = lastChild; } @@ -18031,15 +18652,6 @@ var ts; } } } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } function visit(child) { if (ts.nodeIsMissing(child)) { return; @@ -18144,6 +18756,200 @@ var ts; function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); } + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, false, 0, sourceText); + var pragmas = []; + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { + var _b = _a.arguments, name = _b.name, path = _b.path; + return ({ name: name, path: path }); + }); + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; + default: ts.Debug.fail("Unhandled pragma kind"); + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2, singleLine); + } + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; + var multiLineMatch; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4, multiLineMatch); + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -18212,7 +19018,6 @@ var ts; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; - ContainerFlags[ContainerFlags["IsInferenceContainer"] = 256] = "IsInferenceContainer"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -18228,8 +19033,8 @@ var ts; var languageVersion; var parent; var container; + var thisParentContainer; var blockScopeContainer; - var inferenceContainer; var lastContainer; var seenThisKeyword; var currentFlow; @@ -18272,8 +19077,8 @@ var ts; languageVersion = undefined; parent = undefined; container = undefined; + thisParentContainer = undefined; blockScopeContainer = undefined; - inferenceContainer = undefined; lastContainer = undefined; seenThisKeyword = false; currentFlow = undefined; @@ -18303,19 +19108,14 @@ var ts; function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = [node]; - } - else { - symbol.declarations.push(node); - } + symbol.declarations = ts.append(symbol.declarations, node); if (symbolFlags & 1952 && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } if (symbolFlags & 6240 && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 107455) { + if (symbolFlags & 67216319) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 237)) { @@ -18341,7 +19141,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } - return ts.getEscapedTextOfIdentifierOrLiteral(name); + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { case 154: @@ -18368,7 +19168,7 @@ var ts; case 280: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); case 148: - ts.Debug.assert(node.parent.kind === 280); + ts.Debug.assert(node.parent.kind === 280, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -18378,7 +19178,7 @@ var ts; } } function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); } function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); @@ -18406,7 +19206,7 @@ var ts; symbolTable.set(name, symbol = createSymbol(0, name)); } else { - if (node.name) { + if (ts.isNamedDeclaration(node)) { node.name.parent = node; } var message_1 = symbol.flags & 2 @@ -18435,7 +19235,12 @@ var ts; } } addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { @@ -18453,7 +19258,7 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); var isJSDocTypedefInJSDocNamespace = ts.isJSDocTypedefTag(node) && node.name && node.name.kind === 71 && node.name.isInJSDocNamespace; if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = symbolFlags & 107455 ? 1048576 : 0; + var exportKind = symbolFlags & 67216319 ? 1048576 : 0; var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -18466,8 +19271,12 @@ var ts; } function bindContainer(node, containerFlags) { var saveContainer = container; + var saveThisParentContainer = thisParentContainer; var savedBlockScopeContainer = blockScopeContainer; if (containerFlags & 1) { + if (node.kind !== 191) { + thisParentContainer = container; + } container = blockScopeContainer = node; if (containerFlags & 32) { container.locals = ts.createSymbolTable(); @@ -18528,17 +19337,11 @@ var ts; bindChildren(node); node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; } - else if (containerFlags & 256) { - var saveInferenceContainer = inferenceContainer; - inferenceContainer = node; - node.locals = undefined; - bindChildren(node); - inferenceContainer = saveInferenceContainer; - } else { bindChildren(node); } container = saveContainer; + thisParentContainer = saveThisParentContainer; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { @@ -18558,12 +19361,17 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } - function bindEach(nodes) { + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 232 ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 232 ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } if (nodes === undefined) { return; } if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); + ts.forEach(nodes, bindFunction); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -18571,7 +19379,7 @@ var ts; var nodeArrayFlags = 0; for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { var node = nodes_2[_i]; - bind(node); + bindFunction(node); nodeArrayFlags |= node.transformFlags & ~536870912; } nodes.transformFlags = nodeArrayFlags | 536870912; @@ -18667,6 +19475,14 @@ var ts; case 291: bindJSDocTypedefTag(node); break; + case 272: + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + case 211: + case 238: + bindEachFunctionsFirst(node.statements); + break; default: bindEachChild(node); break; @@ -19284,8 +20100,6 @@ var ts; case 235: case 176: return 1 | 32; - case 170: - return 256; case 272: return 1 | 4 | 32; case 153: @@ -19400,7 +20214,7 @@ var ts; if (ts.hasModifier(node, 1)) { errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } - if (ts.isExternalModuleAugmentation(node)) { + if (ts.isModuleAugmentationExternal(node)) { declareModuleSymbol(node); } else { @@ -19414,10 +20228,8 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 67215503); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } else { @@ -19433,7 +20245,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 67215503 : 0); return state; } function bindFunctionOrConstructorType(node) { @@ -19467,8 +20279,8 @@ var ts; continue; } if (currentKind === 1 && existingKind === 1) { - 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)); + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -19506,7 +20318,7 @@ var ts; } } function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 107455); + bindBlockScopedDeclaration(node, 2, 67216319); } function checkStrictModeIdentifier(node) { if (inStrictMode && @@ -19540,8 +20352,8 @@ var ts; } function checkStrictModeDeleteExpression(node) { if (inStrictMode && node.expression.kind === 71) { - 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)); + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -19551,8 +20363,8 @@ var ts; if (name && name.kind === 71) { 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.idText(identifier))); + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -19676,7 +20488,7 @@ var ts; } } function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); return nodeText === '"use strict"' || nodeText === "'use strict'"; } function bindWorker(node) { @@ -19687,7 +20499,7 @@ var ts; while (parentNode && parentNode.kind !== 291) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288, 793064); + bindBlockScopedDeclaration(parentNode, 524288, 67901928); break; } case 99: @@ -19713,13 +20525,16 @@ var ts; bindModuleExportsAssignment(node); break; case 3: - bindPrototypePropertyAssignment(node); + bindPrototypePropertyAssignment(node.left, node); + break; + case 6: + bindPrototypeAssignment(node); break; case 4: bindThisPropertyAssignment(node); break; case 5: - bindStaticPropertyAssignment(node); + bindSpecialPropertyAssignment(node); break; case 0: break; @@ -19743,7 +20558,7 @@ var ts; seenThisKeyword = true; return; case 160: - return checkTypePredicate(node); + break; case 147: return bindTypeParameter(node); case 148: @@ -19760,22 +20575,22 @@ var ts; case 269: return bindPropertyOrMethodOrAccessor(node, 4, 0); case 271: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); + return bindPropertyOrMethodOrAccessor(node, 8, 68008959); case 157: case 158: case 159: return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 153: case 152: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67208127); case 232: return bindFunctionDeclaration(node); case 154: return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 155: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + return bindPropertyOrMethodOrAccessor(node, 32768, 67150783); case 156: - return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + return bindPropertyOrMethodOrAccessor(node, 65536, 67183551); case 162: case 280: case 163: @@ -19799,9 +20614,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 234: - return bindBlockScopedDeclaration(node, 64, 792968); + return bindBlockScopedDeclaration(node, 64, 67901832); case 235: - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 524288, 67901928); case 236: return bindEnumDeclaration(node); case 237: @@ -19845,7 +20660,7 @@ var ts; case 291: { var fullName = node.fullName; if (!fullName || fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 524288, 67901928); } break; } @@ -19857,16 +20672,6 @@ var ts; function bindAnonymousTypeWorker(node) { return bindAnonymousDeclaration(node, 2048, "__type"); } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 173) { - seenThisKeyword = true; - } - bind(type); - } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -19932,7 +20737,18 @@ var ts; } function bindExportsPropertyAssignment(node) { setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, function (id, original) { + if (!original) { + return undefined; + } + var s = ts.getJSInitializerSymbol(original); + addDeclarationToSymbol(s, id, 1536 | 67108864); + return s; + }); + if (symbol) { + declareSymbol(symbol.exports, symbol, lhs, 4 | 1048576, 0); + } } function bindModuleExportsAssignment(node) { var assignedExpression = ts.getRightMostAssignedExpression(node.right); @@ -19945,96 +20761,133 @@ var ts; } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, false); - switch (container.kind) { + var thisContainer = ts.getThisContainer(node, false); + switch (thisContainer.kind) { case 232: case 190: - container.symbol.members = container.symbol.members || ts.createSymbolTable(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + var constructorSymbol = thisContainer.symbol; + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = getJSInitializerSymbolFromName(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4, 0 & ~4); + } break; case 154: case 151: case 153: case 155: case 156: - var containingClass = container.parent; - var symbolTable = ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members; + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); break; + case 272: + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); } } 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 === 183) && - node.parent.parent.kind === 272) { - bindStaticPropertyAssignment(node); - } - } - function bindPrototypePropertyAssignment(node) { - var leftSideOfAssignment = node.left; - var classPrototype = leftSideOfAssignment.expression; - var constructorFunction = classPrototype.expression; - leftSideOfAssignment.parent = node; - constructorFunction.parent = classPrototype; - classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, true); - } - function bindStaticPropertyAssignment(node) { - var leftSideOfAssignment = node.kind === 183 ? node : node.left; - var target = leftSideOfAssignment.expression; - if (ts.isIdentifier(target)) { - target.parent = leftSideOfAssignment; - if (node.kind === 198) { - leftSideOfAssignment.parent = node; - } - if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { - bindExportsPropertyAssignment(node); + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 272) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); } else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + bindStaticPropertyAssignment(node); } } } - function lookupSymbolForName(name) { - return lookupSymbolForNameWorker(container, name); + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs, lhs, false); } - 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 === 198 || propertyAccess.parent.kind === 214); - var isLegalPosition; - if (propertyAccess.parent.kind === 198) { - var initializerKind = propertyAccess.parent.right.kind; - isLegalPosition = (initializerKind === 203 || initializerKind === 190) && - propertyAccess.parent.parent.parent.kind === 272; + function bindPrototypePropertyAssignment(lhs, parent) { + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, true); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + bindExportsPropertyAssignment(node); } else { - isLegalPosition = propertyAccess.parent.parent.kind === 272; + bindStaticPropertyAssignment(lhs); } - 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); - } + } + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, false); + } + function getJSInitializerSymbolFromName(name, lookupContainer) { + return ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(name, lookupContainer)); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var symbol = getJSInitializerSymbolFromName(name); + var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) + ? propertyAccess.parent.parent.parent.kind === 272 && + !!ts.getJavascriptInitializer(propertyAccess.parent.right, ts.isPrototypeAccess(propertyAccess.parent.left)) + : propertyAccess.parent.parent.kind === 272; + if (!isPrototypeProperty && (!symbol || !(symbol.flags & 1920)) && isToplevelNamespaceableInitializer) { + var flags_1 = 1536 | 67108864; + var excludeFlags_1 = 67215503 & ~67108864; + forEachIdentifierInEntityName(propertyAccess.expression, function (id, original) { + if (original) { + addDeclarationToSymbol(original, id, flags_1); + return original; + } + else { + return symbol = declareSymbol(symbol ? symbol.exports : container.locals, symbol, id, flags_1, excludeFlags_1); + } + }); } - if (!targetSymbol || !(targetSymbol.flags & (16 | 32 | 1024))) { + if (!symbol || !(symbol.flags & (16 | 32 | 1024 | 4096))) { return; } var symbolTable = isPrototypeProperty ? - (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : - (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); - declareSymbol(symbolTable, targetSymbol, propertyAccess, 4, 0); + (symbol.members || (symbol.members = ts.createSymbolTable())) : + (symbol.exports || (symbol.exports = ts.createSymbolTable())); + var symbolFlags = 4 | (isToplevelNamespaceableInitializer ? 67108864 : 0); + var symbolExcludes = 0 & ~(isToplevelNamespaceableInitializer ? 67108864 : 0); + declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(node.expression)); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e)); + } + else { + var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); + ts.Debug.assert(!!s && !!s.exports); + return action(e.name, s.exports.get(e.name.escapedText)); + } } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { @@ -20043,7 +20896,7 @@ var ts; } function bindClassLikeDeclaration(node) { if (node.kind === 233) { - bindBlockScopedDeclaration(node, 32, 899519); + bindBlockScopedDeclaration(node, 32, 68008383); } else { var bindingName = node.name ? node.name.escapedText : "__class"; @@ -20066,8 +20919,8 @@ var ts; } function bindEnumDeclaration(node) { return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128, 899967) - : bindBlockScopedDeclaration(node, 256, 899327); + ? bindBlockScopedDeclaration(node, 128, 68008831) + : bindBlockScopedDeclaration(node, 256, 68008191); } function bindVariableDeclarationOrBindingElement(node) { if (inStrictMode) { @@ -20078,10 +20931,10 @@ var ts; bindBlockScopedVariableDeclaration(node); } else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 107455); + declareSymbolAndAddToSymbolTable(node, 1, 67216319); } else { - declareSymbolAndAddToSymbolTable(node, 1, 107454); + declareSymbolAndAddToSymbolTable(node, 1, 67216318); } } } @@ -20093,7 +20946,7 @@ var ts; bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1, 107455); + declareSymbolAndAddToSymbolTable(node, 1, 67216319); } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; @@ -20109,10 +20962,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 106927); + bindBlockScopedDeclaration(node, 16, 67215791); } else { - declareSymbolAndAddToSymbolTable(node, 16, 106927); + declareSymbolAndAddToSymbolTable(node, 16, 67215791); } } function bindFunctionExpression(node) { @@ -20139,20 +20992,31 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + function getInferTypeContainer(node) { + while (node) { + var parent_2 = node.parent; + if (parent_2 && parent_2.kind === 170 && parent_2.extendsType === node) { + return parent_2; + } + node = parent_2; + } + return undefined; + } function bindTypeParameter(node) { if (node.parent.kind === 171) { - if (inferenceContainer) { - if (!inferenceContainer.locals) { - inferenceContainer.locals = ts.createSymbolTable(); + var container_1 = getInferTypeContainer(node.parent); + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); } - declareSymbol(inferenceContainer.locals, undefined, node, 262144, 530920); + declareSymbol(container_1.locals, undefined, node, 262144, 67639784); } else { bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144, 530920); + declareSymbolAndAddToSymbolTable(node, 262144, 67639784); } } function shouldReportErrorOnModuleDeclaration(node) { @@ -21278,7 +22142,7 @@ var ts; node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (node) { node = ts.getParseTreeNode(node, ts.isParameter); return node ? isOptionalParameter(node) : false; @@ -21315,7 +22179,7 @@ var ts; resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals); }, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, @@ -21327,13 +22191,13 @@ var ts; node = ts.getParseTreeNode(node, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, + getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; }, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); - var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4, "unknown"); @@ -21395,6 +22259,7 @@ var ts; var anyArrayType; var autoArrayType; var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; var deferredGlobalESSymbolConstructorSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; @@ -21408,11 +22273,9 @@ var ts; var deferredGlobalAsyncIteratorType; var deferredGlobalAsyncIterableIteratorType; var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; var deferredNodes; var deferredUnusedIdentifierNodes; + var seenDeferredUnusedIdentifiers = ts.createMap(); var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -21437,6 +22300,18 @@ var ts; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); + var suggestionDiagnostics = ts.createMultiMap(); + function addSuggestionDiagnostic(diag) { + suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + function addErrorOrSuggestionDiagnostic(isError, diag) { + if (isError) { + diagnostics.add(diag); + } + else { + addSuggestionDiagnostic(diag); + } + } var TypeFacts; (function (TypeFacts) { TypeFacts[TypeFacts["None"] = 0] = "None"; @@ -21462,8 +22337,7 @@ var ts; 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["All"] = 4194303] = "All"; TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; @@ -21490,10 +22364,10 @@ var ts; 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["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); @@ -21525,11 +22399,6 @@ var ts; var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - var jsxTypes = ts.createUnderscoreEscapedMap(); var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var definitelyAssignableRelation = ts.createMap(); @@ -21585,6 +22454,7 @@ var ts; TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType"; TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject"; TypeIncludes[TypeIncludes["Union"] = 2048] = "Union"; + TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard"; })(TypeIncludes || (TypeIncludes = {})); var MembersOrExportsResolutionKind; (function (MembersOrExportsResolutionKind) { @@ -21729,7 +22599,23 @@ var ts; }; } } - function getJsxNamespace() { + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } if (!_jsxNamespace) { _jsxNamespace = "React"; if (compilerOptions.jsxFactory) { @@ -21766,35 +22652,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2) - result |= 107455; + result |= 67216319; if (flags & 1) - result |= 107454; + result |= 67216318; if (flags & 4) result |= 0; if (flags & 8) - result |= 900095; + result |= 68008959; if (flags & 16) - result |= 106927; + result |= 67215791; if (flags & 32) - result |= 899519; + result |= 68008383; if (flags & 64) - result |= 792968; + result |= 67901832; if (flags & 256) - result |= 899327; + result |= 68008191; if (flags & 128) - result |= 899967; + result |= 68008831; if (flags & 512) - result |= 106639; + result |= 67215503; if (flags & 8192) - result |= 99263; + result |= 67208127; if (flags & 32768) - result |= 41919; + result |= 67150783; if (flags & 65536) - result |= 74687; + result |= 67183551; if (flags & 262144) - result |= 530920; + result |= 67639784; if (flags & 524288) - result |= 793064; + result |= 67901928; if (flags & 2097152) result |= 2097152; return result; @@ -21823,7 +22709,7 @@ var ts; } function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - source.flags & 67108864 || target.flags & 67108864) { + (source.flags | target.flags) & 67108864) { if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; } @@ -21844,6 +22730,13 @@ var ts; target.exports = ts.createSymbolTable(); mergeSymbolTable(target.exports, source.exports); } + if ((source.flags | target.flags) & 67108864) { + var sourceInitializer = ts.getJSInitializerSymbol(source); + var targetInitializer = ts.getJSInitializerSymbol(target); + if (sourceInitializer !== source || targetInitializer !== target) { + mergeSymbol(targetInitializer, sourceInitializer); + } + } recordMergedSymbol(target, source); } else if (target.flags & 1024) { @@ -21856,10 +22749,12 @@ var ts; ? 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)); + var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); } } @@ -21962,8 +22857,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -22065,18 +22960,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 !== 282) { + if (meaning & result.flags & 67901928 && lastLocation.kind !== 282) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 148 || lastLocation.kind === 147 : false; } - if (meaning & 107455 && result.flags & 1) { + if (meaning & 67216319 && result.flags & 1) { useResult = lastLocation.kind === 148 || (lastLocation === location.type && - result.valueDeclaration.kind === 148); + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } else if (location.kind === 170) { @@ -22126,7 +23021,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 67216319)) { propertyWithInvalidInitializer = location; } } @@ -22135,7 +23030,7 @@ var ts; case 233: case 203: case 234: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064)) { + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -22157,7 +23052,7 @@ var ts; case 205: 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))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -22168,7 +23063,7 @@ var ts; case 146: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 234) { - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -22259,13 +23154,13 @@ var ts; } if (errorLocation && (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455))) { + ((meaning & 32 || meaning & 384) && (meaning & 67216319) === 67216319))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 107455) === 107455) { + if (result && isInExternalModule && (meaning & 67216319) === 67216319) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 240) { 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)); @@ -22350,8 +23245,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~1920, undefined, undefined, false)); + var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(errorLocation) ? 67216319 : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~namespaceMeaning, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -22370,12 +23266,12 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (107455 & ~1024)) { + if (meaning & (67216319 & ~1024)) { 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)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~67216319, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; @@ -22384,15 +23280,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 & (67216319 & ~1024 & ~67901928)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67216319, undefined, undefined, 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, (512 | 1024) & ~793064, undefined, undefined, false)); + else if (meaning & (67901928 & ~1024 & ~67216319)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67901928, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -22448,12 +23344,16 @@ var ts; ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512)); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { return false; } if (!file || file.isDeclarationFile) { - if (resolveExportByName(moduleSymbol, "default", dontResolveAlias)) { + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default", dontResolveAlias); + if (defaultExportSymbol && defaultExportSymbol.valueDeclaration && isSyntacticDefault(defaultExportSymbol.valueDeclaration)) { return false; } if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { @@ -22481,7 +23381,7 @@ var ts; if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && hasSyntheticDefault) { + else if (hasSyntheticDefault) { return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -22495,7 +23395,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (793064 | 1920)) { + if (valueSymbol.flags & (67901928 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -22547,7 +23447,15 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + var moduleName = getFullyQualifiedName(moduleSymbol); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } return symbol; } @@ -22565,7 +23473,7 @@ var ts; resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); + return resolveEntityName(node.expression, 67216319 | 67901928 | 1920, false, dontResolveAlias); } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { @@ -22578,7 +23486,7 @@ var ts; case 246: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 250: - return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67216319 | 67901928 | 1920, dontRecursivelyResolve); case 247: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 240: @@ -22586,7 +23494,7 @@ var ts; } } function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 107455 | 793064 | 1920; } + if (excludes === void 0) { excludes = 67216319 | 67901928 | 1920; } return symbol && (symbol.flags & (2097152 | excludes)) === 2097152; } function resolveSymbol(symbol, dontResolveAlias) { @@ -22618,7 +23526,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67216319) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -22650,7 +23558,7 @@ var ts; } else { ts.Debug.assert(entityName.parent.kind === 241); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 67216319 | 67901928 | 1920, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -22660,35 +23568,43 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } + var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(name) ? meaning & 67216319 : 0); var symbol; if (name.kind === 71) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === namespaceMeaning ? 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 (!symbol) { return undefined; } } else if (name.kind === 145 || name.kind === 183) { - var left = void 0; - if (name.kind === 145) { - left = name.left; - } - else if (name.kind === 183) { - left = name.expression; - } - else { - return undefined; - } + var left = name.kind === 145 ? name.left : name.expression; var right = name.kind === 145 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); + var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, 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); + if (ts.isInJavaScriptFile(name)) { + var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + if (initializer) { + namespace = getSymbolOfNode(initializer); + } + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { @@ -22732,6 +23648,9 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + } return getMergedSymbol(sourceFile.symbol); } if (moduleNotFoundError) { @@ -22750,10 +23669,8 @@ var ts; 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.packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + else { + addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); } return undefined; } @@ -22774,6 +23691,11 @@ var ts; } return undefined; } + function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)); + return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; } @@ -22934,7 +23856,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 107455); + return !!(symbol.flags & 67216319 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67216319); } function findConstructorDeclaration(node) { var members = node.members; @@ -23027,13 +23949,21 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; + return rightMeaning === 67216319 ? 67216319 : 1920; } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { return undefined; } - var visitedSymbolTables = []; + var id = "" + getSymbolId(symbol); + var visitedSymbolTables; + if (visitedSymbolTablesMap.has(id)) { + visitedSymbolTables = visitedSymbolTablesMap.get(id); + } + else { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { @@ -23045,7 +23975,7 @@ var ts; } function canQualifySymbol(symbolFromSymbolTable, meaning) { return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || - !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && @@ -23059,6 +23989,7 @@ var ts; return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 && symbolFromSymbolTable.escapedName !== "export=" + && symbolFromSymbolTable.escapedName !== "default" && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -23112,11 +24043,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928, false); return access.accessibility === 0; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319, false); return access.accessibility === 0; } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { @@ -23192,14 +24123,14 @@ var ts; if (entityName.parent.kind === 164 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 146) { - meaning = 107455 | 1048576; + meaning = 67216319 | 1048576; } else if (entityName.kind === 145 || entityName.kind === 183 || entityName.parent.kind === 241) { meaning = 1920; } else { - meaning = 793064; + meaning = 67901928; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); @@ -23249,6 +24180,7 @@ var ts; } } function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576; } if (writer === void 0) { writer = ts.createTextWriter(""); } var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); @@ -23331,7 +24263,8 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined + symbolStack: undefined, + inferTypeParameters: undefined }; } function typeToTypeNodeHelper(type, context) { @@ -23355,12 +24288,12 @@ var ts; } if (type.flags & 256 && !(type.flags & 131072)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 793064, false); + var parentName = symbolToName(parentSymbol, context, 67901928, false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 272) { - var name = symbolToName(type.symbol, context, 793064, false); + var name = symbolToName(type.symbol, context, 67901928, false); return ts.createTypeReferenceNode(name, undefined); } if (type.flags & (32)) { @@ -23374,6 +24307,9 @@ var ts; } if (type.flags & 1024) { if (!(context.flags & 1048576)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeQueryNode(symbolToName(type.symbol, context, 67216319, false)); + } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } @@ -23415,7 +24351,10 @@ var ts; return typeReferenceToTypeNode(type); } if (type.flags & 32768 || objectFlags & 3) { - var name = type.symbol ? symbolToName(type.symbol, context, 793064, false) : ts.createIdentifier("?"); + if (type.flags & 32768 && ts.contains(context.inferTypeParameters, type)) { + return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + } + var name = type.symbol ? symbolToName(type.symbol, context, 67901928, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { @@ -23453,13 +24392,16 @@ var ts; } if (type.flags & 2097152) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); - var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); - var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 4194304) { - return typeToTypeNodeHelper(type.typeParameter, context); + return typeToTypeNodeHelper(type.typeVariable, context); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { @@ -23477,12 +24419,12 @@ var ts; if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 203 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455); + return createTypeQueryNodeFromSymbol(symbol, 67216319); } else if (ts.contains(context.symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, context, 793064, false); + var entityName = symbolToName(typeAlias, context, 67901928, false); return ts.createTypeReferenceNode(entityName, undefined); } else { @@ -23554,7 +24496,7 @@ var ts; return ts.createTypeQueryNode(entityName); } function symbolToTypeReferenceName(symbol) { - var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928, false) : ts.createIdentifier(""); return entityName; } function typeReferenceToTypeNode(type) { @@ -23582,7 +24524,8 @@ var ts; } else if (context.flags & 2048 && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 203) { + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } else { @@ -23613,7 +24556,7 @@ var ts; } } } - var entityName = undefined; + var entityName = void 0; var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); @@ -23688,12 +24631,12 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319); if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455); + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); } } - var propertyName = symbolToName(propertySymbol, context, 107455, true); + var propertyName = symbolToName(propertySymbol, context, 67216319, true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { @@ -23783,7 +24726,7 @@ var ts; if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } var savedContextFlags = context.flags; context.flags &= ~512; - var name = symbolToName(type.symbol, context, 793064, true); + var name = symbolToName(type.symbol, context, 67901928, true); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); @@ -24008,9 +24951,6 @@ var ts; node.parent.kind === 238 && ts.isExternalModuleAugmentation(node.parent.parent); } - function literalTypeToString(type) { - return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; - } function isDefaultBindingContext(location) { return location.kind === 272 || ts.isAmbientModule(location); } @@ -24041,8 +24981,8 @@ var ts; return "(Anonymous function)"; } } - if (symbol.syntheticLiteralTypeOrigin) { - var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (symbol.nameType && symbol.nameType.flags & 32) { + var stringValue = symbol.nameType.value; if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { return "\"" + ts.escapeString(stringValue, 34) + "\""; } @@ -24126,10 +25066,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 247) { - exportSymbol = resolveName(node, node.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, node, false); + exportSymbol = resolveName(node, node.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, node, false); } else if (node.parent.kind === 250) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 | 67901928 | 1920 | 2097152); } var result; if (exportSymbol) { @@ -24149,7 +25089,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { 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, 67216319 | 67901928 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -24304,8 +25244,7 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var propType = getTypeOfPropertyOfType(parentType, text); - var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); + var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); @@ -24374,7 +25313,8 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); if (declaredType) { return addOptionality(declaredType, isOptional); @@ -24427,12 +25367,18 @@ var ts; return undefined; } function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); + if (specialDeclaration) { + return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + } var types = []; + var constructorTypes; var definedInConstructor = false; var definedInMethod = false; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; + var declarationInConstructor = false; var expression = declaration.kind === 198 ? declaration : declaration.kind === 183 ? ts.getAncestor(declaration, 198) : undefined; @@ -24440,7 +25386,11 @@ var ts; return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { - if (ts.getThisContainer(expression, false).kind === 154) { + var thisContainer = ts.getThisContainer(expression, false); + declarationInConstructor = thisContainer.kind === 154 || + thisContainer.kind === 232 || + (thisContainer.kind === 190 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + if (declarationInConstructor) { definedInConstructor = true; } else { @@ -24460,11 +25410,33 @@ var ts; } } else if (!jsDocType) { - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); + var anyedType = type_2; + if (isEmptyArrayLiteralType(type_2)) { + anyedType = anyArrayType; + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + } + types.push(anyedType); + if (declarationInConstructor) { + (constructorTypes || (constructorTypes = [])).push(anyedType); + } } } - var type = jsDocType || getUnionType(types, 2); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + var type = jsDocType; + if (!type) { + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 | 16777216)); }) ? constructorTypes : types; + type = getUnionType(sourceTypes, 2); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~12288); }) === neverType) { + if (noImplicitAny) { + reportImplicitAnyError(symbol.valueDeclaration, anyType); + } + return anyType; + } + return widened; } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { @@ -24481,11 +25453,11 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var hasComputedProperties = false; + var objectFlags = 128; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (isComputedNonLiteralName(name)) { - hasComputedProperties = true; + objectFlags |= 512; return; } if (e.dotDotDotToken) { @@ -24500,12 +25472,11 @@ var ts; members.set(symbol.escapedName, symbol); }); var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 33554432; + result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; } - if (hasComputedProperties) { - result.objectFlags |= 512; - } return result; } function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { @@ -24727,7 +25698,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 107455 + links.type = targetSymbol.flags & 67216319 ? getTypeOfSymbol(targetSymbol) : unknownType; } @@ -25062,7 +26033,7 @@ 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); + var baseSymbol = resolveEntityName(node.expression, 67901928, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -25364,7 +26335,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 107455) { + if (symbolFlags & 67216319) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; @@ -25391,8 +26362,17 @@ var ts; error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); lateSymbol = createSymbol(0, memberName, 1024); } + var symbolLinks_1 = getSymbolLinks(lateSymbol); + if (!symbolLinks_1.nameType) { + symbolLinks_1.nameType = type; + } addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); - lateSymbol.parent = parent; + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } return links.resolvedSymbol = lateSymbol; } } @@ -25575,7 +26555,7 @@ var ts; } return [signature]; } - var result = undefined; + var result; for (var i = 0; i < signatureLists.length; i++) { var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); if (!match) { @@ -25587,7 +26567,7 @@ var ts; } function getUnionSignatures(types, kind) { var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); - var result = undefined; + var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; @@ -25703,7 +26683,7 @@ var ts; } else { var members = emptySymbols; - var stringIndexInfo = undefined; + var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); } @@ -25783,11 +26763,10 @@ var ts; if (typeof propertySymbolOrIndex === "object") { propertySymbol = propertySymbolOrIndex; } - var iterationMapper = createTypeMapper([typeParameter], [t]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { - var propName = ts.escapeLeadingUnderscores(t.value); + var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 || !(templateModifiers & 8) && modifiersProp && modifiersProp.flags & 16777216); @@ -25801,7 +26780,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } - prop.syntheticLiteralTypeOrigin = t; + prop.nameType = t; members.set(propName, prop); } else if (t.flags & (1 | 2)) { @@ -25971,16 +26950,14 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getDefaultConstraintOfConditionalType(type) { - return getUnionType([type.trueType, type.falseType]); + return getUnionType([getInferredTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); } function getConstraintOfDistributiveConditionalType(type) { - if (isDistributiveConditionalType(type)) { + if (type.root.isDistributive) { var constraint = getConstraintOfType(type.checkType); if (constraint) { - var target = type.target || type; - var mapper = createTypeMapper([target.checkType], [constraint]); - var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper; - return instantiateType(target, combinedMapper); + var mapper = createTypeMapper([type.root.checkType], [constraint]); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); } } return undefined; @@ -25988,17 +26965,23 @@ var ts; function getConstraintOfConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } - function getBaseConstraintOfType(type) { + function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { if (type.flags & (7372800 | 393216)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 524288) { + } + function getBaseConstraintOfType(type) { + var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); + if (!constraint && type.flags & 524288) { return stringType; } - return undefined; + return constraint; + } + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; } function hasNonCircularBaseConstraint(type) { return getResolvedBaseConstraint(type) !== circularConstraintType; @@ -26033,8 +27016,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -26057,7 +27040,8 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 2097152) { - return getBaseConstraint(getConstraintOfConditionalType(t)); + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); } if (t.flags & 4194304) { return getBaseConstraint(t.substitute); @@ -26149,7 +27133,7 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; + var commonType; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; if (prop.declarations) { @@ -26265,23 +27249,11 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 279) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 279; - } - } - } - } + return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 279 + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 279; + })); } function tryFindAmbientModule(moduleName, withAugmentations) { if (ts.isExternalModuleNameRelative(moduleName)) { @@ -26365,16 +27337,20 @@ var ts; var parameters = []; var hasLiteralTypes = false; var minArgumentCount = 0; - var thisParameter = undefined; + var thisParameter = void 0; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJavaScriptFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); 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); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -26389,8 +27365,8 @@ var ts; } var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -26415,14 +27391,14 @@ var ts; return links.resolvedSignature; } function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (!containsArgumentsReference(declaration)) { + return false; + } var lastParam = ts.lastOrUndefined(declaration.parameters); - var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); var lastParamVariadicType = 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; @@ -26485,29 +27461,15 @@ var ts; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; - switch (node.kind) { - case 162: - case 163: - case 232: - case 153: - case 152: - case 154: - case 157: - case 158: - case 159: - case 155: - case 156: - case 190: - case 191: - case 280: - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); + if (!ts.isFunctionLike(node)) + continue; + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + continue; + } } + result.push(getSignatureFromDeclaration(node)); } return result; } @@ -26603,7 +27565,10 @@ var ts; return instantiation; } function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); } function getErasedSignature(signature) { return signature.typeParameters ? @@ -26859,20 +27824,19 @@ var ts; var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 32768 ? getConstrainedTypeParameter(res, node) : res : + res.flags & 32768 ? getConstrainedTypeVariable(res, node) : res : unknownType; } - if (!(symbol.flags & 107455 && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67216319 && isJSDocTypeReference(node))) { return unknownType; } + var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + var referenceType = valueType.symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType || assignedType) { + return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; } - resolveTypeReferenceName(getTypeReferenceName(node), 793064); + resolveTypeReferenceName(getTypeReferenceName(node), 67901928); return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -26888,24 +27852,33 @@ var ts; return getInferredClassType(symbol); } } - function getSubstitutionType(typeParameter, substitute) { + function getSubstitutionType(typeVariable, substitute) { var result = createType(4194304); - result.typeParameter = typeParameter; + result.typeVariable = typeVariable; result.substitute = substitute; return result; } - function getConstrainedTypeParameter(typeParameter, node) { + function isUnaryTupleTypeNode(node) { + return node.kind === 167 && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { var constraints; while (ts.isPartOfTypeNode(node)) { var parent = node.parent; if (parent.kind === 170 && node === parent.trueType) { - if (getTypeFromTypeNode(parent.checkType) === typeParameter) { - constraints = ts.append(constraints, getTypeFromTypeNode(parent.extendsType)); + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); } } node = parent; } - return constraints ? getSubstitutionType(typeParameter, getIntersectionType(ts.append(constraints, typeParameter))) : typeParameter; + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { return node.flags & 1048576 && node.kind === 161; @@ -26973,10 +27946,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 793064; + var meaning = 67901928; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 107455; + meaning |= 67216319; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -27025,10 +27998,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67216319, 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, 67901928, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name, false); @@ -27078,14 +28051,9 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064, undefined); + var symbol = getGlobalSymbol(name, 67901928, undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } - function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); - return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); - } function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; } @@ -27185,6 +28153,8 @@ var ts; } else if (flags & 1) { includes |= 1; + if (type === wildcardType) + includes |= 4096; } else if (!strictNullChecks && flags & 12288) { if (flags & 4096) @@ -27292,7 +28262,7 @@ var ts; var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); if (includes & 1) { - return anyType; + return includes & 4096 ? wildcardType : anyType; } switch (unionReduction) { case 1: @@ -27376,6 +28346,8 @@ var ts; } else if (flags & 1) { includes |= 1; + if (type === wildcardType) + includes |= 4096; } else if (flags & 16384) { includes |= 8; @@ -27414,7 +28386,7 @@ var ts; return neverType; } if (includes & 1) { - return anyType; + return includes & 4096 ? wildcardType : anyType; } if (includes & 1024 && !(includes & 512)) { typeSet.push(emptyObjectType); @@ -27454,19 +28426,29 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ? - neverType : - getLiteralType(ts.symbolName(prop)); + var links = getSymbolLinks(getLateBoundSymbol(prop)); + if (!links.nameType) { + if (links.target && links.target !== unknownSymbol && links.target !== resolvingSymbol && links.target.escapedName === prop.escapedName) { + links.nameType = getLiteralTypeFromPropertyName(links.target); + } + else { + links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ? + neverType : + getLiteralType(ts.symbolName(prop)); + } + } + return links.nameType; } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 7372800) ? getIndexTypeForGenericType(type) : - ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : - type === wildcardType ? wildcardType : - type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : - getLiteralTypeFromPropertyNames(type); + return type.flags & 262144 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) : + maybeTypeOfKind(type, 7372800) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); @@ -27529,6 +28511,9 @@ var ts; } return indexInfo.type; } + if (indexType.flags & 16384) { + return neverType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (getIndexTypeOfType(objectType, 1)) { @@ -27612,10 +28597,13 @@ var ts; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper; + var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 184) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; @@ -27645,7 +28633,13 @@ var ts; function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 1048576 && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; } return links.resolvedType; } @@ -27661,57 +28655,57 @@ var ts; } return links.resolvedType; } - function getActualTypeParameter(type) { - return type.flags & 4194304 ? type.typeParameter : type; + function getActualTypeVariable(type) { + return type.flags & 4194304 ? type.typeVariable : type; } - function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) { - var type = createType(2097152); - type.checkType = checkType; - type.extendsType = extendsType; - type.trueType = trueType; - type.falseType = falseType; - type.inferTypeParameters = inferTypeParameters; - type.target = target; - type.mapper = mapper; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - return type; - } - function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) { - var extendsType = instantiateType(baseExtendsType, mapper); - if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) { - return instantiateType(baseFalseType, mapper); + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; } + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088); var combinedMapper; - if (inferTypeParameters) { - var inferences = ts.map(inferTypeParameters, createInferenceInfo); - inferTypes(inferences, checkType, extendsType, 8 | 16); - var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; }); - var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes); - combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, undefined, 0); + if (!isDeferred) { + inferTypes(context.inferences, checkType, extendsType, 32 | 64); + } + combinedMapper = combineTypeMappers(mapper, context); } - if (checkType.flags & 1 || (checkType.flags & 16384 && !(extendsType.flags & 16384))) { - return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]); + if (!isDeferred) { + if (checkType.flags & 1) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } } - var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType; - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) { - return instantiateType(baseTrueType, combinedMapper || mapper); - } - var erasedCheckType = getActualTypeParameter(checkType); - var trueType = instantiateType(baseTrueType, mapper); - var falseType = instantiateType(baseFalseType, mapper); - var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 ? 1 : 0; - var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive; - var cached = conditionalTypes.get(id); - if (cached) { - return cached; - } - var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper)); - conditionalTypes.set(id, result); + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(2097152); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); return result; } - function isDistributiveConditionalType(type) { - return !!((type.target || type).checkType.flags & 32768); + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferredTrueTypeFromConditionalType(type) { + return type.combinedMapper ? + type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper)) : + getTrueTypeFromConditionalType(type); } function getInferTypeParameters(node) { var result; @@ -27727,7 +28721,28 @@ var ts; function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), undefined, undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var checkType = getTypeFromTypeNode(node.checkType); + var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var allOuterTypeParameters = getOuterTypeParameters(node, true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 32768), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: getAliasSymbolForTypeNode(node), + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } } return links.resolvedType; } @@ -27971,9 +28986,10 @@ var ts; return getTypeFromIntersectionTypeNode(node); case 277: return getTypeFromJSDocNullableTypeNode(node); + case 279: + return addOptionality(getTypeFromTypeNode(node.type)); case 172: case 278: - case 279: case 274: return getTypeFromTypeNode(node.type); case 281: @@ -28054,14 +29070,18 @@ var ts; return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { - return !!mapper.signature; + return !!mapper.typeParameters; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { @@ -28162,8 +29182,8 @@ var ts; } 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 === 211 ? "quit" : n === container_1; })) { + var container_2 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 211 ? "quit" : n === container_2; })) { return ts.forEachChild(node, containsReference); } } @@ -28213,19 +29233,29 @@ var ts; return result; } function getConditionalTypeInstantiation(type, mapper) { - var target = type.target || type; - var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - if (isDistributiveConditionalType(target)) { - var checkType_1 = target.checkType; - var instantiatedType = combinedMapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072) { - return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); }); + var root = type.root; + if (root.outerTypeParameters) { + var typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 | 16384)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } - return instantiateConditionalType(target, combinedMapper); - } - function instantiateConditionalType(type, mapper) { - return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments); + return getConditionalType(root, mapper); } function instantiateType(type, mapper) { if (type && mapper && mapper !== identityMapper) { @@ -28263,10 +29293,10 @@ var ts; return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } if (type.flags & 2097152) { - return getConditionalTypeInstantiation(type, mapper); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } if (type.flags & 4194304) { - return mapper(type.typeParameter); + return instantiateType(type.typeVariable, mapper); } } return type; @@ -28324,7 +29354,8 @@ var ts; return node.body.kind === 211 ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { if (type.flags & 65536) { @@ -28730,10 +29761,10 @@ var ts; target = target.regularType; } if (source.flags & 4194304) { - source = relation === definitelyAssignableRelation ? source.typeParameter : source.substitute; + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } if (target.flags & 4194304) { - target = target.typeParameter; + target = target.typeVariable; } if (source === target) return -1; @@ -28838,11 +29869,11 @@ var ts; } } if (flags & 2097152) { - if (result = isRelatedTo(source.checkType, target.checkType, false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result &= isRelatedTo(source.trueType, target.trueType, false)) { - if (result &= isRelatedTo(source.falseType, target.falseType, false)) { - if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result = isRelatedTo(source.checkType, target.checkType, false)) { + if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { return result; } } @@ -29188,20 +30219,11 @@ var ts; } } else if (source.flags & 2097152) { - if (relation !== definitelyAssignableRelation) { - var constraint = getConstraintOfDistributiveConditionalType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } if (target.flags & 2097152) { - if (isTypeIdenticalTo(source.checkType, target.checkType) && - isTypeIdenticalTo(source.extendsType, target.extendsType)) { - if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { - result &= isRelatedTo(source.falseType, target.falseType, reportErrors); + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -29209,9 +30231,21 @@ var ts; } } } - else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } } else { @@ -29499,6 +30533,10 @@ var ts; if (isIgnoredJsxProperty(source, prop, undefined)) { continue; } + var nameType = getLiteralTypeFromPropertyName(prop); + if (nameType !== undefined && !(isRelatedTo(nameType, stringType) || isRelatedTo(nameType, numberType))) { + continue; + } if (kind === 0 || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -29933,8 +30971,17 @@ var ts; ts.Debug.assert(strictNullChecks); return type.flags & 4096 ? type : getUnionType([type, undefinedType]); } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288, undefined) || unknownSymbol; + } + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 524288); + } function getNonNullableType(type) { - return strictNullChecks ? getTypeWithFacts(type, 524288) : type; + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; } function isObjectTypeWithInferableIndex(type) { return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 && @@ -30027,6 +31074,10 @@ var ts; } var result = createSymbol(4 | 16777216, name); result.type = undefinedType; + var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name)); + if (associatedKeyType.flags & 32) { + result.nameType = associatedKeyType; + } undefinedProperties.set(name, result); return result; } @@ -30113,6 +31164,7 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 198: case 151: case 150: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; @@ -30173,9 +31225,10 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, compareTypes, baseInferences) { - var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); var context = mapper; + context.typeParameters = typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -30282,7 +31335,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return getTypeFromInference(inference) || emptyObjectType; + return getTypeFromInference(inference); } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -30297,21 +31350,33 @@ var ts; } return undefined; } + function typesDefinitelyUnrelated(source, target) { + return isTupleType(source) && isTupleType(target) && getTypeReferenceArity(source) !== getTypeReferenceArity(target) || + !!getUnmatchedProperty(source, target, false) && !!getUnmatchedProperty(target, source, false); + } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : - undefined; + emptyObjectType; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; var contravariant = false; + var propagationType; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; } + if (source === wildcardType) { + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { var sourceTypes = source.aliasTypeArguments; var targetTypes = target.aliasTypeArguments; @@ -30361,14 +31426,15 @@ var ts; inference.priority = priority; } if (priority === inference.priority) { + var candidate = propagationType || source; if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, source); + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, source); + inference.candidates = ts.append(inference.candidates, candidate); } } - if (!(priority & 4) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -30397,7 +31463,10 @@ var ts; else if ((isLiteralType(source) || source.flags & 2) && target.flags & 524288) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; + var savePriority = priority; + priority |= 16; inferFromTypes(empty, target.type); + priority = savePriority; contravariant = !contravariant; } else if (source.flags & 1048576 && target.flags & 1048576) { @@ -30407,8 +31476,8 @@ var ts; else if (source.flags & 2097152 && target.flags & 2097152) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(source.trueType, target.trueType); - inferFromTypes(source.falseType, target.falseType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else if (target.flags & 393216) { var targetTypes = target.types; @@ -30439,7 +31508,7 @@ var ts; } } else { - if (!(priority && 8 && source.flags & (262144 | 7897088))) { + if (!(priority & 32 && source.flags & (262144 | 7897088))) { source = getApparentType(source); } if (source.flags & (65536 | 262144)) { @@ -30466,7 +31535,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 16) { + if (strictFunctionTypes || priority & 64) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -30507,12 +31576,15 @@ var ts; return; } if (constraintType.flags & 32768) { + var savePriority = priority; + priority |= 4; inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); return; } } - if (!getUnmatchedProperty(source, target, false) || !getUnmatchedProperty(target, source, false)) { + if (!typesDefinitelyUnrelated(source, target)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0); inferFromSignatures(source, target, 1); @@ -30606,43 +31678,54 @@ var ts; } return candidates; } + function getContravariantInference(inference) { + return inference.priority & 28 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, context, signature) { + var candidates = widenObjectLiteralCandidates(inference.candidates); + var widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var unwidenedType = context.flags & 1 || inference.priority & 28 ? + getUnionType(baseCandidates, 2) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } 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(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = context.flags & 1 || inference.priority & 4 ? - getUnionType(baseCandidates, 2) : - getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unwidenedType); - if (inferredType.flags & 16384 && inference.contraCandidates) { - inferredType = getCommonSubtype(inference.contraCandidates); + var signature = context.signature; + if (signature) { + if (inference.candidates) { + inferredType = getCovariantInference(inference, context, signature); + if (inferredType.flags & 16384 && inference.contraCandidates) { + inferredType = getContravariantInference(inference); + } } - } - else if (inference.contraCandidates) { - inferredType = getCommonSubtype(inference.contraCandidates); - } - else if (context.flags & 2) { - inferredType = silentNeverType; - } - else { - var defaultType = getDefaultFromTypeParameter(inference.typeParameter); - if (defaultType) { - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + else if (inference.contraCandidates) { + inferredType = getContravariantInference(inference); + } + else if (context.flags & 2) { + inferredType = silentNeverType; } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + } } } + else { + inferredType = getTypeFromInference(inference); + } inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -30666,7 +31749,7 @@ var ts; 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), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 67216319 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -30676,7 +31759,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99) { return "0"; @@ -30885,8 +31968,8 @@ var ts; } if (flags & 65536) { return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; + strictNullChecks ? 1970144 : 4181984 : + strictNullChecks ? 1972176 : 4184016; } if (flags & (2048 | 4096)) { return 2457472; @@ -30898,7 +31981,7 @@ var ts; return strictNullChecks ? 1981320 : 4193160; } if (flags & 134217728) { - return strictNullChecks ? 6166480 : 8378320; + return strictNullChecks ? 1972176 : 4184016; } if (flags & 7897088) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); @@ -30906,7 +31989,7 @@ var ts; if (flags & 393216) { return getTypeFactsOfTypes(type.types); } - return 8388607; + return 4194303; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -30920,7 +32003,7 @@ var ts; } function getTypeOfDestructuredProperty(type, name) { var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || getIndexTypeOfType(type, 0) || unknownType; @@ -31096,6 +32179,9 @@ var ts; return f(type) ? type : neverType; } function mapType(type, mapper, noReductions) { + if (type.flags & 16384) { + return type; + } if (!(type.flags & 131072)) { return mapper(type); } @@ -31819,25 +32905,24 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } - function isApparentTypePosition(node) { + function isConstraintPosition(node) { var parent = node.parent; return parent.kind === 183 || parent.kind === 185 && parent.expression === node || parent.kind === 184 && parent.expression === node || - parent.kind === 207 || parent.kind === 180 && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 7372800 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288); } - function getApparentTypeForLocation(type, node) { - if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getApparentType); + function getConstraintForLocation(type, node) { + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); } return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, 67216319) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -31895,7 +32980,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3)) { @@ -32312,46 +33397,46 @@ var ts; } function getContextuallyTypedParameterType(parameter) { var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = func.parameters.indexOf(parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = func.parameters.indexOf(parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); + indexOfParameter -= 1; + } + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + if (funcHasRestParameters && + indexOfParameter === (func.parameters.length - 1) && + isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } - return undefined; } function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; @@ -32460,7 +33545,8 @@ var ts; return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; case 54: var type = getContextualType(binaryExpression); - return !type && node === right ? getTypeOfExpression(left, true) : type; + return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? + getTypeOfExpression(left, true) : type; case 53: case 26: return node === right ? getContextualType(binaryExpression) : undefined; @@ -32479,6 +33565,7 @@ var ts; case 2: case 3: case 4: + case 6: return false; default: ts.Debug.assertNever(kind); @@ -32530,7 +33617,7 @@ var ts; } function getContextualTypeForChildJsxExpression(node) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); - var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; } function getContextualTypeForJsxExpression(node) { @@ -32656,20 +33743,14 @@ var ts; return anyType; } var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } - function getJsxSignaturesParameterTypes(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, false); - } - function getJsxSignaturesParameterTypesJs(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, true); - } - function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + function getJsxSignaturesParameterTypes(valueType, isJs, context) { if (valueType.flags & 2) { return anyType; } else if (valueType.flags & 32) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = valueType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -32692,21 +33773,24 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0); + if (context.typeArguments) { + signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + } + return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0); } - function getJsxPropsTypeFromCallSignature(sig) { + function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignature(sig); - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { propsType = intersectTypes(intrinsicAttribs, propsType); } return propsType; } - function getJsxPropsTypeFromClassType(hostClassType, isJs) { + function getJsxPropsTypeFromClassType(hostClassType, isJs, context) { if (isTypeAny(hostClassType)) { return hostClassType; } - var propsName = getJsxElementPropertiesName(); + var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context)); if (propsName === undefined) { return anyType; } @@ -32723,14 +33807,14 @@ var ts; } else { var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); if (intrinsicClassAttribs !== unknownType) { var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); apparentAttributesType = intersectTypes(typeParams ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) : intrinsicClassAttribs, apparentAttributesType); } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); } @@ -32738,18 +33822,12 @@ var ts; } } } - function getJsxPropsTypeFromConstructSignatureJs(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, true); - } - function getJsxPropsTypeFromConstructSignature(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, false); - } - function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + function getJsxPropsTypeFromConstructSignature(sig, isJs, context) { var hostClassType = getReturnTypeOfSignature(sig); if (hostClassType) { - return getJsxPropsTypeFromClassType(hostClassType, isJs); + return getJsxPropsTypeFromClassType(hostClassType, isJs, context); } - return getJsxPropsTypeFromCallSignature(sig); + return getJsxPropsTypeFromCallSignature(sig, context); } function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0); @@ -32789,7 +33867,16 @@ var ts; } function getContextualSignature(node) { ts.Debug.assert(node.kind !== 153 || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); + var type; + if (ts.isInJavaScriptFile(node)) { + var jsdoc = ts.getJSDocType(node); + if (jsdoc) { + type = getTypeFromTypeNode(jsdoc); + } + } + if (!type) { + type = getContextualTypeForFunctionLikeDeclaration(node); + } if (!type) { return undefined; } @@ -32936,19 +34023,28 @@ var ts; function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createSymbolTable(); + var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; var propagatedFlags = 8388608; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 178 || contextualType.pattern.kind === 182); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node); + var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - var isInJSFile = ts.isInJavaScriptFile(node); + if (isInJSFile && node.properties.length === 0) { + var symbol = getSymbolOfNode(node); + if (symbol.exports) { + propertiesTable = symbol.exports; + symbol.exports.forEach(function (symbol) { return propertiesArray.push(getMergedSymbol(symbol)); }); + return createObjectLiteralType(); + } + } + propertiesTable = ts.createSymbolTable(); var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; @@ -32984,9 +34080,13 @@ var ts; } typeFlags |= type.flags; var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; - var prop = nameType && isTypeUsableAsLateBoundName(nameType) + var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType); + var prop = hasLateBoundName ? createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024) : createSymbol(4 | member.flags, literalName || member.escapedName); + if (hasLateBoundName) { + prop.nameType = nameType; + } if (inDestructuringPattern) { var isOptional = (memberDecl.kind === 268 && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 269 && memberDecl.objectAssignmentInitializer); @@ -33099,7 +34199,7 @@ var ts; } function checkJsxSelfClosingElement(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxElement(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); @@ -33109,14 +34209,16 @@ var ts; else { checkExpression(node.closingElement.tagName); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxFragment(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); - if (compilerOptions.jsx === 2 && compilerOptions.jsxFactory) { - error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + if (compilerOptions.jsx === 2 && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function isUnhyphenatedJsxName(name) { return !ts.stringContains(name, "-"); @@ -33144,7 +34246,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -33205,7 +34307,10 @@ var ts; if (hasSpreadAnyType) { return anyType; } - return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + if (typeToIntersect && spread !== emptyObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); result.flags |= 33554432; @@ -33231,20 +34336,19 @@ var ts; function checkJsxAttributes(node, checkMode) { return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67901928); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType; } function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); if (intrinsicElementsType !== unknownType) { if (!ts.isIdentifier(node.tagName)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); if (intrinsicProp) { links.jsxFlags |= 1; @@ -33281,23 +34385,66 @@ var ts; } } var instantiatedSignatures = []; + var candidateForTypeArgumentError; + var hasTypeArgumentError = !!node.typeArguments; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, false); + if (typeArgumentInstantiated) { + hasTypeArgumentError = false; + instantiatedSignatures.push(typeArgumentInstantiated); + } + else { + if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + candidateForTypeArgumentError = signature; + } + var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 4 : 0); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } } else { instantiatedSignatures.push(signature); } } + if (node.typeArguments && hasTypeArgumentError) { + if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true); + } + else if (node.typeArguments.length !== 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); + } + } return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); } - function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); + function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (!node.typeArguments) { + return; + } + if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + return; + } + var args = checkTypeArguments(signature, node.typeArguments, reportErrors); + if (!args) { + return; + } + return getSignatureInstantiation(signature, args, isJavascript); + } + function getJsxNamespaceAt(location) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920, undefined, namespaceName, false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920); + if (candidate) { + return candidate; + } + } + return getGlobalSymbol(JsxNames.JSX, 1920, undefined); + } + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928); var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); if (propertiesOfJsxElementAttribPropInterface) { @@ -33313,19 +34460,11 @@ var ts; } return undefined; } - function getJsxElementPropertiesName() { - if (!_hasComputedJsxElementPropertiesName) { - _hasComputedJsxElementPropertiesName = true; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } - function getJsxElementChildrenPropertyName() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - return _jsxElementChildrenPropertyName; + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } function getApparentTypeOfJsxPropsType(propsType) { if (!propsType) { @@ -33344,7 +34483,7 @@ var ts; function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 131072)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); if (callSignature !== unknownSignature) { @@ -33352,7 +34491,7 @@ var ts; var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { paramType = intersectTypes(intrinsicAttributes, paramType); } @@ -33366,7 +34505,7 @@ var ts; function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 131072)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { var candidatesOutArray = []; getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); @@ -33397,7 +34536,7 @@ var ts; if (!result) { result = allMatchingAttributesType; } - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { result = intersectTypes(intrinsicAttributes, result); } @@ -33417,7 +34556,7 @@ var ts; return anyType; } else if (elementType.flags & 32) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -33442,7 +34581,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); @@ -33462,7 +34601,7 @@ var ts; return links.resolvedJsxElementAttributesType; } function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -33485,36 +34624,30 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.escapedText); return prop || unknownSymbol; } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === unknownType) + return undefined; + return type; } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); } - return deferredJsxStatelessElementType; } - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; } function checkJsxPreconditions(errorNode) { if ((compilerOptions.jsx || 0) === 0) { error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); } - if (getJsxGlobalElementType() === undefined) { + if (getJsxElementTypeAt(errorNode) === undefined) { if (noImplicitAny) { error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); } @@ -33527,9 +34660,9 @@ var ts; } checkJsxPreconditions(node); var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = getJsxNamespace(); + var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 107455, reactRefErr, reactNamespace, true); + var reactSym = resolveName(reactLocation, reactNamespace, 67216319, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = 67108863; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -33569,7 +34702,7 @@ var ts; getCustomJsxElementAttributesType(openingLikeElement, false); var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement)))); } else { var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); @@ -33608,7 +34741,9 @@ var ts; return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); + return !!(symbol.flags & 8192 || + ts.getCheckFlags(symbol) & 4 || + ts.isInJavaScriptFile(symbol.valueDeclaration) && ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(symbol.valueDeclaration))); } function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); @@ -33739,7 +34874,7 @@ var ts; return unknownType; } } - propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } if (node.kind !== 183 || assignmentKind === 1 || @@ -33837,7 +34972,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455); + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 67216319); return suggestion && ts.symbolName(suggestion); } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { @@ -33849,6 +34984,10 @@ var ts; }); return result && ts.symbolName(result); } + function getSuggestionForNonexistentModule(name, targetModule) { + var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475); + return suggestion && ts.symbolName(suggestion); + } function getSpellingSuggestionForName(name, symbols, meaning) { var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; @@ -33858,7 +34997,8 @@ var ts; for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; var candidateName = ts.symbolName(candidate); - if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + if (candidateName.charCodeAt(0) === 34 + || !(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { continue; } var candidateNameLowerCase = candidateName.toLowerCase(); @@ -33946,15 +35086,23 @@ var ts; return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) && (!(property.flags & 8192) || isValidMethodAccess(property, type)); } - function isValidMethodAccess(method, type) { + function isValidMethodAccess(method, actualThisType) { var propType = getTypeOfFuncClassEnumModule(method); var signatures = getSignaturesOfType(getNonNullableType(propType), 0); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { - var thisType = getThisTypeOfSignature(sig); - return !thisType || isTypeAssignableTo(type, thisType); + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); }); } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type === unknownType || isTypeAny(type)) { return true; @@ -34161,11 +35309,7 @@ var ts; typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } - var numTypeParameters = ts.length(signature.typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { + if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { return false; } if (spreadArgIndex >= 0) { @@ -34178,6 +35322,12 @@ var ts; var hasEnoughArguments = argCount >= signature.minArgumentCount; return callIsIncomplete || hasEnoughArguments; } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } function getSingleCallSignature(type) { if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); @@ -34189,12 +35339,12 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature, 1, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 1, compareTypes); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { 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)); } @@ -34223,7 +35373,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); @@ -34501,6 +35651,17 @@ var ts; return arg; } } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 187; var isDecorator = node.kind === 149; @@ -34556,21 +35717,13 @@ var ts; 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; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); - } - var paramCount = min < max ? min + "-" + max : min; - diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { - var sig = signatures_6[_a]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -34634,7 +35787,7 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + createInferenceContext(originalCandidate.typeParameters, originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : undefined; while (true) { candidate = originalCandidate; @@ -34959,19 +36112,49 @@ var ts; return false; } function getJavaScriptClassType(symbol) { - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + var initializer = ts.getDeclaredJavascriptInitializer(symbol.valueDeclaration); + if (initializer) { + symbol = getSymbolOfNode(initializer); } + var inferred; if (isJavaScriptConstructor(symbol.valueDeclaration)) { - return getInferredClassType(symbol); + inferred = getInferredClassType(symbol); } - if (symbol.flags & 3) { - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { - return getInferredClassType(valueType.symbol); + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + if (assignmentSymbol) { + var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); + if (prototype) { + return checkExpression(prototype); } } } + function getAssignedJavascriptPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 183) { + parent = parent.parent; + } + return parent && ts.isBinaryExpression(parent) && + ts.isPrototypeAccess(parent.left) && + parent.operatorToken.kind === 58 && + ts.isObjectLiteralExpression(parent.right) && + parent.right; + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -35035,7 +36218,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 107455, undefined, undefined, false); + return globalESSymbol === resolveName(left, "Symbol", 67216319, undefined, undefined, false); } function checkImportCallExpression(node) { if (!checkGrammarArguments(node.arguments)) @@ -35089,8 +36272,8 @@ var ts; return false; } if (!ts.isIdentifier(node.expression)) - throw ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined, true); + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319, undefined, undefined, true); if (!resolvedRequire) { return true; } @@ -35331,24 +36514,20 @@ var ts; } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); + var isAsync = (ts.getFunctionFlags(func) & 2) !== 0; ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); - } - if (functionFlags & 2) { - 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); - } - ts.pushIfUnique(aggregatedTypes, type); - } + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); }); return aggregatedTypes; } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpressionCached(node.expression, checkMode) : undefinedWideningType; + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.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); + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; @@ -35396,7 +36575,8 @@ var ts; if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -35448,7 +36628,6 @@ var ts; function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 153 || ts.isObjectLiteralMethod(node)); if (checkMode === 1 && isContextSensitive(node)) { - checkNodeDeferred(node); return anyFunctionType; } var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); @@ -35924,6 +37103,9 @@ var ts; return (target.flags & 12288) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + return checkExpression(node.right, checkMode); + } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { @@ -36115,42 +37297,28 @@ var ts; error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); } } - if (node.expression) { - var func = ts.getContainingFunction(node); - var functionFlags = func && ts.getFunctionFlags(func); - if (node.asteriskToken) { - if ((functionFlags & 3) === 3 && - languageVersion < 6) { - checkExternalEmitHelpers(node, 26624); - } - if ((functionFlags & 3) === 1 && - languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256); - } + var func = ts.getContainingFunction(node); + var functionFlags = func ? ts.getFunctionFlags(func) : 0; + if (!(functionFlags & 1)) { + return anyType; + } + if (node.asteriskToken) { + if ((functionFlags & 3) === 3 && + languageVersion < 6) { + checkExternalEmitHelpers(node, 26624); } - if (functionFlags & 1) { - var expressionType = checkExpressionCached(node.expression); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); - } - var returnType = ts.getEffectiveReturnTypeNode(func); - if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2) !== 0) || anyType; - if (nodeIsYieldStar) { - checkTypeAssignableTo(functionFlags & 2 - ? 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); - } - else { - checkTypeAssignableTo(functionFlags & 2 - ? 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); - } - } + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256); } } + var isAsync = (functionFlags & 2) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + var returnType = ts.getEffectiveReturnTypeNode(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; + checkTypeAssignableTo(yieldedType, signatureElementType, node.expression || node, undefined); + } return anyType; } function checkConditionalExpression(node, checkMode) { @@ -36202,10 +37370,27 @@ var ts; return node.kind === 188 || node.kind === 206; } function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, true); - return ts.getCombinedNodeFlags(declaration) & 2 || + var inJs = ts.isInJavaScriptFile(declaration); + var initializer = inJs && ts.getDeclaredJavascriptInitializer(declaration) || declaration.initializer; + var type = getTypeOfExpression(initializer, true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 || (ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (inJs) { + if (widened.flags & 12288) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyType); + } + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyArrayType); + } + return anyArrayType; + } + } + return widened; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { @@ -37374,7 +38559,7 @@ 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, 67216319, true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; if (promiseConstructorType === unknownType) { if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { @@ -37394,7 +38579,7 @@ var ts; return unknownType; } var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; @@ -37442,7 +38627,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 ? 793064 : 1920) | 2097152; + var meaning = (typeName.kind === 71 ? 67901928 : 1920) | 2097152; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 @@ -37571,7 +38756,17 @@ var ts; 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 === 145 ? node.name.right : node.name)); + var decl = ts.getHostSignatureFromJSDoc(node); + if (decl) { + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 145 ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 145 ? node.name.right : node.name)); + } + } } } function checkJSDocAugmentsTag(node) { @@ -37580,7 +38775,7 @@ var ts; error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } - var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 285); + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); 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); @@ -37736,14 +38931,14 @@ var ts; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); + diagnostics.add(ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 && ts.idText(node).charCodeAt(0) === 95; + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { @@ -37798,18 +38993,59 @@ var ts; } function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { + var unusedImports_1 = ts.createMap(); 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.symbolName(local)); + if (local.isReferenced || local.exportSymbol) + return; + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + var importClause = importClauseFromImported(declaration); + var key = String(getNodeId(importClause)); + var group_1 = unusedImports_1.get(key); + if (group_1) { + group_1[1].push(declaration); } + else { + unusedImports_1.set(key, [importClause, [declaration]]); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local)); } } }); + unusedImports_1.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name)); + } + } + else if (unuseds.length === 1) { + error(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)); + } + else { + error(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)); + } + }); } } + function isImportedDeclaration(node) { + return node.kind === 243 || node.kind === 246 || node.kind === 244; + } + function importClauseFromImported(decl) { + return decl.kind === 243 ? decl : decl.kind === 244 ? decl.parent : decl.parent.parent; + } + function forEachImportedDeclaration(importClause, cb) { + var defaultName = importClause.name, namedBindings = importClause.namedBindings; + return (defaultName && cb(importClause)) || + namedBindings && (namedBindings.kind === 244 ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); + } function checkBlock(node) { if (node.kind === 211) { checkGrammarStatementInAmbientContext(node); @@ -37827,7 +39063,7 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasRestParameter(node) || node.flags & 2097152 || ts.nodeIsMissing(node.body)) { + if (languageVersion >= 2 || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 2097152 || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -37858,12 +39094,12 @@ var ts; return true; } function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { + if (languageVersion <= 1 && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_this")) { potentialThisCollisions.push(node); } } function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + if (languageVersion <= 1 && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_newTarget")) { potentialNewTargetCollisions.push(node); } } @@ -37896,6 +39132,9 @@ var ts; }); } function checkCollisionWithCapturedSuperVariable(node, name) { + if (languageVersion >= 2 || compilerOptions.noEmit) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } @@ -37914,7 +39153,7 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { - if (modulekind >= ts.ModuleKind.ES2015) { + if (modulekind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { return; } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { @@ -37929,7 +39168,7 @@ var ts; } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1) { @@ -37950,7 +39189,7 @@ var ts; var symbol = getSymbolOfNode(node); if (symbol.flags & 1) { if (!ts.isIdentifier(node.name)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && @@ -37987,7 +39226,7 @@ var ts; return visit(n.expression); } else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined, false); + var symbol = resolveName(n, n.escapedText, 67216319 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -38084,7 +39323,8 @@ var ts; var type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 219) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); + var initializer = ts.isInJavaScriptFile(node) && ts.getDeclaredJavascriptInitializer(node) || node.initializer; + checkTypeAssignableTo(checkExpressionCached(initializer), type, node, undefined); checkParameterInitializer(node); } } @@ -38564,8 +39804,7 @@ var ts; return "quit"; } if (current.kind === 226 && 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)); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } }); @@ -38883,7 +40122,7 @@ var ts; var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && baseProp) { - var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) { issuedMemberError = true; } @@ -39435,7 +40674,10 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { + if (ts.nodeIsMissing(moduleName)) { + return false; + } + if (!ts.isStringLiteral(moduleName)) { error(moduleName, ts.Diagnostics.String_literal_expected); return false; } @@ -39446,7 +40688,7 @@ var ts; ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { if (!isTopLevelInExternalModuleAugmentation(node)) { error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); return false; @@ -39458,8 +40700,8 @@ 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) | + var excludedMeanings = (symbol.flags & (67216319 | 1048576) ? 67216319 : 0) | + (symbol.flags & 67901928 ? 67901928 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 250 ? @@ -39469,7 +40711,7 @@ var ts; } if (compilerOptions.isolatedModules && node.kind === 250 - && !(target.flags & 107455) + && !(target.flags & 67216319) && !(node.flags & 2097152)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -39518,13 +40760,13 @@ var ts; if (node.moduleReference.kind !== 252) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 107455) { + if (target.flags & 67216319) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 67216319 | 1920).flags & 1920)) { 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 & 67901928) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -39578,7 +40820,7 @@ var ts; } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined, true); + var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 | 67901928 | 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.idText(exportedName)); } @@ -39841,6 +41083,12 @@ var ts; checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } @@ -39863,15 +41111,19 @@ var ts; 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)) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { return createArrayType(type); } } } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } return addOptionality(type); } function checkNodeDeferred(node) { @@ -39926,6 +41178,7 @@ var ts; checkUnusedIdentifiers(); } deferredNodes = undefined; + seenDeferredUnusedIdentifiers.clear(); deferredUnusedIdentifierNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); @@ -40007,7 +41260,7 @@ var ts; case 233: case 234: if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928); } break; case 190: @@ -40135,7 +41388,7 @@ var ts; } } if (entityName.parent.kind === 247 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 2097152); + return resolveEntityName(entityName, 67216319 | 67901928 | 1920 | 2097152); } if (entityName.kind !== 183 && isInRightSideOfImportOrExportAssignment(entityName)) { var importEqualsDeclaration = ts.getAncestor(entityName, 241); @@ -40148,9 +41401,9 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 205) { - meaning = 793064; + meaning = 67901928; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455; + meaning |= 67216319; } } else { @@ -40179,7 +41432,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 107455, false, true); + return resolveEntityName(entityName, 67216319, false, true); } else if (entityName.kind === 183 || entityName.kind === 145) { var links = getNodeLinks(entityName); @@ -40196,7 +41449,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 161 ? 793064 : 1920; + var meaning = entityName.parent.kind === 161 ? 67901928 : 1920; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 260) { @@ -40284,14 +41537,14 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 269) { - return resolveEntityName(location.name, 107455 | 2097152); + return resolveEntityName(location.name, 67216319 | 2097152); } return undefined; } 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, 67216319 | 67901928 | 1920 | 2097152); } function getTypeOfNode(node) { if (node.flags & 4194304) { @@ -40437,13 +41690,13 @@ var ts; var symbolLinks = getSymbolLinks(moduleSymbol); if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 107455) + ? !!(moduleSymbol.flags & 67216319) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 107455); + return s && !!(s.flags & 67216319); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -40479,7 +41732,7 @@ var ts; node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); - if (isNonLocalAlias(symbol, 107455)) { + if (isNonLocalAlias(symbol, 67216319)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -40492,7 +41745,7 @@ var ts; 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, 67216319, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } else if (nodeLinks_1.flags & 131072) { @@ -40564,7 +41817,7 @@ var ts; if (target === unknownSymbol) { return true; } - return target.flags & 107455 && + return target.flags & 67216319 && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -40577,7 +41830,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 && target.flags & 107455) { + if (target && ts.getModifierFlags(node) & 1 && target.flags & 67216319) { return true; } } @@ -40588,6 +41841,8 @@ var ts; } function isImplementationOfOverload(node) { if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); return signaturesOfSymbol.length > 1 || @@ -40647,8 +41902,8 @@ var ts; if (!location) return ts.TypeReferenceSerializationKind.Unknown; } - var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); - var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); + var valueSymbol = resolveEntityName(typeName, 67216319, true, false, location); + var typeSymbol = resolveEntityName(typeName, 67901928, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -40697,7 +41952,11 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { + declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(119); + } var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 | 131072)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) @@ -40706,18 +41965,26 @@ var ts; type.symbol === symbol) { flags |= 1048576; } - if (flags & 131072) { + if (addUndefined) { type = getOptionalType(type); } - typeToString(type, enclosingDeclaration, flags | 1024, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { + signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(119); + } var signature = getSignatureFromDeclaration(signatureDeclaration); - typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, writer); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, tracker); } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { + expr = ts.getParseTreeNode(expr, ts.isExpression); + if (!expr) { + return ts.createToken(119); + } var type = getWidenedType(getRegularTypeOfExpression(expr)); - typeToString(type, enclosingDeclaration, flags | 1024, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -40734,7 +42001,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined, true); + return resolveName(location, reference.escapedText, 67216319 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -40755,9 +42022,12 @@ var ts; } return false; } - function writeLiteralConstValue(node, writer) { + function literalTypeToNode(type) { + return ts.createLiteral(type.value); + } + function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); + return literalTypeToNode(type); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -40795,9 +42065,10 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -40819,16 +42090,15 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024); }, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } }; function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { return undefined; } var meaning = (node.kind === 183) || (node.kind === 71 && isInTypeQuery(node)) - ? 107455 | 1048576 - : 793064 | 1920; + ? 67216319 | 1048576 + : 67901928 | 1920; var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -40883,7 +42153,7 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 237 ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); if (!moduleSymbol) { return undefined; @@ -40968,7 +42238,7 @@ var ts; for (var helper = 1; helper <= 65536; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319); 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); } @@ -41582,6 +42852,7 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; @@ -41944,8 +43215,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } } @@ -42073,8 +43344,8 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { 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)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), 0, message, arg0, arg1, arg2)); return true; } } @@ -42157,14 +43428,14 @@ var ts; } ts.updateNode = updateNode; function createNodeArray(elements, hasTrailingComma) { - if (elements) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else { if (ts.isNodeArray(elements)) { return elements; } } - else { - elements = []; - } var array = elements; array.pos = -1; array.end = -1; @@ -42188,7 +43459,7 @@ var ts; return clone; } ts.getSynthesizedClone = getSynthesizedClone; - function createLiteral(value) { + function createLiteral(value, isSingleQuote) { if (typeof value === "number") { return createNumericLiteral(value + ""); } @@ -42196,7 +43467,10 @@ var ts; return value ? createTrue() : createFalse(); } if (ts.isString(value)) { - return createStringLiteral(value); + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; } return createLiteralFromNode(value); } @@ -42267,6 +43541,14 @@ var ts; return name; } ts.createUniqueName = createUniqueName; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 5; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateFlags = 4; @@ -42303,6 +43585,48 @@ var ts; return createSynthesizedNode(86); } ts.createFalse = createFalse; + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1) { + result.push(createModifier(84)); + } + if (flags & 2) { + result.push(createModifier(124)); + } + if (flags & 512) { + result.push(createModifier(79)); + } + if (flags & 2048) { + result.push(createModifier(76)); + } + if (flags & 4) { + result.push(createModifier(114)); + } + if (flags & 8) { + result.push(createModifier(112)); + } + if (flags & 16) { + result.push(createModifier(113)); + } + if (flags & 128) { + result.push(createModifier(117)); + } + if (flags & 32) { + result.push(createModifier(115)); + } + if (flags & 64) { + result.push(createModifier(132)); + } + if (flags & 256) { + result.push(createModifier(120)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; function createQualifiedName(left, right) { var node = createSynthesizedNode(145); node.left = left; @@ -42317,9 +43641,15 @@ var ts; : node; } ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26) || + expression.kind === 296 ? + createParen(expression) : + expression; + } function createComputedPropertyName(expression) { var node = createSynthesizedNode(146); - node.expression = expression; + node.expression = parenthesizeForComputedName(expression); return node; } ts.createComputedPropertyName = createComputedPropertyName; @@ -43938,31 +45268,35 @@ var ts; : node; } ts.updateJsxElement = updateJsxElement; - function createJsxSelfClosingElement(tagName, attributes) { + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(254); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxSelfClosingElement = createJsxSelfClosingElement; - function updateJsxSelfClosingElement(node, tagName, attributes) { + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxSelfClosingElement(tagName, attributes), node) + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; - function createJsxOpeningElement(tagName, attributes) { + function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(255); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxOpeningElement = createJsxOpeningElement; - function updateJsxOpeningElement(node, tagName, attributes) { + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxOpeningElement(tagName, attributes), node) + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxOpeningElement = updateJsxOpeningElement; @@ -44102,7 +45436,7 @@ var ts; var node = createSynthesizedNode(268); node.name = asName(name); node.questionToken = undefined; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); return node; } ts.createPropertyAssignment = createPropertyAssignment; @@ -44153,8 +45487,11 @@ var ts; : node; } ts.updateEnumMember = updateEnumMember; - function updateSourceFileNode(node, statements) { - if (node.statements !== statements) { + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences)) { var updated = createSynthesizedNode(272); updated.flags |= node.flags; updated.statements = createNodeArray(statements); @@ -44162,18 +45499,15 @@ var ts; updated.fileName = node.fileName; updated.path = node.path; updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; - if (node.referencedFiles !== undefined) - updated.referencedFiles = node.referencedFiles; - if (node.typeReferenceDirectives !== undefined) - updated.typeReferenceDirectives = node.typeReferenceDirectives; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; - if (node.isDeclarationFile !== undefined) - updated.isDeclarationFile = node.isDeclarationFile; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; if (node.hasNoDefaultLib !== undefined) @@ -44210,6 +45544,12 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; return updateNode(updated, node); } return node; @@ -44631,7 +45971,8 @@ var ts; requestEmitHelper: ts.noop, resumeLexicalEnvironment: ts.noop, startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, }; function createTypeCheck(value, tag) { return tag === "undefined" @@ -44752,7 +46093,7 @@ var ts; var valuesHelper = { name: "typescript:values", scoped: false, - text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };\n " + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" }; function createValuesHelper(context, expression, location) { context.requestEmitHelper(valuesHelper); @@ -44762,7 +46103,7 @@ var ts; var readHelper = { name: "typescript:read", scoped: false, - text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };\n " + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" }; function createReadHelper(context, iteratorRecord, count, location) { context.requestEmitHelper(readHelper); @@ -44817,7 +46158,7 @@ var ts; } ts.restoreEnclosingLabel = restoreEnclosingLabel; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { - var target = skipParentheses(node); + var target = ts.skipParentheses(node); switch (target.kind) { case 71: return cacheIdentifiers; @@ -45408,7 +46749,7 @@ var ts; do { previousNode = node; if (kinds & 1) { - node = skipParentheses(node); + node = ts.skipParentheses(node); } if (kinds & 2) { node = skipAssertions(node); @@ -45420,13 +46761,6 @@ var ts; return node; } ts.skipOuterExpressions = skipOuterExpressions; - function skipParentheses(node) { - while (node.kind === 189) { - node = node.expression; - } - return node; - } - ts.skipParentheses = skipParentheses; function skipAssertions(node) { while (ts.isAssertionExpression(node) || node.kind === 207) { node = node.expression; @@ -46030,9 +47364,9 @@ var ts; case 253: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 254: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 255: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 256: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 257: @@ -46536,9 +47870,10 @@ var ts; var Debug; (function (Debug) { var isDebugInfoEnabled = false; - Debug.failBadSyntaxKind = Debug.shouldAssert(1) - ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } - : ts.noop; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; Debug.assertEachNode = Debug.shouldAssert(1) ? 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; @@ -46638,7 +47973,7 @@ var ts; var uniqueExports = ts.createMap(); var exportedNames; var hasExportDefault = false; - var exportEquals = undefined; + var exportEquals; var hasExportStarsToExportValues = false; var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -47304,8 +48639,7 @@ var ts; case 210: return node; default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { @@ -47413,8 +48747,7 @@ var ts; case 241: return visitImportEqualsDeclaration(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitSourceFile(node) { @@ -47653,7 +48986,7 @@ var ts; ts.setEmitFlags(propertyName, 1536 | 48); var localName = ts.getMutableClone(name); ts.setEmitFlags(localName, 1536); - return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1))); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536)); } function getInitializedProperties(node, isStatic) { return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); @@ -48022,10 +49355,8 @@ var ts; case 86: return ts.createIdentifier("Boolean"); default: - ts.Debug.failBadSyntaxKind(node.literal); - break; + return ts.Debug.failBadSyntaxKind(node.literal); } - break; case 134: return ts.createIdentifier("Number"); case 138: @@ -48046,8 +49377,7 @@ var ts; case 173: break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } @@ -49240,12 +50570,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: "\n const _super = name => super[name];\n " + text: "\n const _super = name => super[name];" }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - 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 " + 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);" }; })(ts || (ts = {})); var ts; @@ -49737,7 +51067,7 @@ var ts; var awaitHelper = { name: "typescript:await", scoped: false, - text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" }; function createAwaitHelper(context, expression) { context.requestEmitHelper(awaitHelper); @@ -49746,7 +51076,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -49761,7 +51091,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -49771,7 +51101,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -49828,8 +51158,7 @@ var ts; case 257: return visitJsxFragment(node, true); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxElement(node, isChild) { @@ -49860,14 +51189,14 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } return element; } function visitJsxOpeningFragment(node, children, isChild, location) { - var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -49897,7 +51226,7 @@ var ts; return visitJsxExpression(node); } else { - ts.Debug.failBadSyntaxKind(node); + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxText(node) { @@ -50906,11 +52235,11 @@ var ts; 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)); + ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536)) + ]), parameter), 1 | 32 | 384 | 1536)); ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 | 32 | 1048576); + ts.setEmitFlags(statement, 384 | 32 | 1048576 | 1536); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -50974,8 +52303,7 @@ var ts; 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: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } var captureNewTargetStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration("_newTarget", undefined, newTarget) @@ -51415,23 +52743,22 @@ var ts; statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); } } - var bodyLocation; - var statementsLocation; if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); } else { var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); } else { statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); } } - return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), true), 48 | 384); } function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); @@ -51862,18 +53189,15 @@ var ts; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286, 65); var updated; - if (node.transformFlags & 32768) { - var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = transformFunctionBody(node); - if (node.kind === 155) { - updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); - } - else { - updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); - } + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (32768 | 128) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 155) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { - updated = ts.visitEachChild(node, visitor, context); + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 49152, 0); convertedLoopState = savedConvertedLoopState; @@ -52098,10 +53422,10 @@ var ts; } 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)); - if (span_6.literal.text.length !== 0) { - expressions.push(ts.createLiteral(span_6.literal.text)); + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); } } } @@ -52477,8 +53801,7 @@ var ts; case 190: return visitFunctionExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitFunctionDeclaration(node) { @@ -54820,7 +56143,7 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" }; function createExportStarHelper(context, module) { var compilerOptions = context.getCompilerOptions(); @@ -54836,12 +56159,12 @@ var ts; var importStarHelper = { name: "typescript:commonjsimportstar", scoped: false, - text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" }; var importDefaultHelper = { name: "typescript:commonjsimportdefault", scoped: false, - text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" }; })(ts || (ts = {})); var ts; @@ -55030,11 +56353,11 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_1 = dependencyGroups_1[_i]; - var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var group_2 = dependencyGroups_1[_i]; + var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -55776,6 +57099,1323 @@ var ts; ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + 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 === 233) { + 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 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 === 233) { + 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; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 230 || node.kind === 180) { + 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 === 151 || node.kind === 150 || + (node.kind === 148 && ts.hasModifier(node.parent, 8))) { + 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 === 233 || node.kind === 148) { + 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 getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 156) { + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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_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; + } + } + else { + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + 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_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: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 158: + 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 157: + 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 159: + 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 153: + case 152: + if (ts.hasModifier(node, 32)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + 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 === 233) { + 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 : + 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 { + 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 232: + 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 : + 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; + break; + default: + ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 154: + 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 158: + case 163: + 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 157: + 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 159: + 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 153: + case 152: + if (ts.hasModifier(node.parent, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + 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 === 233) { + 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 : + 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 { + 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 232: + case 162: + 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 : + 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; + default: + ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + var diagnosticMessage; + switch (node.parent.kind) { + case 233: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 234: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 158: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 157: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 153: + case 152: + 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 === 233) { + 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 232: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 235: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + if (node.parent.parent.kind === 233) { + diagnosticMessage = node.parent.token === 108 ? + 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 { + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJavaScript(file)) { + return []; + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 | 2048 | 4096 | 8 | 524288; + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var enclosingDeclaration; + var necessaryTypeRefernces; + var possibleImports; + var importDeclarationMap; + var suppressNewDiagnosticContexts; + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + }; + var errorNameNode; + var currentSourceFile; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + var host = context.getEmitHost(); + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeRefernces.set(ref, true); + } + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0) { + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!possibleImports) { + possibleImports = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(possibleImports, ref); + } + } + } + } + else { + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(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) { + context.addDiagnostic(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 transformRoot(node) { + if (node.kind === 272 && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + return node; + } + if (node.kind === 273) { + isBundledEmit = true; + var refs_1 = ts.createMap(); + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + return; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + possibleImports = undefined; + suppressNewDiagnosticContexts = false; + importDeclarationMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + collectReferences(sourceFile, refs_1); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; + needsDeclare = false; + var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], true, [], []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, updated, true, [], []); + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs_1.forEach(referenceVisitor_1); + return bundle; + } + needsDeclare = true; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + possibleImports = undefined; + importDeclarationMap = ts.createMap(); + necessaryTypeRefernces = undefined; + var refs = collectReferences(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + refs.forEach(referenceVisitor); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + if (ts.isExternalModule(node) && !resultHasExternalModuleIndicator) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences()); + return updated; + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeRefernces ? ts.map(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; + var paths = ts.getOutputPathsFor(file, host, true); + declFileName = paths.declarationFilePath || paths.jsFilePath; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getNodeId(elem), elem); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 71) { + return name; + } + else { + if (name.kind === 179) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 204) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55)) : undefined, ensureType(p, p.type, true), ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8)) { + return; + } + if (shouldPrintWithInitializer(node)) { + return; + } + var shouldUseResolverType = node.kind === 148 && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119); + } + if (node.kind === 156) { + return ts.createKeywordTypeNode(119); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 230 || node.kind === 180) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 148 + || node.kind === 151 + || node.kind === 150) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(119); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 232: + case 237: + case 234: + case 233: + case 235: + case 236: + return !resolver.isDeclarationVisible(node); + case 230: + return !getBindingNameVisible(node); + case 241: + case 242: + case 248: + case 247: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + return ts.forEach(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8)) { + return undefined; + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237; + if (input.kind === 9 && isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 252) { + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + return ts.updateImportDeclaration(decl, undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + return visibleDefaultBinding && ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 244) { + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + } + function filterCandidateImports(statements) { + var unconsideredImports = []; + while (ts.length(possibleImports)) { + var i = possibleImports.shift(); + if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { + unconsideredImports.push(i); + continue; + } + if (i.kind === 241) { + var result_3 = transformImportEqualsDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result_3); + continue; + } + var result = transformImportDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result); + } + possibleImports = unconsideredImports; + return ts.mapDefined(statements, function (statement) { + if (ts.isImportDeclaration(statement) || ts.isImportEqualsDeclaration(statement)) { + var key = "" + ts.getNodeId(statement); + if (importDeclarationMap.has(key)) { + var result = importDeclarationMap.get(key); + importDeclarationMap.delete(key); + return result; + } + else { + return undefined; + } + } + else { + return statement; + } + }); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; + return cleanup(ts.createProperty(undefined, input.modifiers, input.name, undefined, undefined, undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 165 || input.kind === 176) && input.parent.kind !== 235); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 205: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 161: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 158: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 154: { + var isPrivate = ts.hasModifier(input, 8); + var ctor = ts.createSignatureDeclaration(154, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0), undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 153: { + var sig = ts.createSignatureDeclaration(152, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 155: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 156: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 151: + return cleanup(ts.updateProperty(input, undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 150: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 152: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 157: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 159: { + return cleanup(ts.updateIndexSignature(input, undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119))); + } + case 230: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 147: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, undefined, undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 170: { + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 162: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 163: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 153 && ts.hasModifier(node.parent, 8); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + return ts.updateExportDeclaration(input, undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 247: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + if (input.expression.kind === 71) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124)] : [], ts.createVariableDeclarationList([varDecl], 2)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + case 241: + case 242: { + possibleImports = possibleImports || []; + ts.pushIfUnique(possibleImports, input); + return input; + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var previousNeedsDeclare; + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var oldPossibleImports; + switch (input.kind) { + case 235: + return cleanup(ts.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 234: { + return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 232: { + return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + } + case 237: { + previousNeedsDeclare = needsDeclare; + needsDeclare = false; + oldPossibleImports = possibleImports; + possibleImports = undefined; + var inner = input.body; + if (inner && inner.kind === 238) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + return cleanup(ts.updateModuleDeclaration(input, undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + needsDeclare = false; + return cleanup(ts.updateModuleDeclaration(input, undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + } + } + case 233: { + var modifiers = ts.createNodeArray(ensureModifiers(input)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 71) { + return preserveJsDoc(ts.createProperty(undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty(undefined, ensureModifiers(param), elem.name, undefined, ensureType(elem, undefined), undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95) { + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124)] : [], ts.createVariableDeclarationList([varDecl], 2)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 85) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 212: { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return cleanup(ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes))); + } + case 236: { + return cleanup(ts.updateEnumDeclaration(input, undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(returnValue) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (input.kind === 237) { + needsDeclare = previousNeedsDeclare; + possibleImports = ts.concatenate(oldPossibleImports, possibleImports); + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (returnValue) { + if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1) && ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 204) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, undefined), undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function ensureModifiers(node) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node) { + var mask = 3071 ^ (4 | 256); + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0; + var parentIsFile = node.parent.kind === 272; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((isBundledEmit && parentIsFile ? 0 : 1) | 512 | 2); + additions = 0; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_6 = function (range) { + if (range.kind === 3) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_6(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 85 && t.expression.kind === 95); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 234) { + return true; + } + return false; + } + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 ^ 4; } + if (modifierAdditions === void 0) { modifierAdditions = 0; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 && flags & 2) { + flags ^= 2; + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 155 + ? accessor.type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 230: + case 151: + case 150: + case 148: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 232: + case 237: + case 241: + case 234: + case 233: + case 235: + case 236: + case 212: + case 242: + case 248: + case 247: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 158: + case 154: + case 153: + case 155: + case 156: + case 151: + case 150: + case 152: + case 157: + case 159: + case 230: + case 147: + case 205: + case 161: + case 170: + case 162: + case 163: + return true; + } + return false; + } +})(ts || (ts = {})); +var ts; (function (ts) { function getModuleTransformer(moduleKind) { switch (moduleKind) { @@ -55843,6 +58483,7 @@ var ts; var onSubstituteNode = function (_, node) { return node; }; var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; var state = 0; + var diagnostics = []; var context = { getCompilerOptions: function () { return options; }, getEmitResolver: function () { return resolver; }, @@ -55870,6 +58511,9 @@ var ts; ts.Debug.assert(state < 1, "Cannot modify transformation hooks after initialization has completed."); ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); } }; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -55887,7 +58531,8 @@ var ts; transformed: transformed, substituteNode: substituteNode, emitNodeWithNotification: emitNodeWithNotification, - dispose: dispose + dispose: dispose, + diagnostics: diagnostics }; function transformRoot(node) { return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; @@ -56027,1683 +58672,6 @@ var ts; ts.transformNodes = transformNodes; })(ts || (ts = {})); var ts; -(function (ts) { - function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var declarationDiagnostics = ts.createDiagnosticCollection(); - ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); - return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); - function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) { - var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, false); - } - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 273; - var newLine = host.getNewLine(); - var compilerOptions = host.getCompilerOptions(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer; - createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var resultHasExternalModuleIndicator; - var currentText; - var currentLineMap; - var currentIdentifiers; - var isCurrentFileExternalModule; - var reportedDeclarationError = false; - var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; - var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var needsDeclare = true; - var moduleElementDeclarationEmitInfo = []; - var asynchronousSubModuleDeclarationEmitInfo; - var referencesOutput = ""; - var usedTypeDirectiveReferences; - var emittedReferencedFiles = []; - var addedGlobalFileReference = false; - var allSourcesModuleElementDeclarationEmitInfo = []; - ts.forEach(sourceFiles, function (sourceFile) { - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { - addedGlobalFileReference = true; - } - emittedReferencedFiles.push(referencedFile); - } - }); - } - resultHasExternalModuleIndicator = false; - if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - needsDeclare = true; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - needsDeclare = false; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - } - if (moduleElementDeclarationEmitInfo.length) { - var oldWriter = writer; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 242); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - increaseIndent(); - } - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - decreaseIndent(); - } - } - }); - setWriter(oldWriter); - allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { - write("export {};"); - writeLine(); - } - }); - if (usedTypeDirectiveReferences) { - ts.forEachKey(usedTypeDirectiveReferences, function (directive) { - referencesOutput += "/// " + newLine; - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput, - }; - function hasInternalAnnotation(range) { - var comment = currentText.substring(range.pos, range.end); - return ts.stringContains(comment, "@internal"); - } - function stripInternal(node) { - if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); - if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { - return; - } - emitNode(node); - } - } - function createAndSetNewTextWriterWithSymbolWriter() { - 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; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeProperty = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsynchronousModuleElements(nodes) { - var oldWriter = writer; - ts.forEach(nodes, function (declaration) { - var nodeToCheck; - if (declaration.kind === 230) { - nodeToCheck = declaration.parent.parent; - } - else if (declaration.kind === 245 || declaration.kind === 246 || declaration.kind === 243) { - ts.Debug.fail("We should be getting ImportDeclaration instead to write"); - } - else { - nodeToCheck = declaration; - } - var moduleElementEmitInfo = ts.forEach(moduleElementDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) { - moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - } - if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 242) { - moduleElementEmitInfo.isVisible = true; - } - else { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - if (nodeToCheck.kind === 237) { - ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); - asynchronousSubModuleDeclarationEmitInfo = []; - } - writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 237) { - moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; - asynchronousSubModuleDeclarationEmitInfo = undefined; - } - moduleElementEmitInfo.asynchronousOutput = writer.getText(); - } - } - }); - setWriter(oldWriter); - } - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { - if (!typeReferenceDirectives) { - return; - } - if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); - } - for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { - var directive = typeReferenceDirectives_1[_i]; - if (!usedTypeDirectiveReferences.has(directive)) { - usedTypeDirectiveReferences.set(directive, directive); - } - } - } - function handleSymbolAccessibilityError(symbolAccessibilityResult) { - if (symbolAccessibilityResult.accessibility === 0) { - if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); - } - } - else { - reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); - if (errorInfo) { - if (errorInfo.typeName) { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - else { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); - } - function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - reportedDeclarationError = true; - 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_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); - } - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - var shouldUseResolverType = declaration.kind === 148 && - (resolver.isRequiredInitializedParameter(declaration) || - resolver.isOptionalUninitializedParameterProperty(declaration)); - if (type && !shouldUseResolverType) { - emitType(type); - } - else { - errorNameNode = declaration.name; - var format = 4096 | 8 | - 2048 | - (shouldUseResolverType ? 131072 : 0); - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); - errorNameNode = undefined; - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - emitType(signature.type); - } - else { - errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048, writer); - errorNameNode = undefined; - } - } - function emitLines(nodes) { - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var node = nodes_6[_i]; - emit(node); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; - if (!canEmitFn || canEmitFn(node)) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(node); - } - } - } - function emitCommaList(nodes, eachNodeEmitFn, canEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); - } - function writeJsDocComments(declaration) { - 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); - } - } - function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 119: - case 137: - case 134: - case 122: - case 135: - case 138: - case 105: - case 140: - case 95: - case 131: - case 173: - case 177: - return writeTextOfNode(currentText, type); - case 205: - return emitExpressionWithTypeArguments(type); - case 161: - return emitTypeReference(type); - case 164: - return emitTypeQuery(type); - case 166: - return emitArrayType(type); - case 167: - return emitTupleType(type); - case 168: - return emitUnionType(type); - case 169: - return emitIntersectionType(type); - case 170: - return emitConditionalType(type); - case 171: - return emitInferType(type); - case 172: - return emitParenType(type); - case 174: - return emitTypeOperator(type); - case 175: - return emitIndexedAccessType(type); - case 176: - return emitMappedType(type); - case 162: - case 163: - return emitSignatureDeclarationWithJsDocComments(type); - case 165: - return emitTypeLiteral(type); - case 71: - return emitEntityName(type); - case 145: - return emitEntityName(type); - case 160: - return emitTypePredicate(type); - } - function writeEntityName(entityName) { - if (entityName.kind === 71) { - writeTextOfNode(currentText, entityName); - } - else { - var left = entityName.kind === 145 ? entityName.left : entityName.expression; - var right = entityName.kind === 145 ? entityName.right : entityName.name; - writeEntityName(left); - write("."); - writeTextOfNode(currentText, right); - } - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 241 ? 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 === 183); - emitEntityName(node.expression); - if (node.typeArguments) { - write("<"); - emitCommaList(node.typeArguments, emitType); - write(">"); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypePredicate(type) { - writeTextOfNode(currentText, type.parameterName); - write(" is "); - emitType(type.type); - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitIntersectionType(type) { - emitSeparatedList(type.types, " & ", emitType); - } - function emitConditionalType(node) { - emitType(node.checkType); - write(" extends "); - emitType(node.extendsType); - write(" ? "); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node.trueType; - emitType(node.trueType); - enclosingDeclaration = prevEnclosingDeclaration; - write(" : "); - emitType(node.falseType); - } - function emitInferType(node) { - write("infer "); - writeTextOfNode(currentText, node.typeParameter.name); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeOperator(type) { - write(ts.tokenToString(type.operator)); - write(" "); - emitType(type.type); - } - function emitIndexedAccessType(node) { - emitType(node.objectType); - write("["); - emitType(node.indexType); - write("]"); - } - function emitMappedType(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write("{"); - writeLine(); - increaseIndent(); - if (node.readonlyToken) { - write(node.readonlyToken.kind === 37 ? "+readonly " : - node.readonlyToken.kind === 38 ? "-readonly " : - "readonly "); - } - write("["); - writeEntityName(node.typeParameter.name); - write(" in "); - emitType(node.typeParameter.constraint); - write("]"); - if (node.questionToken) { - write(node.questionToken.kind === 37 ? "+?" : - node.questionToken.kind === 38 ? "-?" : - "?"); - } - write(": "); - emitType(node.type); - write(";"); - writeLine(); - decreaseIndent(); - write("}"); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentText = node.text; - currentLineMap = ts.getLineStarts(node); - currentIdentifiers = node.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(node); - enclosingDeclaration = node; - ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); - emitLines(node.statements); - } - function getExportTempVariableName(baseName) { - if (!currentIdentifiers.has(baseName)) { - return baseName; - } - var count = 0; - while (true) { - count++; - var name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; - } - } - } - function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { - var tempVarName = getExportTempVariableName(baseName); - if (needsDeclare) { - write("declare "); - } - write("const "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048, writer); - write(";"); - writeLine(); - return tempVarName; - } - function emitExportAssignment(node) { - if (ts.isSourceFile(node.parent)) { - resultHasExternalModuleIndicator = true; - } - if (node.expression.kind === 71) { - write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentText, node.expression); - } - else { - var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }, needsDeclare); - write(node.isExportEquals ? "export = " : "export default "); - write(tempVarName); - } - write(";"); - writeLine(); - if (node.expression.kind === 71) { - var nodes = resolver.collectLinkedAliases(node.expression); - writeAsynchronousModuleElements(nodes); - } - } - function isModuleElementVisible(node) { - return resolver.isDeclarationVisible(node); - } - function emitModuleElement(node, isModuleElementVisible) { - if (isModuleElementVisible) { - writeModuleElement(node); - } - else if (node.kind === 241 || - (node.parent.kind === 272 && isCurrentFileExternalModule)) { - var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 272) { - asynchronousSubModuleDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - else { - if (node.kind === 242) { - var importDeclaration = node; - if (importDeclaration.importClause) { - isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || - isVisibleNamedBinding(importDeclaration.importClause.namedBindings); - } - } - moduleElementDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - } - } - function writeModuleElement(node) { - switch (node.kind) { - case 232: - return writeFunctionDeclaration(node); - case 212: - return writeVariableStatement(node); - case 234: - return writeInterfaceDeclaration(node); - case 233: - return writeClassDeclaration(node); - case 235: - return writeTypeAliasDeclaration(node); - case 236: - return writeEnumDeclaration(node); - case 237: - return writeModuleDeclaration(node); - case 241: - return writeImportEqualsDeclaration(node); - case 242: - return writeImportDeclaration(node); - default: - ts.Debug.fail("Unknown symbol kind"); - } - } - function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 272) { - var modifiers = ts.getModifierFlags(node); - if (modifiers & 1) { - resultHasExternalModuleIndicator = true; - write("export "); - } - if (modifiers & 512) { - write("default "); - } - else if (node.kind !== 234 && needsDeclare) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(flags) { - if (flags & 8) { - write("private "); - } - else if (flags & 16) { - write("protected "); - } - if (flags & 32) { - write("static "); - } - if (flags & 64) { - write("readonly "); - } - if (flags & 128) { - write("abstract "); - } - } - function writeImportEqualsDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1)) { - write("export "); - } - write("import "); - writeTextOfNode(currentText, node.name); - write(" = "); - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - emitExternalModuleSpecifier(node); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function isVisibleNamedBinding(namedBindings) { - if (namedBindings) { - if (namedBindings.kind === 244) { - return resolver.isDeclarationVisible(namedBindings); - } - else { - return namedBindings.elements.some(function (namedImport) { return resolver.isDeclarationVisible(namedImport); }); - } - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1)) { - write("export "); - } - write("import "); - if (node.importClause) { - var currentWriterPos = writer.getTextPos(); - if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentText, node.importClause.name); - } - if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { - if (currentWriterPos !== writer.getTextPos()) { - write(", "); - } - if (node.importClause.namedBindings.kind === 244) { - write("* as "); - writeTextOfNode(currentText, node.importClause.namedBindings.name); - } - else { - write("{ "); - emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); - write(" }"); - } - } - write(" from "); - } - emitExternalModuleSpecifier(node); - write(";"); - writer.writeLine(); - } - function emitExternalModuleSpecifier(parent) { - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237; - var moduleSpecifier = parent.kind === 241 ? ts.getExternalModuleImportEqualsDeclarationExpression(parent) : - parent.kind === 237 ? parent.name : parent.moduleSpecifier; - if (moduleSpecifier.kind === 9 && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); - if (moduleName) { - write('"'); - write(moduleName); - write('"'); - return; - } - } - writeTextOfNode(currentText, moduleSpecifier); - } - function emitImportOrExportSpecifier(node) { - if (node.propertyName) { - writeTextOfNode(currentText, node.propertyName); - write(" as "); - } - writeTextOfNode(currentText, node.name); - } - function emitExportSpecifier(node) { - emitImportOrExportSpecifier(node); - var nodes = resolver.collectLinkedAliases(node.propertyName || node.name); - writeAsynchronousModuleElements(nodes); - } - function emitExportDeclaration(node) { - resultHasExternalModuleIndicator = true; - emitJsDocComments(node); - write("export "); - if (node.exportClause) { - write("{ "); - emitCommaList(node.exportClause.elements, emitExportSpecifier); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitExternalModuleSpecifier(node); - } - write(";"); - writer.writeLine(); - } - function writeModuleDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isGlobalScopeAugmentation(node)) { - write("global "); - } - else { - if (node.flags & 16) { - write("namespace "); - } - else { - write("module "); - } - if (ts.isExternalModuleAugmentation(node)) { - emitExternalModuleSpecifier(node); - } - else { - writeTextOfNode(currentText, node.name); - } - } - while (node.body && node.body.kind !== 238) { - node = node.body; - write("."); - writeTextOfNode(currentText, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - if (node.body) { - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - else { - write(";"); - } - } - function writeTypeAliasDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function writeEnumDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentText, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentText, node.name); - var enumMemberValue = resolver.getConstantValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(ts.getTextOfConstantValue(enumMemberValue)); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 153 && ts.hasModifier(node.parent, 8); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - emitJsDocComments(node); - decreaseIndent(); - writeTextOfNode(currentText, node.name); - if (node.constraint && !isPrivateMethodTypeParameter(node)) { - write(" extends "); - if (node.parent.kind === 162 || - node.parent.kind === 163 || - (node.parent.parent && node.parent.parent.kind === 165)) { - ts.Debug.assert(node.parent.kind === 153 || - node.parent.kind === 152 || - node.parent.kind === 162 || - node.parent.kind === 163 || - node.parent.kind === 157 || - node.parent.kind === 158); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - if (node.default && !isPrivateMethodTypeParameter(node)) { - write(" = "); - if (node.parent.kind === 162 || - node.parent.kind === 163 || - (node.parent.parent && node.parent.parent.kind === 165)) { - ts.Debug.assert(node.parent.kind === 153 || - node.parent.kind === 152 || - node.parent.kind === 162 || - node.parent.kind === 163 || - node.parent.kind === 157 || - node.parent.kind === 158); - emitType(node.default); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError); - } - } - function getTypeParameterConstraintVisibilityError() { - var diagnosticMessage; - switch (node.parent.kind) { - case 233: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 234: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 158: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 157: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 153: - case 152: - 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 === 233) { - 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 232: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - case 235: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - } - else if (!isImplementsList && node.expression.kind === 95) { - write("null"); - } - function getHeritageClauseVisibilityError() { - var diagnosticMessage; - if (node.parent.parent.kind === 233) { - 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 { - diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: ts.getNameOfDeclaration(node.parent.parent) - }; - } - } - } - function writeClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (ts.hasModifier(param, 92)) { - emitPropertyDeclaration(param); - } - }); - } - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - var tempVarName; - if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { - tempVarName = baseTypeNode.expression.kind === 95 ? - "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 === 237; })); - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.hasModifier(node, 128)) { - write("abstract "); - } - write("class "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - if (baseTypeNode) { - if (!ts.isEntityNameExpression(baseTypeNode.expression)) { - write(" extends "); - write(tempVarName); - if (baseTypeNode.typeArguments) { - write("<"); - emitCommaList(baseTypeNode.typeArguments, emitType); - write(">"); - } - } - else { - emitHeritageClause([baseTypeNode], false); - } - } - emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(ts.getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function writeInterfaceDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); - if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, false); - } - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - emitJsDocComments(node); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - emitVariableDeclaration(node); - 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 !== 230 || isVariableDeclarationVisible(node)) { - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); - if ((node.kind === 151 || node.kind === 150 || - (node.kind === 148 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 151 || node.kind === 150) && node.parent.kind === 165) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (resolver.isLiteralConstDeclaration(node)) { - write(" = "); - resolver.writeLiteralConstValue(node, writer); - } - else if (!ts.hasModifier(node, 8)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 230) { - 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 === 151 || node.kind === 150 || - (node.kind === 148 && ts.hasModifier(node.parent, 8))) { - 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 === 233 || node.kind === 148) { - 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 getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function emitBindingPattern(bindingPattern) { - var elements = []; - for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.kind !== 204 && isVariableDeclarationVisible(element)) { - elements.push(element); - } - } - emitCommaList(elements, emitBindingElement); - } - function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - writeTextOfNode(currentText, bindingElement.name); - writeTypeOfDeclaration(bindingElement, undefined, getBindingElementTypeVisibilityError); - } - } - } - } - function emitTypeOfVariableDeclarationFromTypeLiteral(node) { - if (ts.hasType(node)) { - write(": "); - emitType(node.type); - } - } - function isVariableStatementVisible(node) { - 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); })) { - return; - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isLet(node.declarationList)) { - write("let "); - } - else if (ts.isConst(node.declarationList)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); - write(";"); - writeLine(); - } - function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - var accessorWithTypeAnnotation; - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64)); - writeNameOfDeclaration(node, getAccessorNameVisibilityError); - if (!ts.hasModifier(node, 8)) { - accessorWithTypeAnnotation = node; - var type = getTypeAnnotationFromAccessor(node); - if (!type) { - var anotherAccessor = node.kind === 155 ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 155 - ? 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 === 233) { - 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 === 156) { - if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - 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_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; - } - } - else { - if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? - 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_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: accessorWithTypeAnnotation.name - }; - } - } - function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - if (!resolver.isImplementationOfOverload(node)) { - emitJsDocComments(node); - if (node.kind === 232) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 153 || node.kind === 154) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - } - if (node.kind === 232) { - write("function "); - writeTextOfNode(currentText, node.name); - } - else if (node.kind === 154) { - write("constructor"); - } - else { - 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 === 233) { - 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); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var closeParenthesizedFunctionType = false; - if (node.kind === 159) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - write("["); - } - else { - if (node.kind === 154 && ts.hasModifier(node, 8)) { - write("();"); - writeLine(); - return; - } - if (node.kind === 158 || node.kind === 163) { - write("new "); - } - else if (node.kind === 162) { - var currentOutput = writer.getText(); - if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { - closeParenthesizedFunctionType = true; - write("("); - } - } - emitTypeParameters(node.typeParameters); - write("("); - } - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 159) { - write("]"); - } - else { - write(")"); - } - var isFunctionTypeOrConstructorType = node.kind === 162 || node.kind === 163; - if (isFunctionTypeOrConstructorType || node.parent.kind === 165) { - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 154 && !ts.hasModifier(node, 8)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - else if (closeParenthesizedFunctionType) { - write(")"); - } - function getReturnTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 158: - 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 157: - 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 159: - 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 153: - case 152: - if (ts.hasModifier(node, 32)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? - 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 === 233) { - 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 : - 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 { - 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 232: - 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 : - 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; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - writeTextOfNode(currentText, node.name); - } - if (resolver.isOptionalParameter(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 162 || - node.parent.kind === 163 || - node.parent.parent.kind === 165) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!ts.hasModifier(node.parent, 8)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - switch (node.parent.kind) { - case 154: - 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 158: - 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 157: - 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 159: - 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 153: - case 152: - if (ts.hasModifier(node.parent, 32)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? - 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 === 233) { - 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 : - 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 { - 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 232: - 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 : - 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; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - } - function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 178) { - write("{"); - emitCommaList(bindingPattern.elements, emitBindingElement); - write("}"); - } - else if (bindingPattern.kind === 179) { - write("["); - var elements = bindingPattern.elements; - emitCommaList(elements, emitBindingElement); - if (elements && elements.hasTrailingComma) { - write(", "); - } - write("]"); - } - } - function emitBindingElement(bindingElement) { - if (bindingElement.kind === 204) { - write(" "); - } - else if (bindingElement.kind === 180) { - if (bindingElement.propertyName) { - writeTextOfNode(currentText, bindingElement.propertyName); - write(": "); - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - ts.Debug.assert(bindingElement.name.kind === 71); - if (bindingElement.dotDotDotToken) { - write("..."); - } - writeTextOfNode(currentText, bindingElement.name); - } - } - } - } - } - function emitNode(node) { - switch (node.kind) { - case 232: - case 237: - case 241: - case 234: - case 233: - case 235: - case 236: - return emitModuleElement(node, isModuleElementVisible(node)); - case 212: - return emitModuleElement(node, isVariableStatementVisible(node)); - case 242: - return emitModuleElement(node, !node.importClause); - case 248: - return emitExportDeclaration(node); - case 154: - case 153: - case 152: - return writeFunctionDeclaration(node); - case 158: - case 157: - case 159: - return emitSignatureDeclarationWithJsDocComments(node); - case 155: - case 156: - return emitAccessorDeclaration(node); - case 151: - case 150: - return emitPropertyDeclaration(node); - case 271: - return emitEnumMemberDeclaration(node); - case 247: - return emitExportAssignment(node); - case 272: - return emitSourceFile(node); - } - } - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { - var declFileName; - var addedBundledEmitReference = false; - if (referencedFile.isDeclarationFile) { - declFileName = referencedFile.fileName; - } - else { - ts.forEachEmittedFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); - } - if (declFileName) { - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); - referencesOutput += "/// " + newLine; - } - return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFileOrBundle) { - var isBundledEmit = sourceFileOrBundle.kind === 273; - if (isBundledEmit && !addBundledFileReference) { - return; - } - ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); - declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; - addedBundledEmitReference = isBundledEmit; - } - } - } - 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 || emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var declarationOutput = emitDeclarationResult.referencesOutput - + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); - } - return emitSkipped; - function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { - var appliedSyncOutputPos = 0; - var declarationOutput = ""; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.asynchronousOutput) { - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); - declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); - return declarationOutput; - } - } - ts.writeDeclarationFile = writeDeclarationFile; -})(ts || (ts = {})); -var ts; (function (ts) { var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -57712,8 +58680,8 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); + function createSourceMapWriter(host, writer, compilerOptions) { + if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSource; var currentSourceText; @@ -57723,11 +58691,11 @@ var ts; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; + var sourceMapDataList; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, - getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitNodeWithSourceMap: emitNodeWithSourceMap, @@ -57738,13 +58706,14 @@ var ts; function skipSourceTrivia(pos) { return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); } - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) { + function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { if (disabled) { return; } if (sourceMapData) { reset(); } + sourceMapDataList = outputSourceMapDataList; currentSource = undefined; currentSourceText = undefined; sourceMapSourceIndex = -1; @@ -57788,6 +58757,9 @@ var ts; if (disabled) { return; } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMapData); + } currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -57795,6 +58767,7 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + sourceMapDataList = undefined; } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -57959,7 +58932,7 @@ var ts; return; } if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.convertToBase64(getText()); + var base64SourceMapText = ts.base64encode(ts.sys, getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; } else { @@ -58185,7 +59158,15 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -58212,6 +59193,8 @@ var ts; forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!writer.isAtStartOfLine()) { writer.write(" "); } @@ -58304,6 +59287,8 @@ var ts; } } function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (emitPos) emitPos(commentPos); ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); @@ -58324,10 +59309,8 @@ var ts; var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var bundle = ts.createBundle(sourceFiles); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; } @@ -58336,10 +59319,7 @@ var ts; else { for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { var sourceFile = sourceFiles_1[_a]; - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); if (result) { return result; } @@ -58347,8 +59327,27 @@ var ts; } } ts.forEachEmittedFile = forEachEmittedFile; + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 273) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + else { + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var isJs = ts.isSourceFileJavaScript(sourceFile); + var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; } function getOutputExtension(sourceFile, options) { if (options.jsx === 1) { @@ -58363,41 +59362,28 @@ var ts; } return ".js"; } - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 273) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); - } - return ts.getOriginalSourceFile(sourceFileOrBundle); - } function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { var compilerOptions = host.getCompilerOptions(); var moduleKind = ts.getEmitModuleKind(compilerOptions); - var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); var writer = ts.createTextWriter(newLine); var sourceMap = ts.createSourceMapWriter(host, writer); + var declarationSourceMap = ts.createSourceMapWriter(host, writer, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); var currentSourceFile; var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; - var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, false); - var printer = createPrinter(compilerOptions, { - hasGlobalName: resolver.hasGlobalName, - onEmitNode: transform.emitNodeWithNotification, - substituteNode: transform.substituteNode, - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - onEmitHelpers: emitHelpers, - onSetSourceFile: setSourceFile, - }); ts.performance.mark("beforePrint"); - forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); - transform.dispose(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -58405,18 +59391,9 @@ var ts; sourceMaps: sourceMapDataList }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { - if (!emitOnlyDtsFiles) { - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); - } - } - else { - emitSkipped = true; - } - if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; - } + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { emittedFilesList.push(jsFilePath); @@ -58429,11 +59406,64 @@ var ts; } } } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + emitSkipped = true; + return; + } + if (emitOnlyDtsFiles) { + return; + } + var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, false); + var printer = createPrinter(compilerOptions, { + hasGlobalName: resolver.hasGlobalName, + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: sourceMap.emitPos, + onEmitHelpers: emitHelpers, + onSetSourceFile: setSourceFile, + }); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true }), { + hasGlobalName: resolver.hasGlobalName, + onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: declarationSourceMap.emitPos, + onSetSourceFile: setSourceFileForDeclarationSourceMaps, + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + } + declarationTransform.dispose(); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 273 ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 272 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); + mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { bundledHelpers = ts.createMap(); isOwnFileEmit = false; @@ -58444,18 +59474,15 @@ var ts; printer.writeFile(sourceFile, writer); } writer.writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); + var sourceMappingURL = mapRecorder.getSourceMappingURL(); if (sourceMappingURL) { writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); } - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); - } - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); + if (sourceMapFilePath) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), false, sourceFiles); } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); - sourceMap.reset(); + mapRecorder.reset(); writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; @@ -58465,6 +59492,10 @@ var ts; currentSourceFile = node; sourceMap.setSourceFile(node); } + function setSourceFileForDeclarationSourceMaps(node) { + currentSourceFile = node; + declarationSourceMap.setSourceFile(node); + } function emitHelpers(node, writeLines) { var helpersEmitted = false; var bundle = node.kind === 273 ? node : undefined; @@ -58594,6 +59625,7 @@ var ts; emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpersIndirect(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { var sourceFile = _b[_a]; print(0, sourceFile, sourceFile); @@ -59097,7 +60129,7 @@ var ts; else { emitTypeAnnotation(node.type); } - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); } function emitDecorator(decorator) { writePunctuation("@"); @@ -59116,8 +60148,9 @@ var ts; emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); + emitIfPresent(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { @@ -59233,7 +60266,7 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; + var flags = ts.getEmitFlags(node) & 1 ? 384 : 16449; emitList(node, node.members, flags | 262144); writePunctuation("}"); } @@ -59248,7 +60281,7 @@ var ts; } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 336); + emitList(node, node.elementTypes, 272); writePunctuation("]"); } function emitUnionType(node) { @@ -59356,7 +60389,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } function emitArrayLiteralExpression(node) { var elements = node.elements; @@ -59390,7 +60423,10 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - writePunctuation(shouldEmitDotDot ? ".." : "."); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(23, node.expression.end, writePunctuation, node); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -59411,9 +60447,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - writePunctuation("["); + var openPos = emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - writePunctuation("]"); + emitTokenWithComment(22, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); @@ -59421,7 +60457,7 @@ var ts; emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { - writeKeyword("new"); + emitTokenWithComment(94, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); @@ -59439,9 +60475,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - writePunctuation("("); + var openParenPos = emitTokenWithComment(19, node.pos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -59459,22 +60495,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - writeKeyword("delete"); + emitTokenWithComment(80, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - writeKeyword("typeof"); + emitTokenWithComment(103, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - writeKeyword("void"); + emitTokenWithComment(105, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - writeKeyword("await"); + emitTokenWithComment(121, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -59530,7 +60566,7 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - writeKeyword("yield"); + emitTokenWithComment(116, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } @@ -59568,16 +60604,13 @@ var ts; emit(node.literal); } function emitBlock(node) { - writeToken(17, node.pos, writePunctuation, node); emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18, node.statements.end, writePunctuation, node); } function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(17, node.pos, writePunctuation, node); var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; emitList(node, node.statements, format); + emitTokenWithComment(18, node.statements.end, writePunctuation, node, !!(format & 1)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -59592,15 +60625,15 @@ var ts; writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(90, node.pos, writeKeyword, node); writeSpace(); - writeToken(19, openParenPos, writePunctuation, node); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20, node.expression.end, writePunctuation, node); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82, node.thenStatement.end, writeKeyword, node); + emitTokenWithComment(82, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 215) { writeSpace(); emit(node.elseStatement); @@ -59610,8 +60643,15 @@ var ts; } } } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(106, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(19, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); + } function emitDoStatement(node) { - writeKeyword("do"); + emitTokenWithComment(81, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -59619,55 +60659,48 @@ var ts; else { writeLineOrSpace(node); } - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(");"); + emitWhileClause(node, node.statement.end); + writePunctuation(";"); } function emitWhileStatement(node) { - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(")"); + emitWhileClause(node, node.pos); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); writeSpace(); - writeToken(19, openParenPos, writePunctuation, node); + var pos = emitTokenWithComment(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); - writeSemicolon(); + pos = emitTokenWithComment(25, node.initializer ? node.initializer.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.condition); - writeSemicolon(); + pos = emitTokenWithComment(25, node.condition ? node.condition.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.incrementor); - writePunctuation(")"); + emitTokenWithComment(20, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); writeSpace(); - writeToken(19, openParenPos, writePunctuation); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("in"); + emitTokenWithComment(92, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end, writePunctuation); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - writeToken(19, openParenPos, writePunctuation); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("of"); + emitTokenWithComment(144, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end, writePunctuation); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -59681,22 +60714,34 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77, node.pos, writeKeyword); + emitTokenWithComment(77, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72, node.pos, writeKeyword); + emitTokenWithComment(72, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } - function emitTokenWithComment(token, pos, writer, contextNode) { - var node = contextNode && ts.getParseTreeNode(contextNode); - if (node && node.kind === contextNode.kind) { + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, writer, contextNode); - if (node && node.kind === contextNode.kind) { + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { emitTrailingCommentsOfPosition(pos, true); } return pos; @@ -59707,35 +60752,35 @@ var ts; writeSemicolon(); } function emitWithStatement(node) { - writeKeyword("with"); + var openParenPos = emitTokenWithComment(107, node.pos, writeKeyword, node); writeSpace(); - writePunctuation("("); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(98, node.pos, writeKeyword, node); writeSpace(); - writeToken(19, openParenPos, writePunctuation); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20, node.expression.end, writePunctuation); + emitTokenWithComment(20, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - writePunctuation(":"); + emitTokenWithComment(56, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - writeKeyword("throw"); + emitTokenWithComment(100, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); writeSemicolon(); } function emitTryStatement(node) { - writeKeyword("try"); + emitTokenWithComment(102, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -59744,7 +60789,7 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - writeKeyword("finally"); + emitTokenWithComment(87, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } @@ -59756,7 +60801,7 @@ var ts; function emitVariableDeclaration(node) { emit(node.name); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); @@ -59887,7 +60932,7 @@ var ts; increaseIndent(); } emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256); + emitList(node, node.heritageClauses, 0); writeSpace(); writePunctuation("{"); emitList(node, node.members, 65); @@ -59940,6 +60985,8 @@ var ts; } emit(node.name); var body = node.body; + if (!body) + return writeSemicolon(); while (body.kind === 237) { writePunctuation("."); emit(body.name); @@ -59950,23 +60997,21 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); - writePunctuation("{"); emitBlockStatements(node, isEmptyBlock(node)); - writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17, node.pos, writePunctuation); + emitTokenWithComment(17, node.pos, writePunctuation, node); emitList(node, node.clauses, 65); - writeToken(18, node.clauses.end, writePunctuation); + emitTokenWithComment(18, node.clauses.end, writePunctuation, node, true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - writePunctuation("="); + emitTokenWithComment(58, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); writeSemicolon(); @@ -59981,12 +61026,12 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - writeKeyword("from"); + emitTokenWithComment(142, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -59995,15 +61040,15 @@ var ts; function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - writePunctuation(","); + emitTokenWithComment(26, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - writePunctuation("*"); + var asPos = emitTokenWithComment(39, node.pos, writePunctuation, node); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -60014,41 +61059,42 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - writeOperator("="); + emitTokenWithComment(58, nextPos, writeOperator, node); } else { - writeKeyword("default"); + emitTokenWithComment(79, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); writeSemicolon(); } function emitExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - writePunctuation("*"); + nextPos = emitTokenWithComment(39, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); - writeKeyword("from"); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(142, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node); writeSpace(); - writeKeyword("as"); + nextPos = emitTokenWithComment(118, nextPos, writeKeyword, node); writeSpace(); - writeKeyword("namespace"); + nextPos = emitTokenWithComment(130, nextPos, writeKeyword, node); writeSpace(); emit(node.name); writeSemicolon(); @@ -60061,14 +61107,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 432); + emitList(node, node.elements, 262576); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -60088,9 +61134,7 @@ var ts; writePunctuation("<"); emitJsxTagName(node.tagName); writeSpace(); - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); - } + emit(node.attributes); writePunctuation("/>"); } function emitJsxFragment(node) { @@ -60104,8 +61148,8 @@ var ts; emitJsxTagName(node.tagName); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); - emit(node.attributes); } + emit(node.attributes); } writePunctuation(">"); } @@ -60149,30 +61193,29 @@ var ts; } } function emitCaseClause(node) { - writeKeyword("case"); + emitTokenWithComment(73, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - writeKeyword("default"); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + var pos = emitTokenWithComment(79, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); } - function emitCaseOrDefaultClauseStatements(parentNode, statements) { + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { var emitAsSingleStatement = statements.length === 1 && (ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); - if (statements.length > 0) { - emitTrailingCommentsOfPosition(statements.pos); - } var format = 81985; if (emitAsSingleStatement) { + writeToken(56, colonPos, writePunctuation, parentNode); writeSpace(); format &= ~(1 | 64); } + else { + emitTokenWithComment(56, colonPos, writePunctuation, parentNode); + } emitList(parentNode, statements, format); } function emitHeritageClause(node) { @@ -60182,12 +61225,12 @@ var ts; emitList(node, node.types, 272); } function emitCatchClause(node) { - var openParenPos = writeToken(74, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(74, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - writeToken(19, openParenPos, writePunctuation); + emitTokenWithComment(19, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration.end, writePunctuation); + emitTokenWithComment(20, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -60220,7 +61263,7 @@ var ts; } function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } function emitSourceFile(node) { writeLine(); @@ -60236,11 +61279,31 @@ var ts; } emitSourceFileWorker(node); } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.referencedFiles, node.typeReferenceDirectives); + } + function emitTripleSlashDirectives(files, types) { + for (var _a = 0, files_1 = files; _a < files_1.length; _a++) { + var directive = files_1[_a]; + write("/// "); + writeLine(); + } + for (var _b = 0, types_18 = types; _b < types_18.length; _b++) { + var directive = types_18[_b]; + write("/// "); + writeLine(); + } + } function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); emitList(node, statements, 1, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -60322,10 +61385,10 @@ var ts; emit(node); } } - function emitInitializer(node) { + function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - writeOperator("="); + emitTokenWithComment(58, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -60450,6 +61513,9 @@ var ts; } if (format & 7680) { writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + emitTrailingCommentsOfPosition(children.pos, true); + } } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -60533,6 +61599,9 @@ var ts; onAfterEmitNodeArray(children); } if (format & 7680) { + if (isEmpty && !isUndefined) { + emitLeadingCommentsOfPosition(children.end); + } writePunctuation(getClosingBracket(format)); } } @@ -60629,9 +61698,9 @@ var ts; } function writeLines(text) { var lines = text.split(/\r\n?|\n/g); - var indentation = guessIndentation(lines); - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var lineText = lines_1[_a]; + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var lineText = lines_2[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); @@ -60640,21 +61709,6 @@ var ts; } } } - function guessIndentation(lines) { - var indentation; - 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) { - indentation = i; - break; - } - } - } - } - return indentation; - } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { increaseIndent(); @@ -60852,7 +61906,7 @@ var ts; 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)) { + if (local && local.flags & (67216319 | 1048576 | 2097152)) { return false; } } @@ -60886,7 +61940,13 @@ var ts; } } } - function makeUniqueName(baseName) { + function makeUniqueName(baseName, optimistic) { + if (optimistic) { + if (isUniqueName(baseName)) { + generatedNames.set(baseName, true); + return baseName; + } + } if (baseName.charCodeAt(baseName.length - 1) !== 95) { baseName += "_"; } @@ -60954,6 +62014,8 @@ var ts; return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 16)); case 3: return makeUniqueName(ts.idText(name)); + case 5: + return makeUniqueName(ts.idText(name), true); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -61167,8 +62229,7 @@ var ts; } 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(); + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " 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; @@ -61192,8 +62253,9 @@ var ts; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } @@ -61223,8 +62285,8 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; @@ -61258,9 +62320,7 @@ var ts; output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); output += " - "; } - var categoryColor = getCategoryFormat(diagnostic.category); - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { @@ -61506,8 +62566,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var sourceFile = files_1[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -61519,13 +62579,13 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } var unknownModuleNames; var result; @@ -62044,14 +63104,16 @@ var ts; case 185: case 186: case 205: + case 254: + case 255: if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return; } break; } - for (var _b = 0, nodes_8 = nodes; _b < nodes_8.length; _b++) { - var node = nodes_8[_b]; + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; walk(node); } } @@ -62130,9 +63192,9 @@ var ts; 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 === 71 + ? b.kind === 71 && a.escapedText === b.escapedText + : b.kind === 9 && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -62147,7 +63209,7 @@ var ts; && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); - var importDecl = ts.createImportDeclaration(undefined, undefined, undefined); + var importDecl = ts.createImportDeclaration(undefined, undefined, undefined, externalHelpersModuleReference); ts.addEmitFlags(importDecl, 67108864); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; @@ -62165,49 +63227,39 @@ var ts; file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { - switch (node.kind) { - case 242: - case 241: - case 248: - var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { - break; + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); } - if (!moduleNameExpr.text) { - break; - } - if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { - (imports || (imports = [])).push(moduleNameExpr); - } - break; - case 237: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { - var moduleName = node.name; - var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { - (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + (ambientModules || (ambientModules = [])).push(nameText); } - else if (!inAmbientModule) { - if (file.isDeclarationFile) { - (ambientModules || (ambientModules = [])).push(nameText); - } - var body = node.body; - if (body) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, true); - } + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); } } } + } } } function collectDynamicImportOrRequireCalls(node) { if (ts.isRequireCall(node, true)) { - (imports || (imports = [])).push(node.arguments[0]); + imports = ts.append(imports, node.arguments[0]); } - else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9) { - (imports || (imports = [])).push(node.arguments[0]); + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); } else { ts.forEachChild(node, collectDynamicImportOrRequireCalls); @@ -62563,8 +63615,8 @@ var ts; if (options.out && options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } - if (options.mapRoot && !options.sourceMap) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { if (!options.declaration) { @@ -62574,6 +63626,9 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } + if (options.declarationMap && !options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } @@ -62589,21 +63644,21 @@ var ts; } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { - 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)); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } 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"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - 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")); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -62622,7 +63677,7 @@ var ts; } if (options.emitDeclarationOnly) { if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -62715,18 +63770,18 @@ var ts; } return ts.emptyArray; } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(true, option1, option2, message, option1, option2); + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(true, option1, option2, message, option1, option2, option3); } function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(false, option1, undefined, message, arg0); } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } function getCompilerOptionsObjectLiteralSyntax() { @@ -62744,11 +63799,11 @@ var ts; } return _compilerOptionsObjectLiteralSyntax; } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { var props = ts.getPropertyAssignment(objectLiteral, key1, key2); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); } return !!props.length; } @@ -62876,6 +63931,13 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, { name: "watch", shortName: "w", @@ -62953,9 +64015,10 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "es2018.promise": "lib.es2018.promise.d.ts", + "es2018.regexp": "lib.es2018.regexp.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, @@ -62995,6 +64058,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, { name: "emitDeclarationOnly", type: "boolean", @@ -63917,7 +64987,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_6 = function (name) { + var _loop_7 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; @@ -63941,7 +65011,7 @@ var ts; } }; for (var name in options) { - _loop_6(name); + _loop_7(name); } return result; } @@ -64413,7 +65483,7 @@ var ts; function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); - var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; @@ -64551,12 +65621,6 @@ var ts; wildcardFiles.delete(lowerPriorityPath); } } - function caseSensitiveKeyMapper(key) { - return key; - } - function caseInsensitiveKeyMapper(key) { - return key.toLowerCase(); - } function convertCompilerOptionsForTelemetry(opts) { var out = {}; for (var key in opts) { @@ -64618,6 +65682,7 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + ts.defaultPreferences = {}; var TextChange = (function () { function TextChange() { } @@ -64971,16 +66036,13 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 71 && - (node.parent.kind === 222 || node.parent.kind === 221) && - node.parent.label === node; + return node.kind === 71 && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 && - node.parent.kind === 226 && - node.parent.label === node; + return node.kind === 71 && ts.isLabeledStatement(node.parent) && node.parent.label === node; } + ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } @@ -65113,6 +66175,8 @@ var ts; return "property"; case 5: return ts.isFunctionExpression(right) ? "method" : "property"; + case 6: + return "local class"; default: { ts.assertTypeIsNever(kind); return ""; @@ -65319,11 +66383,7 @@ var ts; } ts.findChildOfKind = findChildOfKind; function findContainingList(node) { - var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) { - return c; - } - }); + var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); }); ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); return syntaxList; } @@ -65502,6 +66562,88 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { + var tokenKind = token.kind; + var remainingMatchingTokens = 0; + while (true) { + token = findPrecedingToken(token.getFullStart(), sourceFile); + if (!token) { + return undefined; + } + if (token.kind === matchingTokenKind) { + if (remainingMatchingTokens === 0) { + return token; + } + remainingMatchingTokens--; + } + else if (token.kind === tokenKind) { + remainingMatchingTokens++; + } + } + } + ts.findPrecedingMatchingToken = findPrecedingMatchingToken; + function isPossiblyTypeArgumentPosition(token, sourceFile) { + var remainingLessThanTokens = 0; + while (token) { + switch (token.kind) { + case 27: + token = findPrecedingToken(token.getFullStart(), sourceFile); + var tokenIsIdentifier = token && ts.isIdentifier(token); + if (!remainingLessThanTokens || !tokenIsIdentifier) { + return tokenIsIdentifier; + } + remainingLessThanTokens--; + break; + case 47: + remainingLessThanTokens = +3; + break; + case 46: + remainingLessThanTokens = +2; + break; + case 29: + remainingLessThanTokens++; + break; + case 18: + token = findPrecedingMatchingToken(token, 17, sourceFile); + if (!token) + return false; + break; + case 20: + token = findPrecedingMatchingToken(token, 19, sourceFile); + if (!token) + return false; + break; + case 22: + token = findPrecedingMatchingToken(token, 21, sourceFile); + if (!token) + return false; + break; + case 26: + case 36: + case 71: + case 9: + case 8: + case 101: + case 86: + case 103: + case 85: + case 128: + case 23: + case 49: + case 55: + case 56: + break; + default: + if (ts.isTypeNode(token)) { + break; + } + return false; + } + token = findPrecedingToken(token.getFullStart(), sourceFile); + } + return false; + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; function isInComment(sourceFile, position, tokenAtPosition, predicate) { return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, false, undefined, tokenAtPosition, predicate); } @@ -65679,15 +66821,6 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; - function addToSeen(seen, key) { - key = String(key); - if (seen.has(key)) { - return false; - } - seen.set(key, true); - return true; - } - ts.addToSeen = addToSeen; function getSnapshotText(snap) { return snap.getText(0, snap.getLength()); } @@ -65958,31 +67091,27 @@ var ts; } ts.getSynthesizedDeepClones = getSynthesizedDeepClones; 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); - } - } + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); } ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } + function getFirstChild(node) { + return node.forEachChild(function (child) { return child; }); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -66155,16 +67284,15 @@ var ts; return textSpan(node); } if (node.kind === 198) { - var binaryExpression = node; - if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { - return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); + var _a = node, left = _a.left, operatorToken = _a.operatorToken; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } - if (binaryExpression.operatorToken.kind === 58 && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + if (operatorToken.kind === 58 && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (binaryExpression.operatorToken.kind === 26) { - return spanInNode(binaryExpression.left); + if (operatorToken.kind === 26) { + return spanInNode(left); } } if (ts.isExpressionNode(node)) { @@ -66188,40 +67316,43 @@ var ts; break; } } - if (node.parent.kind === 268 && - node.parent.name === node && - !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { - return spanInNode(node.parent.initializer); - } - if (node.parent.kind === 188 && 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 === 230 || - node.parent.kind === 148)) { - var paramOrVarDecl = node.parent; - if (paramOrVarDecl.initializer === node || - paramOrVarDecl.type === node || - ts.isAssignmentOperator(node.kind)) { - return spanInPreviousNode(node); + switch (node.parent.kind) { + case 268: + if (node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + return spanInNode(node.parent.initializer); + } + break; + case 188: + if (node.parent.type === node) { + return spanInNextNode(node.parent.type); + } + break; + case 230: + case 148: { + var _b = node.parent, initializer = _b.initializer, type = _b.type; + if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; } - } - if (node.parent.kind === 198) { - var binaryExpression = node.parent; - if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && - (binaryExpression.right === node || - binaryExpression.operatorToken === node)) { - return spanInPreviousNode(node); + case 198: { + var left = node.parent.left; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + return spanInPreviousNode(node); + } + break; } + default: + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } } return spanInNode(node.parent); } } function textSpanFromVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 231 && - variableDeclaration.parent.declarations[0] === variableDeclaration) { + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) { return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); } else { @@ -66240,7 +67371,7 @@ var ts; variableDeclaration.parent.parent.kind === 220) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (variableDeclaration.parent.kind === 231 && + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] !== variableDeclaration) { return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); } @@ -66616,7 +67747,7 @@ var ts; case 13: return 4; default: - throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } return lastOnTemplateStack === 14 ? 6 : undefined; @@ -66709,7 +67840,7 @@ var ts; case 0: return { prefix: "" }; default: - throw ts.Debug.assertNever(lexState); + return ts.Debug.assertNever(lexState); } } function isBinaryExpressionOperatorToken(token) { @@ -67208,28 +68339,37 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function createPathCompletion(name, kind, span) { - return { name: name, kind: kind, span: span }; + function nameAndKind(name, kind) { + return { name: name, kind: kind }; + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind; + return ({ name: name, kind: kind, span: span }); + }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker)); + } + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + function getStringLiteralCompletionsFromModuleNamesWorker(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(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, false, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, false, host, scriptPath); } } else { - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } - PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { @@ -67237,18 +68377,18 @@ var ts; }); 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) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); var result = []; for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, host, exclude, result); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); } return result; } - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, host, exclude, result) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -67266,8 +68406,8 @@ var ts; var files = tryReadDirectory(host, baseDirectory, extensions, undefined, ["./*"]); if (files) { var foundFiles = ts.createMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var filePath = files_2[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0) { continue; @@ -67278,7 +68418,7 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createPathCompletion(foundFile, "script", span)); + result.push(nameAndKind(foundFile, "script")); }); } var directories = tryGetDirectories(host, baseDirectory); @@ -67286,31 +68426,31 @@ var ts; 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(createPathCompletion(directoryName, "directory", span)); + result.push(nameAndKind(directoryName, "directory")); } } } return result; } - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span, compilerOptions, host, typeChecker) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; var fileExtensions = ts.getSupportedExtensions(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, span, host, undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, host, undefined, result); for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (name, kind) { + var _loop_8 = function (name, kind) { if (!result.some(function (entry) { return entry.name === name; })) { - result.push(createPathCompletion(name, kind, span)); + result.push(nameAndKind(name, kind)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_7(name, kind); + _loop_8(name, kind); } } } @@ -67319,14 +68459,14 @@ var ts; 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); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, false, host, undefined, result); } }); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { var moduleName = _d[_c]; - result.push(createPathCompletion(moduleName, "external module name", span)); + result.push(nameAndKind(moduleName, "external module name")); } return result; } @@ -67419,21 +68559,13 @@ var ts; } 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); - return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, host, sourceFile.path); - } - 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; - } + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) + : undefined; + return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, result) { if (result === void 0) { result = []; } var seen = ts.createMap(); if (options.types) { @@ -67479,7 +68611,7 @@ var ts; } function pushResult(moduleName) { if (!seen.has(moduleName)) { - result.push(createPathCompletion(moduleName, "external module name", span)); + result.push(nameAndKind(moduleName, "external module name")); seen.set(moduleName, true); } } @@ -67541,9 +68673,10 @@ var ts; } } function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6) ? undefined : ts.createTextSpan(textStart + offset, length); } function isPathRelativeToScript(path) { if (path && path.length >= 2 && path.charCodeAt(0) === 46) { @@ -67603,11 +68736,18 @@ var ts; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { + var GlobalsSearch; + (function (GlobalsSearch) { + GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue"; + GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; + GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; + })(GlobalsSearch || (GlobalsSearch = {})); + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && convertPathCompletions(entries); @@ -67616,19 +68756,19 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log); + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 || contextToken.kind === 77 || contextToken.kind === 71)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, preferences, compilerOptions.target); if (!completionData) { return undefined; } switch (completionData.kind) { case 0: - return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); case 1: return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); case 2: @@ -67636,11 +68776,11 @@ var ts; case 3: return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); default: - throw ts.Debug.assertNever(completionData); + return ts.Debug.assertNever(completionData); } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log) { + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -67649,12 +68789,12 @@ var ts; return convertPathCompletions(completion.paths); case 1: { var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6, log, 4); - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6, log, 4, preferences); + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "", kind: "var", sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "", kind: "type", sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } default: return ts.Debug.assertNever(completion); @@ -67672,8 +68812,8 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; if (sourceFile.languageVariant === 1 && location && location.parent && ts.isJsxClosingElement(location.parent)) { var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, @@ -67686,20 +68826,20 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: completionKind === 1, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isMemberCompletionKind(kind) { switch (kind) { @@ -67727,7 +68867,7 @@ var ts; } }); } - function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); if (!info) { return undefined; @@ -67735,12 +68875,12 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (includeInsertTextCompletions) { + if (preferences.includeCompletionsWithInsertText) { if (origin && origin.type === "this-type") { - insertText = needsConvertPropertyAccess ? "this[" + quote(name) + "]" : "this." + name; + insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; } else if (needsConvertPropertyAccess) { - insertText = "[" + quote(name) + "]"; + insertText = "[" + quote(name, preferences) + "]"; var dot = ts.findChildOfKind(propertyAccessToConvert, 23, sourceFile); var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); @@ -67754,7 +68894,7 @@ var ts; } } } - if (insertText !== undefined && !includeInsertTextCompletions) { + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } return { @@ -67769,8 +68909,17 @@ var ts; replacementSpan: replacementSpan, }; } - function quote(text) { - return JSON.stringify(text); + function quote(text, preferences) { + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || @@ -67782,13 +68931,13 @@ var ts; function getSourceFromOrigin(origin) { return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); var uniques = ts.createMap(); for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { var symbol = symbols_4[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } @@ -67847,20 +68996,19 @@ var ts; case 161: return { kind: 2, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent), typeChecker) }; case 175: - return { kind: 1, symbols: typeChecker.getTypeFromTypeNode(node.parent.parent.objectType).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); default: return undefined; } case 268: if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { - var type = typeChecker.getContextualType(node.parent.parent); - return { kind: 1, symbols: type && type.getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); } return fromContextualType(); case 184: { var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { - return { kind: 1, symbols: typeChecker.getTypeAtLocation(expression).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); } return undefined; } @@ -67887,6 +69035,9 @@ var ts; return { kind: 2, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker), typeChecker) }; } } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } function getStringLiteralTypes(type, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 32768) { @@ -67900,7 +69051,7 @@ var ts; } 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, includeInsertTextCompletions: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } @@ -67920,9 +69071,16 @@ var ts; || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; } - function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName, preferences) { var typeChecker = program.getTypeChecker(); var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker); + } var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); switch (symbolCompletion.type) { case "request": { @@ -67940,39 +69098,45 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, 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 (allKeywordsCompletions().some(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; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, codeActions, sourceDisplay); } + case "none": + return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createCompletionDetails(name, "", "keyword", [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)]) : undefined; } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo && symbolOriginInfo.type === "export" - ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) - : { codeActions: undefined, sourceDisplay: undefined }; + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, codeActions, sourceDisplay) { + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker) { + switch (completion.kind) { + case 0: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && createCompletionDetails(name, "", match.kind, [ts.textPart(name)]); + } + case 1: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location); + } + case 2: + return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "", "type", [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || symbolOriginInfo.type !== "export") { + return { codeActions: undefined, sourceDisplay: undefined }; + } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { @@ -68063,7 +69227,7 @@ var ts; function isModuleSymbol(symbol) { return symbol.declarations.some(function (d) { return d.kind === 272; }); } - function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, preferences, target) { var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, false); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); @@ -68071,6 +69235,7 @@ var ts; var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); var insideJsDocTagTypeExpression = false; + var isInSnippetScope = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64) { @@ -68204,9 +69369,9 @@ var ts; getTypeScriptMemberSymbols(); } else if (isRightOfOpenTag) { - var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNames(), "getJsxIntrinsicTagNames() should all be defined"); + var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 2097152)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 | 2097152)); })); } else { symbols = tagSymbols; @@ -68228,7 +69393,7 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, position, sourceFile, typeChecker); - return { kind: 0, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { kind: 0, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 287: @@ -68243,6 +69408,7 @@ var ts; completionKind = 2; var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile)); if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { @@ -68251,7 +69417,7 @@ var ts; var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; - var isValidAccess = isRhsOfImportDeclaration ? + var isValidAccess = allowTypeOrValue ? 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++) { @@ -68272,6 +69438,7 @@ var ts; } } function addTypeProperties(type) { + isNewIdentifierLocation = hasIndexSignature(type); if (ts.isSourceFileJavaScript(sourceFile)) { symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, true)); } @@ -68285,42 +69452,37 @@ var ts; } } function tryGetGlobalSymbols() { - var objectLikeContainer; - var namedImportsOrExports; - var classLikeContainer; - var jsxContainer; - if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { - return tryGetObjectLikeCompletionSymbols(objectLikeContainer); - } - if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { - return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); - } - if (tryGetConstructorLikeCompletionContainer(contextToken)) { - completionKind = 5; - isNewIdentifierLocation = true; - keywordFilters = 2; - return true; - } - if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { - getGetClassLikeCompletionSymbols(classLikeContainer); - return true; - } - if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType = void 0; - if ((jsxContainer.kind === 254) || (jsxContainer.kind === 255)) { - attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); - if (attrsType) { - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - completionKind = 3; - isNewIdentifierLocation = false; - return true; - } - } - } - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 3; - } + var result = tryGetObjectLikeCompletionSymbols() + || tryGetImportOrExportClauseCompletionSymbols() + || tryGetConstructorCompletion() + || tryGetClassLikeCompletionSymbols() + || tryGetJsxCompletionSymbols() + || (getGlobalCompletions(), 1); + return result === 1; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) + return 0; completionKind = 5; + isNewIdentifierLocation = true; + keywordFilters = 3; + return 1; + } + function tryGetJsxCompletionSymbols() { + var jsxContainer = tryGetContainingJsxElement(contextToken); + var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + if (!attrsType) + return 0; + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); + completionKind = 3; + isNewIdentifierLocation = false; + return 1; + } + function getGlobalCompletions() { + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 4; + } + completionKind = 1; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -68329,12 +69491,10 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (isGlobalCompletionScope(scopeNode)) { - completionKind = 1; - } - var symbolMeanings = 793064 | 107455 | 1920 | 2097152; + isInSnippetScope = isSnippetScope(scopeNode); + var symbolMeanings = 67901928 | 67216319 | 1920 | 2097152; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); - if (options.includeInsertTextCompletions && scopeNode.kind !== 272) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 272) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, true); _i < _a.length; _i++) { @@ -68344,13 +69504,12 @@ var ts; } } } - if (options.includeExternalModuleExports) { + if (preferences.includeCompletionsForModuleExports && !(sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator)) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } filterGlobalCompletion(symbols); - return true; } - function isGlobalCompletionScope(scopeNode) { + function isSnippetScope(scopeNode) { switch (scopeNode.kind) { case 272: case 200: @@ -68362,9 +69521,10 @@ var ts; } } function filterGlobalCompletion(symbols) { - var isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - if (isTypeCompletion) - keywordFilters = 4; + var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile); + if (isTypeOnlyCompletion) + keywordFilters = 5; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { if (ts.isExportAssignment(location.parent)) { @@ -68374,17 +69534,20 @@ var ts; if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920); } - if (isTypeCompletion) { - return symbolCanBeReferencedAtTypeLocation(symbol); + if (allowTypes) { + var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); + if (symbolAllowedAsType || isTypeOnlyCompletion) { + return symbolAllowedAsType; + } } } - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319); }); } function isContextTokenValueLocation(contextToken) { return contextToken && contextToken.kind === 103 && - contextToken.parent.kind === 164; + (contextToken.parent.kind === 164 || ts.isTypeOfExpression(contextToken.parent)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { @@ -68407,7 +69570,7 @@ var ts; function symbolCanBeReferencedAtTypeLocation(symbol) { symbol = symbol.exportSymbol || symbol; symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 793064) { + if (symbol.flags & 67901928) { return true; } if (symbol.flags & 1536) { @@ -68521,10 +69684,10 @@ var ts; case 113: return containingNodeKind === 151; } - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": + switch (keywordForNode(previousToken)) { + case 114: + case 113: + case 112: return true; } } @@ -68546,15 +69709,18 @@ var ts; } return false; } - function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + function tryGetObjectLikeCompletionSymbols() { + var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); + if (!objectLikeContainer) + return 0; completionKind = 0; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 182) { - isNewIdentifierLocation = true; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) - return false; + return 2; + isNewIdentifierLocation = hasIndexSignature(typeForObject); typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, false); existingMembers = objectLikeContainer.properties; } @@ -68563,7 +69729,7 @@ var ts; isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (!ts.isVariableLike(rootDeclaration)) - throw ts.Debug.fail("Root declaration is not variable-like."); + return ts.Debug.fail("Root declaration is not variable-like."); var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 220; if (!canGetType && rootDeclaration.kind === 148) { if (ts.isExpression(rootDeclaration.parent)) { @@ -68576,7 +69742,7 @@ var ts; if (canGetType) { var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); if (!typeForObject) - return false; + return 2; typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24); }); existingMembers = objectLikeContainer.elements; } @@ -68584,63 +69750,60 @@ var ts; if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); } - return true; + return 1; } - function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + function tryGetImportOrExportClauseCompletionSymbols() { + var namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken); + if (!namedImportsOrExports) + return undefined; var declarationKind = namedImportsOrExports.kind === 245 ? 242 : 248; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { - return false; + return 2; } completionKind = 3; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { symbols = ts.emptyArray; - return true; + return 2; } var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); - return true; + return 1; } - function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + function tryGetClassLikeCompletionSymbols() { + var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location); + if (!decl) + return 0; completionKind = 3; isNewIdentifierLocation = true; - keywordFilters = 1; - 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)) { - switch (contextToken.getText()) { - case "private": - classElementModifierFlags = classElementModifierFlags | 8; - break; - case "static": - classElementModifierFlags = classElementModifierFlags | 32; - break; - } - } - if (!(classElementModifierFlags & 8)) { - var baseClassTypeToGetPropertiesFrom = void 0; - if (baseTypeNode) { - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); - if (classElementModifierFlags & 32) { - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); - } - } - var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? - ts.emptyArray : - ts.flatMap(implementsTypeNodes || ts.emptyArray, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); - symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? - typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : - ts.emptyArray, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + keywordFilters = ts.isClassLike(decl) ? 1 : 2; + if (!ts.isClassLike(decl)) + return 1; + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { + switch (contextToken.getText()) { + case "private": + classElementModifierFlags = classElementModifierFlags | 8; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32; + break; } } + if (!(classElementModifierFlags & 8)) { + var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } + return 1; } function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { @@ -68670,52 +69833,9 @@ var ts; } return undefined; } - function isFromClassElementDeclaration(node) { - return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); - } - function isParameterOfConstructorDeclaration(node) { - return ts.isParameter(node) && ts.isConstructorDeclaration(node.parent); - } function isConstructorParameterCompletion(node) { - return node.parent && - isParameterOfConstructorDeclaration(node.parent) && - (isConstructorParameterCompletionKeyword(node.kind) || ts.isDeclarationName(node)); - } - function tryGetClassLikeCompletionContainer(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 17: - if (ts.isClassLike(contextToken.parent)) { - return contextToken.parent; - } - break; - case 26: - if (ts.isClassLike(contextToken.parent)) { - return contextToken.parent; - } - break; - case 25: - case 18: - if (ts.isClassLike(location)) { - return location; - } - if (isFromClassElementDeclaration(location) && - location.parent.name === location) { - return location.parent.parent; - } - break; - default: - if (isFromClassElementDeclaration(contextToken) && - (isClassMemberCompletionKeyword(contextToken.kind) || - isClassMemberCompletionKeywordText(contextToken.getText()))) { - return contextToken.parent.parent; - } - } - } - if (location && location.kind === 293 && ts.isClassLike(location.parent)) { - return location.parent; - } - return undefined; + return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent) + && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node)); } function tryGetConstructorLikeCompletionContainer(contextToken) { if (contextToken) { @@ -68808,14 +69928,7 @@ var ts; return containingNodeKind === 267 || isFunctionLikeButNotConstructor(containingNodeKind); case 17: - return containingNodeKind === 236 || - containingNodeKind === 234 || - containingNodeKind === 165; - case 25: - return containingNodeKind === 150 && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 234 || - contextToken.parent.parent.kind === 165); + return containingNodeKind === 236; case 27: return containingNodeKind === 233 || containingNodeKind === 203 || @@ -68838,7 +69951,7 @@ var ts; containingNodeKind === 244; case 125: case 136: - if (isFromClassElementDeclaration(contextToken)) { + if (isFromObjectTypeDeclaration(contextToken)) { return false; } case 75: @@ -68853,33 +69966,32 @@ var ts; case 139: return true; } - if (isClassMemberCompletionKeywordText(contextToken.getText()) && - isFromClassElementDeclaration(contextToken)) { + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; } if (isConstructorParameterCompletion(contextToken)) { if (!ts.isIdentifier(contextToken) || - isConstructorParameterCompletionKeywordText(contextToken.getText()) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || isCurrentlyEditingNode(contextToken)) { return false; } } - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": + switch (keywordForNode(contextToken)) { + case 117: + case 120: + case 75: + case 76: + case 124: + case 83: + case 89: + case 109: + case 110: + case 112: + case 113: + case 114: + case 115: + case 104: + case 116: return true; } return ts.isDeclarationName(contextToken) @@ -68934,13 +70046,13 @@ var ts; } else { var name = ts.getNameOfDeclaration(m); - existingName = ts.getEscapedTextOfIdentifierOrLiteral(name); + existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } existingMemberNames.set(existingName, true); } return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); } - function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; @@ -68956,10 +70068,7 @@ var ts; if (ts.hasModifier(m, 8)) { continue; } - var mIsStatic = ts.hasModifier(m, 32); - var currentElementIsStatic = !!(currentClassElementModifierFlags & 32); - if ((mIsStatic && !currentElementIsStatic) || - (!mIsStatic && currentElementIsStatic)) { + if (ts.hasModifier(m, 32) !== !!(currentClassElementModifierFlags & 32)) { continue; } var existingName = ts.getPropertyNameForPropertyNameNode(m.name); @@ -68967,23 +70076,11 @@ var ts; existingMemberNames.set(existingName, true); } } - var result = []; - addPropertySymbols(baseSymbols, 8); - addPropertySymbols(implementingTypeSymbols, 24); - return result; - function addPropertySymbols(properties, inValidModifierFlags) { - for (var _i = 0, properties_12 = properties; _i < properties_12.length; _i++) { - var property = properties_12[_i]; - if (isValidProperty(property, inValidModifierFlags)) { - result.push(property); - } - } - } - function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.escapedName) && - propertySymbol.getDeclarations() && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); - } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8); + }); } function filterJsxAttributes(symbols, attributes) { var seenNames = ts.createUnderscoreEscapedMap(); @@ -68999,7 +70096,7 @@ var ts; return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { - return node.getStart() <= position && position <= node.getEnd(); + return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { @@ -69018,9 +70115,9 @@ var ts; case 0: return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2: - case 5: case 1: return name.charCodeAt(0) === 32 ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 5: case 4: return validIdentiferResult; default: @@ -69049,61 +70146,35 @@ var ts; case 1: return isClassMemberCompletionKeyword(kind); case 2: - return isConstructorParameterCompletionKeyword(kind); + return isInterfaceOrTypeLiteralCompletionKeyword(kind); case 3: - return isFunctionLikeBodyCompletionKeyword(kind); + return ts.isParameterPropertyModifier(kind); case 4: + return !isClassMemberCompletionKeyword(kind); + case 5: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); } })); } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 132; + } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 114: - case 113: - case 112: case 117: - case 115: case 123: - case 132: case 125: case 136: case 120: return true; + default: + return ts.isClassMemberModifier(kind); } } - function isClassMemberCompletionKeywordText(text) { - return isClassMemberCompletionKeyword(ts.stringToToken(text)); - } - function isConstructorParameterCompletionKeyword(kind) { - switch (kind) { - case 114: - case 112: - case 113: - case 132: - return true; - } - } - function isConstructorParameterCompletionKeywordText(text) { - return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); - } - function isFunctionLikeBodyCompletionKeyword(kind) { - switch (kind) { - case 114: - case 112: - case 113: - case 132: - case 123: - case 115: - case 117: - case 125: - case 136: - case 140: - return false; - } - return true; + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 : node.kind; } function isEqualityOperatorKind(kind) { switch (kind) { @@ -69154,6 +70225,41 @@ var ts; }); return ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined"); } + function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + switch (location.kind) { + case 293: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 18, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 25: + case 18: + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 17: + case 26: + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) + ? contextToken.parent.parent : undefined; + } + } + function isFromObjectTypeDeclaration(node) { + return node.parent && (ts.isClassElement(node.parent) || ts.isTypeElement(node.parent)) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -69182,30 +70288,17 @@ var ts; } function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); - return referenceEntries && convertReferencedSymbols(referenceEntries); - } - function convertReferencedSymbols(referenceEntries) { - var fileNameToDocumentHighlights = ts.createMap(); - for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { - var entry = referenceEntries_1[_i]; - var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span; - var highlightSpans = fileNameToDocumentHighlights.get(fileName); - if (!highlightSpans) { - fileNameToDocumentHighlights.set(fileName, highlightSpans = []); - } - highlightSpans.push(span_12); - } - return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) { + if (!referenceEntries) + return undefined; + var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); + return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; return ({ fileName: fileName, highlightSpans: highlightSpans }); }); } function getSyntacticDocumentHighlights(node, sourceFile) { var highlightSpans = getHighlightSpans(node, sourceFile); - if (!highlightSpans || highlightSpans.length === 0) { - return undefined; - } - return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { @@ -69691,7 +70784,9 @@ var ts; } else if (ts.isDefaultImport(direct)) { var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); - addIndirectUser(sourceFileLike); + if (!isAvailableThroughGlobal) { + addIndirectUser(sourceFileLike); + } directImports.push(direct); } else { @@ -69912,8 +71007,8 @@ var ts; function forEachImport(sourceFile, action) { if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); } } else { @@ -69940,19 +71035,6 @@ var ts; }); } } - function importerFromModuleSpecifier(moduleSpecifier) { - var decl = moduleSpecifier.parent; - switch (decl.kind) { - case 185: - case 242: - case 248: - return decl; - case 252: - return decl.parent; - default: - ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); - } - } function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { @@ -70122,8 +71204,8 @@ var ts; if (parent.kind === 272) { return parent; } - ts.Debug.assert(parent.kind === 238 && isAmbientModuleDeclaration(parent.parent)); - return parent.parent; + ts.Debug.assert(parent.kind === 238); + return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { return node.kind === 237 && node.name.kind === 9; @@ -70143,11 +71225,12 @@ var ts; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, {}); var checker = program.getTypeChecker(); return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { var definition = _a.definition, references = _a.references; - return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }; + return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) }; }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; @@ -70164,9 +71247,9 @@ var ts; } var checker = program.getTypeChecker(); if (node.parent.kind === 269) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { var symbol = checker.getSymbolAtLocation(node); @@ -70177,8 +71260,8 @@ var ts; } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); - return ts.map(x, toReferenceEntry); + var node = ts.getTouchingPropertyName(sourceFile, position, true); + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { @@ -70186,60 +71269,50 @@ var ts; return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); - } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); } - function definitionToReferencedSymbolDefinitionInfo(def, checker) { + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { case "symbol": { - var symbol = def.symbol, node_3 = def.node; - var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var symbol = def.symbol; + var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - var node_4 = def.node; - return { node: node_4, name: node_4.text, kind: "label", displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] }; + var node_3 = def.node; + return { node: node_3, name: node_3.text, kind: "label", displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { - var node_5 = def.node; - var name_5 = ts.tokenToString(node_5.kind); - return { node: node_5, name: name_5, kind: "keyword", displayParts: [{ text: name_5, kind: "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" }] }; } case "this": { - 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 }; + 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 }; } case "string": { - 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)] }; + 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)] }; } + default: + return ts.Debug.assertNever(def); } })(); - if (!info) { - return undefined; - } var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); - return { - containerKind: "", - containerName: "", - fileName: sourceFile.fileName, - kind: kind, - name: name, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: displayParts - }; + var textSpan = getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile); + return { containerKind: "", containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: textSpan, displayParts: displayParts }; } - function getDefinitionKindAndDisplayParts(symbol, node, checker) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind; + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); + var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } function toReferenceEntry(entry) { @@ -70270,7 +71343,7 @@ var ts; function implementationKindDisplayParts(node, checker) { var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node); if (symbol) { - return getDefinitionKindAndDisplayParts(symbol, node, checker); + return getDefinitionKindAndDisplayParts(symbol, checker, node); } else if (node.kind === 182) { return { @@ -70304,8 +71377,8 @@ var ts; return { fileName: fileName, span: span }; } FindAllReferences.toHighlightSpan = toHighlightSpan; - function getTextSpan(node) { - var start = node.getStart(); + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); var end = node.getEnd(); if (node.kind === 9) { start += 1; @@ -70388,23 +71461,18 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ - definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, - references: references - }]; + return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; } function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); } - if (ts.isLabelName(node)) { - if (ts.isJumpStatementTarget(node)) { - var labelDefinition = ts.getTargetLabel(node.parent, node.text); - return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); - } - else { - return getLabelReferencesInNode(node.parent, node); - } + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); + } + else if (ts.isLabelOfLabeledStatement(node)) { + return getLabelReferencesInNode(node.parent, node); } if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); @@ -70416,18 +71484,18 @@ var ts; } function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; - var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); + var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); var result = []; var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === 79) { - addReference(node, symbol, node, state); + addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 }, state); } else { 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); + getReferencesInContainer(scope, scope.getSourceFile(), search, state, !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); } else { for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { @@ -70490,7 +71558,11 @@ var ts; this.markSeenReExportRHS = ts.nodeSeenTracker(); this.symbolIdToReferences = []; this.sourceFileToSeenSymbols = []; + this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; }); } + State.prototype.includesSourceFile = function (sourceFile) { + return this.includedSourceFiles.has(sourceFile.fileName); + }; State.prototype.getImportSearches = function (exportSymbol, exportInfo) { if (!this.importTracker) this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken); @@ -70498,20 +71570,20 @@ 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.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _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, allSearchSymbols = searchOptions.allSearchSymbols; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { - location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, + symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, }; }; - State.prototype.referenceAdder = function (searchSymbol, searchLocation) { + State.prototype.referenceAdder = function (searchSymbol) { var symbolId = ts.getSymbolId(searchSymbol); var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references }); + this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; @@ -70532,7 +71604,7 @@ var ts; function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; if (singleReferences.length) { - var addRef = state.referenceAdder(exportSymbol, exportLocation); + var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; addRef(singleRef); @@ -70565,7 +71637,8 @@ var ts; 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); + var exportingFile = declaration.getSourceFile(); + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0), state, state.includesSourceFile(exportingFile)); } } function searchForName(sourceFile, search, state) { @@ -70633,6 +71706,16 @@ var ts; } return exposedByParent ? scope.getSourceFile() : scope; } + function isSymbolReferencedInFile(definition, checker, sourceFile) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return true; + return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) { + var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, true), ts.isIdentifier); + return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol; + }); + } + Core.isSymbolReferencedInFile = isSymbolReferencedInFile; function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } var positions = []; @@ -70656,26 +71739,23 @@ var ts; return positions; } function getLabelReferencesInNode(container, targetLabel) { - var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); - for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { - var position = possiblePositions_1[_i]; + var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) { var node = ts.getTouchingWord(sourceFile, position, false); - if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { - references.push(FindAllReferences.nodeEntry(node)); - } - } + return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined; + }); return [{ definition: { type: "label", node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { switch (node.kind) { case 71: return node.text.length === searchSymbolName.length; - case 9: - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.text.length === searchSymbolName.length; + case 9: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + str.text.length === searchSymbolName.length; + } case 8: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; case 79: @@ -70685,38 +71765,30 @@ var ts; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { - var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); - } + return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); + return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; + }); + }); return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } - function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - 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); - if (referenceLocation.kind === kind) { - references.push(FindAllReferences.nodeEntry(referenceLocation)); - } - } - } - function getReferencesInSourceFile(sourceFile, search, state) { + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } state.cancellationToken.throwIfCancellationRequested(); - return getReferencesInContainer(sourceFile, sourceFile, search, state); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); } - function getReferencesInContainer(container, sourceFile, search, state) { + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; - getReferencesAtLocation(sourceFile, position, search, state); + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } - function getReferencesAtLocation(sourceFile, position, search, state) { + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (!isValidReferencePosition(referenceLocation, search.text)) { if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { @@ -70737,7 +71809,7 @@ var ts; } if (ts.isExportSpecifier(parent)) { ts.Debug.assert(referenceLocation.kind === 71); - getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); @@ -70747,7 +71819,8 @@ var ts; } switch (state.specialSearchKind) { case 0: - addReference(referenceLocation, relatedSymbol, search.location, state); + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); break; case 1: addConstructorReferences(referenceLocation, sourceFile, search, state); @@ -70760,7 +71833,7 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -70774,8 +71847,8 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, name, state); + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { + addReference(name, referenceSymbol, state); } } else { @@ -70795,7 +71868,8 @@ var ts; searchForImportedSymbol(imported, state); } function addRef() { - addReference(referenceLocation, localSymbol, search.location, state); + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); } } function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { @@ -70829,11 +71903,11 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 33554432) && search.includes(shorthandValueSymbol)) { - addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state); } } - function addReference(referenceLocation, relatedSymbol, searchLocation, state) { - var addRef = state.referenceAdder(relatedSymbol, searchLocation); + function addReference(referenceLocation, relatedSymbol, state) { + var addRef = state.referenceAdder(relatedSymbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } @@ -70843,9 +71917,9 @@ var ts; } function addConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { - addReference(referenceLocation, search.symbol, search.location, state); + addReference(referenceLocation, search.symbol, state); } - var pusher = function () { return state.referenceAdder(search.symbol, search.location); }; + var pusher = function () { return state.referenceAdder(search.symbol); }; if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.kind === 79 || referenceLocation.parent.name === referenceLocation); findOwnConstructorReferences(search.symbol, sourceFile, pusher()); @@ -70858,10 +71932,10 @@ var ts; } } function addClassStaticThisReferences(referenceLocation, search, state) { - addReference(referenceLocation, search.symbol, search.location, state); - if (ts.isClassLike(referenceLocation.parent)) { + addReference(referenceLocation, search.symbol, state); + if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); - addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol)); } } function addStaticThisReferences(classLike, pusher) { @@ -70977,7 +72051,7 @@ var ts; return result; } function getContainingTypeReference(node) { - var topLevelTypeReference = undefined; + var topLevelTypeReference; while (node) { if (ts.isTypeNode(node)) { topLevelTypeReference = node; @@ -71013,53 +72087,24 @@ var ts; return false; } } - function explicitlyInheritsFrom(child, parent, cachedResults, checker) { - var parentIsInterface = parent.getFlags() & 64; - return searchHierarchy(child); - function searchHierarchy(symbol) { - if (symbol === parent) { - return true; - } - var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); - var cached = cachedResults.get(key); - if (cached !== undefined) { - return cached; - } - cachedResults.set(key, false); - var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - if (parentIsInterface) { - var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); - if (interfaceReferences) { - for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { - var typeReference = interfaceReferences_1[_i]; - if (searchTypeReference(typeReference)) { - return true; - } - } - } - } - return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - } - else if (declaration.kind === 234) { - if (parentIsInterface) { - return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); - } - } - return false; - }); - cachedResults.set(key, inherits); - return inherits; + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; } - function searchTypeReference(typeReference) { - if (typeReference) { + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { var type = checker.getTypeAtLocation(typeReference); - if (type && type.symbol) { - return searchHierarchy(type.symbol); - } - } - return false; - } + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; } function getReferencesForSuperKeyword(superKeyword) { var searchSpaceNode = ts.getSuperContainer(superKeyword, false); @@ -71081,21 +72126,16 @@ var ts; default: return undefined; } - var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) { var node = ts.getTouchingWord(sourceFile, position, false); if (!node || node.kind !== 97) { - continue; + return; } var container = ts.getSuperContainer(node, false); - if (container && (32 & 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 }]; + return container && (32 & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); @@ -71125,18 +72165,11 @@ var ts; return undefined; } var references = []; - var possiblePositions; - if (searchSpaceNode.kind === 272) { - ts.forEach(sourceFiles, function (sourceFile) { - cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); - getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, staticFlag, references); - }); - } - else { - var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); - getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, references); + for (var _i = 0, _a = searchSpaceNode.kind === 272 ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + cancellationToken.throwIfCancellationRequested(); + var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode); + getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 ? sourceFile : searchSpaceNode, positions, staticFlag, references); } return [{ definition: { type: "this", node: thisOrSuperKeyword }, @@ -71178,26 +72211,17 @@ var ts; }); } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { - var references = []; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); - getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); - } + return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) { + var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, false), ts.isStringLiteral); + return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, true) : undefined; + }); + }); return [{ definition: { type: "string", node: node }, references: references }]; - 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_8 = ts.getTouchingWord(sourceFile, position, false); - if (node_8 && node_8.kind === 9 && node_8.text === searchText) { - references.push(FindAllReferences.nodeEntry(node_8, true)); - } - } - } } function populateSearchSymbolSet(symbol, location, checker, implementations) { var result = []; @@ -71242,28 +72266,17 @@ var ts; : undefined; } function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache, checker) { - if (!symbol) { - return; - } - if (previousIterationSymbolsCache.has(symbol.escapedName)) { + if (!symbol || previousIterationSymbolsCache.has(symbol.escapedName)) { return; } if (symbol.flags & (32 | 64)) { - ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); - } - else if (declaration.kind === 234) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = checker.getTypeAtLocation(typeReference); - if (type) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + for (var _b = 0, _c = ts.getAllSuperTypeNodes(declaration); _b < _c.length; _b++) { + var typeReference = _c[_b]; + var type = checker.getTypeAtLocation(typeReference); + if (!type) + continue; var propertySymbol = checker.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push.apply(result, checker.getRootSymbols(propertySymbol)); @@ -71307,7 +72320,7 @@ var ts; function findRootSymbol(sym) { return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { if (search.includes(rootSymbol)) { - return rootSymbol; + return ts.getCheckFlags(sym) & 6 ? sym : rootSymbol; } if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })) { @@ -71315,7 +72328,7 @@ var ts; } var result = []; getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); - return ts.find(result, search.includes); + return result.some(search.includes) ? rootSymbol : undefined; } return undefined; }); @@ -71338,7 +72351,9 @@ var ts; return symbol ? [symbol] : contextualType && contextualType.flags & 131072 ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; } - function getIntersectingMeaningFromDeclarations(meaning, declarations) { + function getIntersectingMeaningFromDeclarations(node, symbol) { + var meaning = ts.getMeaningFromLocation(node); + var declarations = symbol.declarations; if (declarations) { var lastIterationMeaning = void 0; do { @@ -71354,36 +72369,12 @@ var ts; } return meaning; } + Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; function isImplementation(node) { - if (!node) { - return false; - } - else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { - return true; - } - else if (node.kind === 230) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2); - } - else if (ts.isFunctionLike(node)) { - return !!node.body || ts.hasModifier(node, 2); - } - else { - switch (node.kind) { - case 233: - case 203: - case 236: - case 237: - return true; - } - } - return false; - } - function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 212) { - ts.Debug.assert(node.parent.kind === 231); - return node.parent.parent; - } + return !!(node.flags & 2097152) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); } function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { var refSymbol = checker.getSymbolAtLocation(node); @@ -71409,12 +72400,6 @@ var ts; function tryGetClassByExtendingIdentifier(node) { return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); } - function isNameOfExternalModuleImportOrDeclaration(node) { - if (node.kind === 9) { - return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node); - } - return false; - } function getParentSymbolsOfPropertyAccess(location, symbol, checker) { var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(location); if (!propertyAccessExpression) { @@ -71448,9 +72433,8 @@ var ts; return undefined; } if (ts.isJumpStatementTarget(node)) { - var labelName = node.text; - var label = ts.getTargetLabel(node.parent, labelName); - return label ? [createDefinitionInfoFromName(label, "label", labelName, undefined)] : undefined; + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfoFromName(label, "label", node.text, undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -71621,8 +72605,8 @@ var ts; return createDefinitionInfo(decl, symbolKind, symbolName, containerName); } function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; + for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { + var ref = refs_2[_i]; if (ref.pos <= pos && pos <= ref.end) { return ref; } @@ -72157,8 +73141,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -72229,7 +73213,7 @@ var ts; case 6: return "Package name '" + typing + "' contains non URI safe characters"; case 0: - throw ts.Debug.fail(); + return ts.Debug.fail(); default: ts.Debug.assertNever(result); } @@ -72244,18 +73228,18 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_8 = function (sourceFile) { + var _loop_9 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { return "continue"; } - ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { + sourceFile.getNamedDeclarations().forEach(function (declarations, name) { getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_8(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_9(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -72309,37 +73293,31 @@ var ts; return true; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - var text = ts.getTextOfIdentifierOrLiteral(name); - if (text !== undefined) { - containers.unshift(text); - } - else if (name.kind === 146) { - return tryAddComputedPropertyName(name.expression, containers, true); - } - else { - return false; - } - } + var name = ts.getNameOfDeclaration(declaration); + if (name && ts.isPropertyNameLiteral(name)) { + containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); + return true; + } + else if (name && name.kind === 146) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; } - return true; } function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (text !== undefined) { + if (ts.isPropertyNameLiteral(expression)) { + var text = ts.getTextOfIdentifierOrLiteral(expression); if (includeLastPortion) { containers.unshift(text); } return true; } - if (expression.kind === 183) { - var propertyAccess = expression; + if (ts.isPropertyAccessExpression(expression)) { if (includeLastPortion) { - containers.unshift(propertyAccess.name.text); + containers.unshift(expression.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, true); + return tryAddComputedPropertyName(expression.expression, containers, true); } return false; } @@ -72599,6 +73577,7 @@ var ts; case 1: case 2: case 3: + case 6: addNodeWithRecursiveChild(node, node.right); break; case 4: @@ -72945,39 +73924,91 @@ var ts; (function (ts) { var OrganizeImports; (function (OrganizeImports) { - function organizeImports(sourceFile, formatContext, host) { - var oldImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - if (oldImportDecls.length === 0) { - return []; - } - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { - return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); - }); - var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { - return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup)) - : importGroup; - }); + function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); - if (newImportDecls.length === 0) { - changeTracker.deleteNode(sourceFile, oldImportDecls[0]); - } - else { - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - useNonAdjustedStartPosition: false, - useNonAdjustedEndPosition: false, - suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(topLevelImportDecls); + for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { + var ambientModule = _a[_i]; + var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(ambientModuleImportDecls); } return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls) { + if (ts.length(oldImportDecls) === 0) { + return; + } + ts.suppressLeadingTrivia(oldImportDecls[0]); + var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); + var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { + return getExternalModuleName(importGroup[0].moduleSpecifier) + ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + : importGroup; + }); + if (newImportDecls.length === 0) { + changeTracker.deleteNode(sourceFile, oldImportDecls[0], { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + }); + } + else { + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), + }); + } + for (var i = 1; i < oldImportDecls.length; i++) { + changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + } + } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports) { - return oldImports; + function getModuleBlock(moduleDecl) { + var body = moduleDecl.body; + return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + } + function removeUnusedImports(oldImports, sourceFile, program) { + var typeChecker = program.getTypeChecker(); + var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxContext = sourceFile.languageVariant === 1 && program.getCompilerOptions().jsx; + var usedImports = []; + for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { + var importDecl = oldImports_1[_i]; + var importClause = importDecl.importClause; + if (!importClause) { + usedImports.push(importDecl); + continue; + } + var name = importClause.name, namedBindings = importClause.namedBindings; + if (name && !isDeclarationUsed(name)) { + name = undefined; + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + if (!isDeclarationUsed(namedBindings.name)) { + namedBindings = undefined; + } + } + else { + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); + if (newElements.length < namedBindings.elements.length) { + namedBindings = newElements.length + ? ts.updateNamedImports(namedBindings, newElements) + : undefined; + } + } + } + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + } } function getExternalModuleName(specifier) { return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier) @@ -72988,20 +74019,22 @@ var ts; if (importGroup.length === 0) { return importGroup; } - var _a = getImportParts(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; + var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; var coalescedImports = []; if (importWithoutClause) { coalescedImports.push(importWithoutClause); } if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { - var defaultImportClause = defaultImports[0].parent; - coalescedImports.push(updateImportDeclarationAndClause(defaultImportClause, defaultImportClause.name, namespaceImports[0])); + var defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); return coalescedImports; } - var sortedNamespaceImports = ts.stableSort(namespaceImports, function (n1, n2) { return compareIdentifiers(n1.name, n2.name); }); + var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { + return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); + }); for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { var namespaceImport = sortedNamespaceImports_1[_i]; - coalescedImports.push(updateImportDeclarationAndClause(namespaceImport.parent, undefined, namespaceImport)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, undefined, namespaceImport.importClause.namedBindings)); } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -73009,30 +74042,30 @@ var ts; var newDefaultImport; var newImportSpecifiers = []; if (defaultImports.length === 1) { - newDefaultImport = defaultImports[0]; + newDefaultImport = defaultImports[0].importClause.name; } else { for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { var defaultImport = defaultImports_1[_b]; - newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (n) { return n.elements; })); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || compareIdentifiers(s1.name, s2.name); }); - var importClause = defaultImports.length > 0 - ? defaultImports[0].parent - : namedImports[0].parent; + var importDecl = defaultImports.length > 0 + ? defaultImports[0] + : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 ? undefined : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0], sortedImportSpecifiers); - coalescedImports.push(updateImportDeclarationAndClause(importClause, newDefaultImport, newNamedImports)); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; - function getImportParts(importGroup) { + function getCategorizedImports(importGroup) { var importWithoutClause; var defaultImports = []; var namespaceImports = []; @@ -73045,14 +74078,14 @@ var ts; } var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; if (name) { - defaultImports.push(name); + defaultImports.push(importDeclaration); } if (namedBindings) { if (ts.isNamespaceImport(namedBindings)) { - namespaceImports.push(namedBindings); + namespaceImports.push(importDeclaration); } else { - namedImports.push(namedBindings); + namedImports.push(importDeclaration); } } } @@ -73066,12 +74099,11 @@ var ts; function compareIdentifiers(s1, s2) { return ts.compareStringsCaseSensitive(s1.text, s2.text); } - function updateImportDeclarationAndClause(importClause, name, namedBindings) { - var importDeclaration = importClause.parent; - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, name, namedBindings), importDeclaration.moduleSpecifier); - } } OrganizeImports.coalesceImports = coalesceImports; + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + } function compareModuleSpecifiers(m1, m2) { var name1 = getExternalModuleName(m1); var name2 = getExternalModuleName(m2); @@ -73117,13 +74149,13 @@ var ts; 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+(.*))?$/); + var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/); 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, false, result[2] || "#region")); + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, span, false, result[2] || "#region")); } else { var region = regions.pop(); @@ -73319,9 +74351,9 @@ var ts; if (index > 0) { var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - 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)); + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, true)) { + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span, chunk.text, false)); } } } @@ -73370,7 +74402,7 @@ var ts; } } var subWordTextChunks = segment.subWordTextChunks; - var matches = undefined; + var matches; for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { var subWordTextChunk = subWordTextChunks_1[_i]; var result = matchTextChunk(candidate, subWordTextChunk, true); @@ -73412,8 +74444,8 @@ var ts; var chunkCharacterSpans = chunk.characterSpans; var currentCandidate = 0; var currentChunkSpan = 0; - var firstMatch = undefined; - var contiguous = undefined; + var firstMatch; + var contiguous; while (true) { if (currentChunkSpan === chunkCharacterSpans.length) { var weight = 0; @@ -73652,11 +74684,18 @@ var ts; function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { if (readImportFiles === void 0) { readImportFiles = true; } if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } - var referencedFiles = []; - var typeReferenceDirectives = []; + var pragmaContext = { + languageVersion: 1, + pragmas: undefined, + checkJsDirective: undefined, + referencedFiles: [], + typeReferenceDirectives: [], + amdDependencies: [], + hasNoDefaultLib: undefined, + moduleName: undefined + }; var importedFiles = []; var ambientExternalModules; - var isNoDefaultLib = false; var braceNesting = 0; var externalModule = false; function nextToken() { @@ -73669,23 +74708,6 @@ var ts; } return token; } - function processTripleSlashDirectives() { - var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); - ts.forEach(commentRanges, function (commentRange) { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); - if (referencePathMatchResult) { - isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; - if (fileReference) { - var collection = referencePathMatchResult.isTypeReferenceDirective - ? typeReferenceDirectives - : referencedFiles; - collection.push(fileReference); - } - } - }); - } function getFileReference() { var fileName = ts.scanner.getTokenValue(); var pos = ts.scanner.getTokenPos(); @@ -73903,7 +74925,8 @@ var ts; if (readImportFiles) { processImports(); } - processTripleSlashDirectives(); + ts.processCommentPragmas(pragmaContext, sourceText); + ts.processPragmasIntoFields(pragmaContext, ts.noop); if (externalModule) { if (ambientExternalModules) { for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { @@ -73911,7 +74934,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; } else { var ambientModuleNames = void 0; @@ -73929,7 +74952,7 @@ var ts; } } } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -73958,20 +74981,15 @@ var ts; function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { - var declarations = symbol.getDeclarations(); + var declarations = symbol.declarations; if (declarations && declarations.length > 0) { - if (ts.some(declarations, isDefinedInLibraryFile)) { + if (declarations.some(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) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 79 && symbol.parent.flags & 1536) { return undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - if (!kind) { - return undefined; - } var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; @@ -73980,12 +74998,11 @@ var ts; return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } - else if (node.kind === 9) { + else if (ts.isStringLiteral(node)) { 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(node.text, node.text, "var", "", node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -74342,10 +75359,73 @@ var ts; })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program) { + program.getSemanticDiagnostics(sourceFile); + var checker = program.getDiagnosticsProducingTypeChecker(); + var diags = []; + if (sourceFile.commonJsModuleIndicator) { + diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + } + var isJsFile = ts.isSourceFileJavaScript(sourceFile); + function check(node) { + switch (node.kind) { + case 232: + case 190: + if (isJsFile) { + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + } + break; + } + if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + node.forEachChild(check); + } + check(sourceFile); + if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); + if (!name) + continue; + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); + if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + } + } + } + return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + } + ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + function importNameForConvertToDefaultImport(node) { + switch (node.kind) { + case 242: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings.kind === 244 && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 241: + return node.name; + default: + return undefined; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { function getSymbolKind(typeChecker, symbol, location) { + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + if (result !== "") { + return result; + } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32) { return ts.getDeclarationOfKind(symbol, 203) ? @@ -74359,17 +75439,14 @@ var ts; return "interface"; if (flags & 262144) return "type parameter"; - 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 (flags & 262144) + return "type parameter"; + if (flags & 8) + return "enum member"; + if (flags & 2097152) + return "alias"; + if (flags & 1536) + return "module"; return result; } SymbolDisplay.getSymbolKind = getSymbolKind; @@ -74967,7 +76044,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_10 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -74983,7 +76060,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_10(opt); } return options; } @@ -76334,8 +77411,8 @@ var ts; } else if (tokenInfo.token.kind === listStartToken) { startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); + var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1, parent, parentDynamicIndentation, parentStartLine); + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { @@ -77167,25 +78244,13 @@ var ts; function isControlFlowEndingStatement(kind, parent) { switch (kind) { case 223: - case 227: - switch (parent.kind) { - case 211: - var grandParent = parent.parent; - switch (grandParent && grandParent.kind) { - case 232: - case 190: - return false; - default: - return true; - } - case 264: - case 265: - case 272: - case 238: - return true; - default: - throw ts.Debug.fail(); + case 227: { + if (parent.kind !== 211) { + return true; } + var grandParent = parent.parent; + return !(grandParent && grandParent.kind === 190 || grandParent.kind === 232); + } case 221: case 222: return true; @@ -77253,14 +78318,14 @@ var ts; ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; })(ChangeKind || (ChangeKind = {})); - function getSeparatorCharacter(separator) { - return ts.tokenToString(separator.kind); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - textChanges_1.getSeparatorCharacter = getSeparatorCharacter; function getAdjustedStartPosition(sourceFile, node, options, position) { if (options.useNonAdjustedStartPosition) { - return node.getStart(); + return node.getStart(sourceFile); } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); @@ -77277,7 +78342,6 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } - textChanges_1.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { return node.getEnd(); @@ -77288,7 +78352,6 @@ var ts; ? newEnd : end; } - textChanges_1.getAdjustedEndPosition = getAdjustedEndPosition; function isSeparator(node, candidate) { return candidate && node.parent && (candidate.kind === 26 || (candidate.kind === 25 && node.parent.kind === 182)); } @@ -77300,10 +78363,9 @@ var ts; return s; } var ChangeTracker = (function () { - function ChangeTracker(newLineCharacter, formatContext, validator) { + function ChangeTracker(newLineCharacter, formatContext) { this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; - this.validator = validator; this.changes = []; this.deletedNodesInLists = []; this.nodesInsertedAtClassStarts = ts.createMap(); @@ -77382,38 +78444,33 @@ var ts; return this; }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); }; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); - return this; + this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + }; + ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -77431,6 +78488,27 @@ var ts; var pos = before.getStart(sourceFile); this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, false); + var text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: { pos: pos, end: pos }, text: text }); + }; + ChangeTracker.prototype.insertTypeAnnotation = function (sourceFile, node, type) { + var end = (ts.isFunctionLike(node) + ? ts.findChildOfKind(node, 20, sourceFile) || ts.first(node.parameters) + : node.kind !== 230 && node.questionToken ? node.questionToken : node.name).end; + this.insertNodeAt(sourceFile, end, type, { prefix: ": " }); + }; + ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { + var start = (ts.findChildOfKind(node, 19, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); + }; ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { if (ts.isStatement(before) || ts.isClassElement(before)) { return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; @@ -77438,7 +78516,10 @@ var ts; else if (ts.isVariableDeclaration(before)) { return { suffix: ", " }; } - throw ts.Debug.failBadSyntaxKind(before); + else if (ts.isParameter(before)) { + return {}; + } + return ts.Debug.failBadSyntaxKind(before); }; ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { var firstStatement = ts.firstOrUndefined(ctr.body.statements); @@ -77459,7 +78540,7 @@ var ts; } }; ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { - this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, true), { useNonAdjustedEndPosition: true }); + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, true)); }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); @@ -77491,17 +78572,11 @@ var ts; after.kind === 150 || after.kind === 152) { if (sourceFile.text.charCodeAt(after.end - 1) !== 59) { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - options: {}, - range: { pos: after.end, end: after.end }, - node: ts.createToken(25) - }); + this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, { pos: endPosition, end: endPosition }, newNode, this.getInsertNodeAfterOptions(after)); + return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); }; ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { @@ -77513,7 +78588,10 @@ var ts; else if (ts.isVariableDeclaration(node)) { return { prefix: ", " }; } - throw ts.Debug.failBadSyntaxKind(node); + else if (ts.isParameter(node)) { + return {}; + } + return ts.Debug.failBadSyntaxKind(node); }; ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); @@ -77540,16 +78618,8 @@ var ts; else { startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, - node: newNode, - options: { - prefix: prefix, - suffix: "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)) - } - }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -77570,34 +78640,16 @@ var ts; multilineList = true; } if (multilineList) { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: ts.createToken(separator), - options: {} - }); + this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); 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--; } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: insertPos, end: insertPos }, - node: newNode, - options: { indentation: indentation, prefix: this.newLineCharacter } - }); + this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: newNode, - options: { prefix: ts.tokenToString(separator) + " " } - }); + this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; @@ -77609,91 +78661,75 @@ var ts; var newCls = cls.kind === 233 ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); - _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + _this.replaceNode(sourceFile, cls, newCls); }); }; - ChangeTracker.prototype.getChanges = function () { - var _this = this; + ChangeTracker.prototype.getChanges = function (validate) { this.finishInsertNodeAtClassStart(); - return ts.group(this.changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { - var sourceFile = changesInFile[0].sourceFile; - var textChanges = ChangeTracker.normalize(changesInFile).map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), _this.computeNewText(c, sourceFile)); - }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; - }); - }; - ChangeTracker.prototype.computeNewText = function (change, sourceFile) { - var _this = this; - if (change.kind === ChangeKind.Remove) { - return ""; - } - var options = change.options || {}; - var text; - var pos = change.range.pos; - var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - if (change.kind === ChangeKind.ReplaceWithMultipleNodes) { - var lastIndex_1 = change.nodes.length - 1; - var parts = change.nodes.map(function (n, index) { - var formatted = _this.getFormattedTextOfNode(n, sourceFile, pos, options); - return index === lastIndex_1 || ts.endsWith(formatted, _this.newLineCharacter) - ? formatted - : (formatted + _this.newLineCharacter); - }); - text = parts.join(""); - } - else { - ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode"); - text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options); - } - text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, ""); - return (options.prefix || "") + text + (options.suffix || ""); - }; - ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) { - var nonformattedText = getNonformattedText(node, sourceFile, this.newLineCharacter); - if (this.validator) { - this.validator(nonformattedText); - } - var formatOptions = this.formatContext.options; - var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - var initialIndentation = options.indentation !== undefined - ? options.indentation - : (options.useIndentationFromFile !== false) - ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter)) - : 0; - var delta = options.delta !== undefined - ? options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(node) - ? (formatOptions.indentSize || 0) - : 0; - 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; }); - for (var i = 0; i < normalized.length - 2; i++) { - ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos); - } - return normalized; + return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); }; return ChangeTracker; }()); textChanges_1.ChangeTracker = ChangeTracker; - function getNonformattedText(node, sourceFile, newLine) { - var writer = new Writer(newLine); - var printer = ts.createPrinter({ newLine: newLine === "\n" ? 1 : 0 }, writer); - printer.writeNode(4, node, sourceFile, writer); - return { text: writer.getText(), node: assignPositionsToNode(node) }; - } - 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, formatContext); - return applyChanges(nonFormattedText.text, changes); - } + var changesToText; + (function (changesToText) { + function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { + return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + var sourceFile = changesInFile[0].sourceFile; + var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); + var _loop_11 = function (i) { + ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { + return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + }); + }; + for (var i = 0; i < normalized.length - 1; i++) { + _loop_11(i); + } + var textChanges = normalized.map(function (c) { + return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + }); + return { fileName: sourceFile.fileName, textChanges: textChanges }; + }); + } + changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + if (change.kind === ChangeKind.Remove) { + return ""; + } + if (change.kind === ChangeKind.Text) { + return change.text; + } + var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; + var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; + var text = change.kind === ChangeKind.ReplaceWithMultipleNodes + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter) + : format(change.node); + var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + return (options.prefix || "") + noIndent + (options.suffix || ""); + } + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; + if (validate) + validate(node, text); + var formatOptions = formatContext.options; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn) ? (formatOptions.indentSize || 0) : 0; + } + var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; + var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); + return applyChanges(text, changes); + } + function getNonformattedText(node, sourceFile, newLineCharacter) { + var writer = new Writer(newLineCharacter); + var newLine = newLineCharacter === "\n" ? 1 : 0; + ts.createPrinter({ newLine: newLine }, writer).writeNode(4, node, sourceFile, writer); + return { text: writer.getText(), node: assignPositionsToNode(node) }; + } + })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; @@ -77858,7 +78894,7 @@ var ts; var ranges = ts.getLeadingCommentRanges(text, position); if (!ranges) return position; - if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0])) { + if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0].pos)) { position = ranges[0].end; advancePastLineBreak(); ranges = ranges.slice(1); @@ -77885,6 +78921,10 @@ var ts; } } } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + } + textChanges_1.isValidLocationToAddComment = isValidLocationToAddComment; })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); var ts; @@ -77893,6 +78933,22 @@ var ts; (function (codefix) { var codeFixRegistrations = []; var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(changes, description) { + return createCodeFixActionWorker(diagnosticToString(description), changes, undefined, undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(description, changes, fixId, fixAllDescription, command) { + return { description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } function registerCodeFix(reg) { for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { var error = _a[_i]; @@ -77955,16 +79011,9 @@ var ts; return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; - function codeFixAllWithTextChanges(context, errorCodes, use) { - var changes = []; - eachDiagnostic(context, errorCodes, function (diag) { return use(changes, diag); }); - changes.sort(function (a, b) { return b.span.start - a.span.start; }); - return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); - } - codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges; function eachDiagnostic(_a, errorCodes, cb) { var program = _a.program, sourceFile = _a.sourceFile; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) { + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) { var diag = _b[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); @@ -78009,7 +79058,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, @@ -78024,6 +79073,708 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "annotateWithTypeFromJSDoc"; + var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var decl = getDeclaration(diag.file, diag.start); + if (decl) + doChange(changes, diag.file, decl); + }); }, + }); + function getDeclaration(file, pos) { + var name = ts.getTokenAtPosition(file, pos, false); + return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc; + function hasUsableJSDoc(decl) { + return ts.isFunctionLikeDeclaration(decl) + ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)) + : !decl.type && !!ts.getJSDocType(decl); + } + function doChange(changes, sourceFile, decl) { + if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { + if (!decl.typeParameters) { + var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); + if (typeParameters) + changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19)); + for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (!param.type) { + var paramType = ts.getJSDocType(param); + if (paramType) + changes.insertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20)); + if (!decl.type) { + var returnType = ts.getJSDocReturnType(decl); + if (returnType) + changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + } + } + else { + var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); + ts.Debug.assert(!decl.type); + changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + } + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 230 || + node.kind === 150 || + node.kind === 151; + } + function transformJSDocType(node) { + switch (node.kind) { + case 275: + case 276: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 279: + return transformJSDocOptionalType(node); + case 278: + return transformJSDocType(node.type); + case 277: + return transformJSDocNullableType(node); + case 281: + return transformJSDocVariadicType(node); + case 280: + return transformJSDocFunctionType(node); + case 161: + 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) { + return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 281 && 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 === 134 ? "n" : "s", undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 ? "number" : "string", []), undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(undefined, undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1); + return indexSignature; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertFunctionToEs6Class"; + var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, + }); + function doChange(changes, sourceFile, position, checker) { + var deletedNodes = []; + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, false)); + if (!ctorSymbol || !(ctorSymbol.flags & (16 | 3))) { + return undefined; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 232: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 230: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return undefined; + } + copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); + for (var _i = 0, deletedNodes_1 = deletedNodes; _i < deletedNodes_1.length; _i++) { + var _a = deletedNodes_1[_i], node = _a.node, inList = _a.inList; + if (inList) { + changes.deleteNodeInList(sourceFile, node); + } + else { + changes.deleteNode(sourceFile, node); + } + } + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + if (!deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n.node); })) { + deletedNodes.push({ node: node, inList: inList }); + } + } + function createClassElementsFromSymbol(symbol) { + var memberElements = []; + if (symbol.members) { + symbol.members.forEach(function (member) { + var memberElement = createClassElement(member, undefined); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + if (symbol.exports) { + symbol.exports.forEach(function (member) { + var memberElement = createClassElement(member, [ts.createToken(115)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + return memberElements; + function shouldConvertDeclaration(_target, source) { + return ts.isFunctionLike(source); + } + function createClassElement(symbol, modifiers) { + if (!(symbol.flags & 4)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + return; + } + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 214 + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 190: { + var functionExpression = assignmentBinaryExpression.right; + 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, sourceFile); + return method; + } + case 191: { + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + if (arrowFunctionBody.kind === 211) { + bodyBlock = arrowFunctionBody; + } + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + } + 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, sourceFile); + return method; + } + default: { + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + return prop; + } + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 190) { + return undefined; + } + if (node.name.kind !== 71) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); + } + var modifiers = getModifierKindFromSource(precedingNode, 84); + var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements); + return cls; + } + function createClassFromFunctionDeclaration(node) { + var memberElements = createClassElementsFromSymbol(ctorSymbol); + if (node.body) { + memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + } + var modifiers = getModifierKindFromSource(node, 84); + var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements); + return cls; + } + } + function copyComments(sourceNode, targetNode, sourceFile) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3) { + pos += 2; + end -= 2; + } + else { + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, sourceFile, changes); + } + } + }); + return [codefix.createCodeFixActionNoFixId(changes, ts.Diagnostics.Convert_to_ES6_module)]; + }, + }); + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 241: + changes.replaceNode(importingFile, importNode, makeImport(importNode.name, undefined, moduleSpecifier)); + break; + case 185: + if (ts.isRequireCall(importNode, false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); + } + break; + } + } + } + function convertFileToEs6Module(sourceFile, checker, changes, target) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 67216319, true))) { + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 212: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 214: { + var expression = statement.expression; + switch (expression.kind) { + case 185: { + if (ts.isRequireCall(expression, true)) { + changes.replaceNode(sourceFile, statement, makeImport(undefined, undefined, expression.arguments[0])); + } + return false; + } + case 198: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + } + else { + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 178: + case 179: { + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71: + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 155: + case 156: + case 269: + case 270: + return undefined; + case 268: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); + case 153: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84)], prop); + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + var newNodes = [ + makeConst(undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right)); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84), ts.createToken(79)]; + switch (exported.kind) { + case 190: + case 191: { + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 203: { + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 185: + if (ts.isRequireCall(exported, true)) { + return convertReExportAll(exported.arguments[0], checker); + } + default: + return [[ts.createExportAssignment(undefined, undefined, false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84)]; + switch (exported.kind) { + case 190: { + var expressionName = exported.name; + if (expressionName && expressionName.text !== name) { + return exportConst(); + } + } + case 191: + return functionExpressionToDeclaration(name, modifiers, exported); + case 203: + return classExpressionToDeclaration(name, modifiers, exported); + default: + return exportConst(); + } + function exportConst() { + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 178: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(undefined, importSpecifiers, moduleSpecifier)]; + } + } + case 179: { + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier), + makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + var namedBindingsNames = ts.createMap(); + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 183: + return parent.name !== node; + case 180: + return parent.propertyName !== node; + default: + return true; + } + } + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier) + : makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + return makeImportDeclaration(name, namedImports, moduleSpecifier); + } + function makeImportDeclaration(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(undefined, undefined, importClause, moduleSpecifier); + } + codefix.makeImportDeclaration = makeImportDeclaration; + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, undefined, init)], 2)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration(undefined, undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -78036,8 +79787,8 @@ var ts; if (!qualifiedName) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); - return [{ description: description, changes: changes, fixId: fixId }]; + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -78073,11 +79824,8 @@ var ts; var classDeclaration = getClass(sourceFile, span.start); var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - return { description: description, changes: changes, fixId: fixId }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, fixIds: [fixId], @@ -78088,29 +79836,27 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); }, }); function getClass(sourceFile, pos) { - var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, false)); - ts.Debug.assert(!!classDeclaration); - return classDeclaration; + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, false))); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { var implementedType = checker.getTypeAtLocation(implementedTypeNode); var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8); }); var classType = checker.getTypeAtLocation(classDeclaration); - if (!checker.getIndexTypeOfType(classType, 1)) { + if (!classType.getNumberIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 1); } - if (!checker.getIndexTypeOfType(classType, 0)) { + if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { @@ -78136,7 +79882,7 @@ var ts; if (!info) return undefined; var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs ? ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); @@ -78146,7 +79892,7 @@ var ts; getAllCodeActions: function (context) { var seenNames = ts.createMap(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var program = context.program; + var program = context.program, preferences = context.preferences; var info = getInfo(diag.file, diag.start, program.getTypeChecker()); if (!info) return; @@ -78155,7 +79901,7 @@ var ts; return; } if (call) { - addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, preferences); } else { if (inJs) { @@ -78209,10 +79955,8 @@ var ts; } function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); - return { description: description, changes: changes, fixId: fixId }; + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { @@ -78251,9 +79995,8 @@ var ts; return typeNode || ts.createKeywordTypeNode(119); } function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); - return { description: description, changes: changes, fixId: fixId }; + return codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); @@ -78264,15 +80007,14 @@ var ts; var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); - return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); - return { description: description, changes: changes, fixId: fixId }; + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic, preferences); changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -78295,8 +80037,7 @@ var ts; return undefined; var node = info.node, suggestion = info.suggestion; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); - return [{ description: description, changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -78330,10 +80071,10 @@ var ts; flags |= 1920; } if (meaning & 2) { - flags |= 793064; + flags |= 67901928; } if (meaning & 1) { - flags |= 107455; + flags |= 67216319; } return flags; } @@ -78348,36 +80089,27 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); - return codeAction && [__assign({ fixId: fixId }, codeAction)]; + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = getTypesPackageNameToInstall(host, sourceFile, start); + return packageName === undefined ? [] + : [codefix.createCodeFixAction([], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start); if (pkg) { commands.push(getCommand(diag.file.fileName, pkg)); } }); }, }); - function getModuleName(sourceFile, pos) { - return ts.cast(ts.getTokenAtPosition(sourceFile, pos, false), ts.isStringLiteral).text; - } function getCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, moduleName) { + function getTypesPackageNameToInstall(host, sourceFile, pos) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos, false), ts.isStringLiteral).text; var packageName = ts.getPackageName(moduleName).packageName; return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; } - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { - var packageName = getTypesPackageNameToInstall(host, moduleName); - return packageName === undefined ? undefined : { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), - changes: [], - commands: [getCommand(fileName, packageName)], - }; - } - codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -78394,26 +80126,30 @@ var ts; getCodeActions: function (context) { var program = context.program, sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); }); - return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes); - }); }, + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + } + }); + }, }); function getClass(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos, false); - var classDeclaration = token.parent; - ts.Debug.assert(ts.isClassLike(classDeclaration)); - return classDeclaration; + return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); @@ -78436,7 +80172,7 @@ var ts; return undefined; var constructor = nodes.constructor, superCall = nodes.superCall; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -78486,7 +80222,7 @@ var ts; var sourceFile = context.sourceFile, span = context.span; var ctr = getNode(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -78519,7 +80255,7 @@ var ts; return undefined; var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -78535,7 +80271,7 @@ var ts; return extendsToken.kind === 85 ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(108)); if (heritageClauses.length === 2 && heritageClauses[0].token === 85 && heritageClauses[1].token === 108) { @@ -78567,7 +80303,7 @@ var ts; return undefined; } var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_this_to_unresolved_variable, fixId, ts.Diagnostics.Add_this_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -78583,7 +80319,7 @@ var ts; return; } ts.suppressLeadingAndTrailingTrivia(token); - changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -78596,29 +80332,33 @@ var ts; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = getToken(sourceFile, context.span.start); + var errorCode = context.errorCode, sourceFile = context.sourceFile; + var importDecl = tryGetFullImport(sourceFile, context.span.start); + if (importDecl) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } + var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); if (deletion.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); - result.push({ description: description, changes: deletion, fixId: fixIdDelete }); + result.push(codefix.createCodeFixAction(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } - var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, context.errorCode, sourceFile, token); }); + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); - result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + result.push(codefix.createCodeFixAction(prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); } return result; }, fixIds: [fixIdPrefix, fixIdDelete], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var sourceFile = context.sourceFile; - var token = getToken(diag.file, diag.start); + var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); switch (context.fixId) { case fixIdPrefix: if (ts.isIdentifier(token) && canPrefix(token)) { @@ -78626,16 +80366,26 @@ var ts; } break; case fixIdDelete: - tryDeleteDeclaration(changes, sourceFile, token); + var importDecl = tryGetFullImport(diag.file, diag.start); + if (importDecl) { + changes.deleteNode(sourceFile, importDecl); + } + else { + tryDeleteDeclaration(changes, sourceFile, token); + } break; default: ts.Debug.fail(JSON.stringify(context.fixId)); } }); }, }); + function tryGetFullImport(sourceFile, pos) { + var startToken = ts.getTokenAtPosition(sourceFile, pos, false); + return startToken.kind === 91 ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; + } function getToken(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, false); - return token.kind === 21 ? ts.getTokenAtPosition(sourceFile, pos + 1, false) : token; + var token = ts.findPrecedingToken(pos, sourceFile); + return token.kind === 22 ? ts.findPrecedingToken(pos - 1, sourceFile) : token; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { @@ -78699,10 +80449,13 @@ var ts; break; case 148: var oldFunction = parent.parent; + if (ts.isSetAccessor(oldFunction)) { + break; + } if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction, ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, oldFunction, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); @@ -78809,45 +80562,38 @@ var ts; return undefined; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); - var actions = [fix(type, fixIdPlain)]; + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; if (typeNode.kind === 277) { - actions.push(fix(checker.getNullableType(type, 4096), fixIdNullable)); + actions.push(fix(checker.getNullableType(type, 4096), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; - function fix(type, fixId) { - var newText = typeString(type, checker); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], - fixId: fixId, - }; + function fix(type, fixId, fixAllDescription) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], getAllCodeActions: function (context) { var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; var checker = program.getTypeChecker(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + return codefix.codeFixAll(context, errorCodes, function (changes, err) { var info = getInfo(err.file, err.start, checker); if (!info) return; var typeNode = info.typeNode, type = info.type; var fixedType = typeNode.kind === 277 && fixId === fixIdNullable ? checker.getNullableType(type, 4096) : type; - changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + doChange(changes, sourceFile, typeNode, fixedType, checker); }); } }); + function doChange(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, oldTypeNode)); + } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, false), isTypeContainer); var typeNode = decl && decl.type; return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; } - function createChange(declaration, sourceFile, newText) { - return ts.createTextChange(ts.createTextSpanFromNode(declaration, sourceFile), newText); - } - function typeString(type, checker) { - return checker.typeToString(type, undefined, 1); - } function isTypeContainer(node) { switch (node.kind) { case 206: @@ -78890,7 +80636,7 @@ var ts; if (!nodes) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -78913,6 +80659,9 @@ var ts; function getNodes(sourceFile, start) { var token = ts.getTokenAtPosition(sourceFile, start, false); var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } var insertBefore; switch (containingFunction.kind) { case 153: @@ -78962,8 +80711,7 @@ var ts; getAllCodeActions: ts.notImplemented, }); function createCodeAction(descriptionDiagnostic, diagnosticArgs, changes) { - var description = ts.formatMessage.apply(undefined, [undefined, descriptionDiagnostic].concat(diagnosticArgs)); - return { description: description, changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(changes, [descriptionDiagnostic].concat(diagnosticArgs)); } function convertToImportCodeFixContext(context, symbolToken, symbolName) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; @@ -78979,7 +80727,8 @@ var ts; cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolName, - symbolToken: symbolToken + symbolToken: symbolToken, + preferences: context.preferences, }; } var ImportKind; @@ -78989,11 +80738,11 @@ var ts; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken) { + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken, preferences) { var exportInfos = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host)).moduleSpecifier; - var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken }; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } codefix.getImportCompletionAction = getImportCompletionAction; @@ -79042,33 +80791,20 @@ var ts; var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); var cached = cachedImportDeclarations[moduleSymbolId]; if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { - var declaration = checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; - return declaration && { declaration: declaration, importKind: importKind }; + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 242 || i.kind === 241) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } return cached; } - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 242: - return parent; - case 252: - return parent.parent; - case 248: - case 185: - return undefined; - default: - ts.Debug.fail(); - } - } function getCodeActionForNewImport(context, _a) { var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; - var sourceFile = context.sourceFile, symbolName = context.symbolName; + var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); + var quotedModuleSpecifier = ts.createLiteral(moduleSpecifierWithoutQuotes, shouldUseSingleQuote(sourceFile, preferences)); var importDecl = importKind !== 3 ? ts.createImportDeclaration(undefined, undefined, createImportClauseOfKind(importKind, symbolName), quotedModuleSpecifier) : ts.createImportEqualsDeclaration(undefined, undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); @@ -79082,11 +80818,14 @@ var ts; }); return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } - 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 shouldUseSingleQuote(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single"; + } + else { + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + } } function usesJsExtensionOnImports(sourceFile) { return ts.firstDefined(sourceFile.imports, function (_a) { @@ -79107,35 +80846,40 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { - var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; + function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var addJsExtension = usesJsExtensionOnImports(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); if (global) { return [global]; } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); - if (!baseUrl) { + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), compilerOptions, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { return [relativePath]; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { return [relativePath]; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, compilerOptions, addJsExtension); if (paths) { var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); if (fromPaths) { return [fromPaths]; } } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); if (isPathRelativeToParent(relativeToBaseUrl)) { return [relativePath]; } @@ -79345,7 +81089,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); return newImportInfos.map(function (info) { return getCodeActionForNewImport(ctx, info); }); } function newImportInfoFromExistingSpecifier(_a) { @@ -79411,7 +81155,7 @@ var ts; var parent = token.parent; var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent); if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258) { - umdSymbol = checker.resolveName(checker.getJsxNamespace(), isNodeOpeningLikeElement ? parent.tagName : parent, 107455, false); + umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319, false); } } if (ts.isUMDExportSymbol(umdSymbol)) { @@ -79438,34 +81182,34 @@ var ts; case ts.ModuleKind.None: return 2; default: - throw ts.Debug.assertNever(moduleKind); + return ts.Debug.assertNever(moduleKind); } } function getActionsForNonUMDImport(context) { var sourceFile = context.sourceFile, span = context.span, program = context.program, cancellationToken = context.cancellationToken; var checker = program.getTypeChecker(); var symbolToken = ts.getTokenAtPosition(sourceFile, span.start, false); - var isJsxNamespace = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken; - if (!isJsxNamespace && !ts.isIdentifier(symbolToken)) { + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863, false)) + ? checker.getJsxNamespace() + : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; + if (!symbolName) return undefined; - } - var symbolName = isJsxNamespace ? checker.getJsxNamespace() : symbolToken.text; - var allSourceFiles = program.getSourceFiles(); - var compilerOptions = program.getCompilerOptions(); ts.Debug.assert(symbolName !== "default"); var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); } - forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if ((localSymbol && localSymbol.escapedName === symbolName || getEscapedNameForExportDefault(defaultExport) === symbolName || - moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { addSymbol(moduleSymbol, localSymbol || defaultExport, 1); } } @@ -79520,21 +81264,22 @@ var ts; return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { - return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); } codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); var res = ""; var lastCharWasValid = true; - var firstCharCode = moduleSpecifier.charCodeAt(0); + var firstCharCode = baseName.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); + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); var isValid = ts.isIdentifierPart(ch, target); if (isValid) { var char = String.fromCharCode(ch); @@ -79562,49 +81307,37 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, span = context.span; + var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } - var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter).change])], - fixId: fixId, - }, - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [ - ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), - ])], - fixId: undefined, - }]; + var fixes = [ + codefix.createCodeFixActionNoFixId([codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), + ]; + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); + } + return fixes; }, fixIds: [fixId], getAllCodeActions: function (context) { var seenLines = ts.createMap(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { - if (err.start !== undefined) { - var _a = getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options)), lineNumber = _a.lineNumber, change = _a.change; - if (ts.addToSeen(seenLines, lineNumber)) { - changes.push(change); - } + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { + makeChange(changes, diag.file, diag.start, seenLines); } }); }, }); - function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) { + function makeChange(changes, sourceFile, position, seenLines) { var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; - var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); - var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); - if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition, false); - var tokenLeadingComments = ts.getLeadingCommentRangesOfNode(token, sourceFile); - if (!tokenLeadingComments || !tokenLeadingComments.length || tokenLeadingComments[0].pos >= startPosition) { - return { lineNumber: lineNumber, change: ts.createTextChangeFromStartLength(startPosition, 0, "// @ts-ignore" + newLineCharacter) }; - } + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } - return { lineNumber: lineNumber, change: ts.createTextChangeFromStartLength(position, 0, (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter) }; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -79612,17 +81345,17 @@ var ts; (function (ts) { var codefix; (function (codefix) { - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); } } } codefix.createMissingMemberNodes = createMissingMemberNodes; - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -79650,7 +81383,7 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { @@ -79659,11 +81392,11 @@ var ts; } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); } else { ts.Debug.assert(declarations.length === signatures.length); - out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); } break; } @@ -79688,11 +81421,11 @@ var ts; function getSynthesizedDeepClones(nodes) { return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); } - function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { + function createMethodFromCallExpression(_a, methodName, inJs, makeStatic, preferences) { var typeArguments = _a.typeArguments, args = _a.arguments; return ts.createMethod(undefined, makeStatic ? [ts.createToken(115)] : undefined, undefined, methodName, undefined, inJs ? undefined : ts.map(typeArguments, function (_, i) { return ts.createTypeParameterDeclaration(84 + typeArguments.length - 1 <= 90 ? String.fromCharCode(84 + i) : "T" + i); - }), createDummyParameters(args.length, undefined, undefined, inJs), inJs ? undefined : ts.createKeywordTypeNode(119), createStubbedMethodBody()); + }), createDummyParameters(args.length, undefined, undefined, inJs), inJs ? undefined : ts.createKeywordTypeNode(119), createStubbedMethodBody(preferences)); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, minArgumentCount, inJs) { @@ -79703,7 +81436,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers) { + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; @@ -79725,13 +81458,13 @@ var ts; var restParameter = ts.createParameter(undefined, undefined, ts.createToken(24), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", maxNonRestArgs >= minArgumentCount ? ts.createToken(55) : undefined, anyArrayType, undefined); parameters.push(restParameter); } - return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined); + return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined, preferences); } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { + return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } - function createStubbedMethodBody() { - return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), undefined, [ts.createLiteral("Method not implemented.")]))], true); + function createStubbedMethodBody(preferences) { + return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), undefined, [ts.createLiteral("Method not implemented.", preferences.quotePreference === "single")]))], true); } function createVisibilityModifier(flags) { if (flags & 4) { @@ -79761,28 +81494,23 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (_a) { - var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; if (ts.isSourceFileJavaScript(sourceFile)) { return undefined; } var token = ts.getTokenAtPosition(sourceFile, start, false); - var fix = getFix(sourceFile, token, errorCode, program, cancellationToken); - if (!fix) - return undefined; - var declaration = fix.declaration, textChanges = fix.textChanges; - var name = ts.getNameOfDeclaration(declaration); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); - return [{ description: description, changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }], fixId: fixId }]; + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); + return changes.length === 0 ? undefined + : [codefix.createCodeFixAction(changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; var seenFunctions = ts.createMap(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { - var fix = getFix(sourceFile, ts.getTokenAtPosition(err.file, err.start, false), err.code, program, cancellationToken, seenFunctions); - if (fix) - changes.push.apply(changes, fix.textChanges); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, false), err.code, program, cancellationToken, seenFunctions); }); }, }); @@ -79796,17 +81524,25 @@ var ts; return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function getFix(sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { - if (!isAllowedTokenKind(token.kind)) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 && token.kind !== 24) { return undefined; } + var parent = token.parent; 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, program, cancellationToken); + if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { + annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + return parent; + } + return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, program, cancellationToken); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + return symbol.valueDeclaration; + } } } var containingFunction = ts.getContainingFunction(token); @@ -79816,40 +81552,38 @@ var ts; switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction, program, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + return containingFunction; } case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return !seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction)) - ? getCodeActionForParameters(ts.cast(token.parent, ts.isParameter), containingFunction, sourceFile, program, cancellationToken) - : undefined; + if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + return param; + } + return undefined; 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, sourceFile, program, cancellationToken) : undefined; + if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + return containingFunction; + } + return 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, program, cancellationToken) : undefined; + if (ts.isSetAccessor(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + return containingFunction; + } + return undefined; default: - throw ts.Debug.fail(String(errorCode)); + return ts.Debug.fail(String(errorCode)); } } - function isAllowedTokenKind(kind) { - switch (kind) { - case 71: - case 24: - case 114: - case 112: - case 113: - case 132: - return true; - default: - return false; + function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); } } - function getCodeActionForVariableDeclaration(declaration, program, cancellationToken) { - if (!ts.isIdentifier(declaration.name)) - return undefined; - var type = inferTypeForVariableFromUsage(declaration.name, program, cancellationToken); - return makeFix(declaration, declaration.name.getEnd(), type, program); - } function isApplicableFunctionForInference(declaration) { switch (declaration.kind) { case 232: @@ -79861,46 +81595,46 @@ var ts; } return false; } - function getCodeActionForParameters(parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; + return; } var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - if (!types) - return undefined; - if (containingFunction.parameters.length !== types.length) { - return undefined; + if (!types || containingFunction.parameters.length !== types.length) { + return; } - var textChanges = ts.arrayFrom(ts.mapDefinedIterator(ts.zipToIterator(containingFunction.parameters, types), function (_a) { - var parameter = _a[0], type = _a[1]; - return type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined; - })); - return textChanges.length ? { declaration: parameterDeclaration, textChanges: textChanges } : undefined; + ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (!parameter.type && !parameter.initializer) { + annotate(changes, sourceFile, parameter, type, program); + } + }); } - function getCodeActionForSetAccessor(setAccessorDeclaration, program, cancellationToken) { - var setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { - return undefined; + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || + inferTypeForVariableFromUsage(param.name, program, cancellationToken); + annotate(changes, sourceFile, param, type, program); } - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(setAccessorParameter.name, program, cancellationToken); - return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); } - function getCodeActionForGetAccessor(getAccessorDeclaration, sourceFile, program, cancellationToken) { - if (!ts.isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, program, cancellationToken); - var closeParenToken = ts.findChildOfKind(getAccessorDeclaration, 20, sourceFile); - return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + function annotate(changes, sourceFile, declaration, type, program) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); + if (typeNode) + changes.insertTypeAnnotation(sourceFile, declaration, typeNode); } - function makeFix(declaration, start, type, program) { - return type && { declaration: declaration, textChanges: [makeChange(declaration, start, type, program)] }; - } - function makeChange(declaration, start, type, program) { - var typeString = type && typeToString(type, declaration, program.getTypeChecker()); - return typeString === undefined ? undefined : ts.createTextChangeFromStartLength(start, 0, ": " + typeString); + function getTypeNodeIfAccessible(type, enclosingScope, checker) { + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, undefined, { + trackSymbol: function (symbol, declaration, meaning) { + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, false).accessibility === 0; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + }); + return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { @@ -79925,48 +81659,6 @@ var ts; } } } - function getTypeAccessiblityWriter(checker) { - var str = ""; - var typeIsAccessible = true; - var writeText = function (text) { return str += text; }; - return { - getText: function () { return typeIsAccessible ? str : undefined; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - write: writeText, - writeTextOfNode: writeText, - rawWrite: writeText, - writeLiteral: writeText, - getTextPos: function () { return 0; }, - getLine: function () { return 0; }, - getColumn: function () { return 0; }, - getIndent: function () { return 0; }, - isAtStartOfLine: function () { return false; }, - writeLine: function () { return writeText(" "); }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { str = ""; typeIsAccessible = true; }, - trackSymbol: function (symbol, declaration, meaning) { - if (checker.isSymbolAccessible(symbol, declaration, meaning, false).accessibility !== 0) { - typeIsAccessible = false; - } - }, - reportInaccessibleThisError: function () { typeIsAccessible = false; }, - reportPrivateInBaseOfClassExpression: function () { typeIsAccessible = false; }, - reportInaccessibleUniqueSymbolError: function () { typeIsAccessible = false; } - }; - } - function typeToString(type, enclosingDeclaration, checker) { - var writer = getTypeAccessiblityWriter(checker); - checker.writeType(type, enclosingDeclaration, undefined, writer); - return writer.getText(); - } var InferFromReference; (function (InferFromReference) { function inferTypeFromReferences(references, checker, cancellationToken) { @@ -79996,13 +81688,13 @@ var ts; var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; - var isRestParameter = ts.isRestParameter(parameter); + var isRest = ts.isRestParameter(parameter); for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { continue; } - if (isRestParameter) { + if (isRest) { for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); } @@ -80015,7 +81707,7 @@ var ts; return undefined; } var type = checker.getWidenedType(checker.getUnionType(types, 2)); - return isRestParameter ? checker.createArrayType(type) : type; + return isRest ? checker.createArrayType(type) : type; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -80319,18 +82011,15 @@ var ts; var namespace = ts.getNamespaceDeclarationNode(node); var opts = context.program.getCompilerOptions(); var variations = []; - variations.push(createAction(context, sourceFile, node, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(namespace.name, undefined), node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, undefined, node.moduleSpecifier))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(undefined, undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); } return variations; } function createAction(context, sourceFile, node, replacement) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceRange(sourceFile, { pos: node.getStart(), end: node.end }, replacement); }); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), - changes: changes, - }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -80356,881 +82045,164 @@ var ts; if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } - fixes.push({ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), - changes: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }), - }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(changes, ts.Diagnostics.Use_synthetic_default_member)); return fixes; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { - var refactor; - (function (refactor) { - var annotateWithTypeFromJSDoc; - (function (annotateWithTypeFromJSDoc) { - var refactorName = "Annotate with type from JSDoc"; - var actionName = "annotate"; - var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (ts.isInJavaScriptFile(context.file)) { - return undefined; - } - var node = ts.getTokenAtPosition(context.file, context.startPosition, false); - if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { - return [{ - name: refactorName, - description: description, - actions: [ - { - description: 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 === 148) { - 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.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions); - 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.replaceNode(sourceFile, decl, functionWithType, ts.textChanges.useNonAdjustedPositions); - return { - edits: changeTracker.getChanges(), - renameFilename: undefined, - renameLocation: undefined - }; - } - function isDeclarationWithType(node) { - return ts.isFunctionLikeDeclaration(node) || - node.kind === 230 || - node.kind === 148 || - node.kind === 150 || - node.kind === 151; - } - 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 232: - return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); - case 154: - return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); - case 190: - return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); - case 191: - return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); - case 153: - return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body); - case 155: - return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body); - case 156: - 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 230: - return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer); - case 150: - return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); - case 151: - 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 275: - case 276: - return ts.createTypeReferenceNode("any", ts.emptyArray); - case 279: - return transformJSDocOptionalType(node); - case 278: - return transformJSDocType(node.type); - case 277: - return transformJSDocNullableType(node); - case 281: - return transformJSDocVariadicType(node); - case 280: - return transformJSDocFunctionType(node); - case 148: - return transformJSDocParameter(node); - case 161: - 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 === 281 && 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 === 134 ? "n" : "s", undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 ? "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) { - var convertFunctionToES6Class; - (function (convertFunctionToES6Class) { - var refactorName = "Convert to ES2015 class"; - var actionName = "convert"; - var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (!ts.isInJavaScriptFile(context.file)) { - return undefined; - } - var symbol = getConstructorSymbol(context); - if (!symbol) { - return undefined; - } - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = symbol.valueDeclaration.initializer.symbol; - } - if ((symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { - return [ - { - name: refactorName, - description: description, - actions: [ - { - description: description, - name: actionName - } - ] - } - ]; - } - } - function getEditsForAction(context, action) { - if (actionName !== action) { - return undefined; - } - var sourceFile = context.file; - var ctorSymbol = getConstructorSymbol(context); - var deletedNodes = []; - var deletes = []; - if (!(ctorSymbol.flags & (16 | 3))) { - return undefined; - } - var ctorDeclaration = ctorSymbol.valueDeclaration; - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var precedingNode; - var newClassDeclaration; - switch (ctorDeclaration.kind) { - case 232: - precedingNode = ctorDeclaration; - deleteNode(ctorDeclaration); - newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); - break; - case 230: - precedingNode = ctorDeclaration.parent.parent; - if (ctorDeclaration.parent.declarations.length === 1) { - deleteNode(precedingNode); - } - else { - deleteNode(ctorDeclaration, true); - } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - break; - } - if (!newClassDeclaration) { - return undefined; - } - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); - for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { - var deleteCallback = deletes_1[_i]; - deleteCallback(); - } - return { - edits: changeTracker.getChanges(), - renameFilename: undefined, - renameLocation: undefined, - }; - function deleteNode(node, inList) { - if (inList === void 0) { inList = false; } - if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { - return; - } - deletedNodes.push(node); - if (inList) { - deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); - } - else { - deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); - } - } - function createClassElementsFromSymbol(symbol) { - var memberElements = []; - if (symbol.members) { - symbol.members.forEach(function (member) { - var memberElement = createClassElement(member, undefined); - if (memberElement) { - memberElements.push(memberElement); - } - }); - } - if (symbol.exports) { - symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(115)]); - if (memberElement) { - memberElements.push(memberElement); - } - }); - } - return memberElements; - function shouldConvertDeclaration(_target, source) { - return ts.isFunctionLike(source); - } - function createClassElement(symbol, modifiers) { - if (!(symbol.flags & 4)) { - return; - } - var memberDeclaration = symbol.valueDeclaration; - var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; - } - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 214 - ? assignmentBinaryExpression.parent : assignmentBinaryExpression; - deleteNode(nodeToDelete); - if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); - } - switch (assignmentBinaryExpression.right.kind) { - case 190: { - var functionExpression = assignmentBinaryExpression.right; - 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 191: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - if (arrowFunctionBody.kind === 211) { - bodyBlock = arrowFunctionBody; - } - else { - bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); - } - 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; - } - default: { - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop); - return prop; - } - } - } - } - function copyComments(sourceNode, targetNode) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - if (kind === 3) { - pos += 2; - end -= 2; - } - else { - pos += 2; - } - ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); - }); - } - function createClassFromVariableDeclaration(node) { - var initializer = node.initializer; - if (!initializer || initializer.kind !== 190) { - return undefined; - } - if (node.name.kind !== 71) { - return undefined; - } - var memberElements = createClassElementsFromSymbol(initializer.symbol); - if (initializer.body) { - memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); - } - var modifiers = getModifierKindFromSource(precedingNode, 84); - var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements); - return cls; - } - function createClassFromFunctionDeclaration(node) { - var memberElements = createClassElementsFromSymbol(ctorSymbol); - if (node.body) { - memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); - } - 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 = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var refactor; - (function (refactor) { - var actionName = "Convert to ES6 module"; - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); - refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition; - if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { - return undefined; - } - var node = ts.getTokenAtPosition(file, startPosition, false); - return !isAtTriggerLocation(file, node) ? undefined : [ - { - name: actionName, - description: description, - actions: [ - { - description: description, - name: actionName, - }, - ], - }, - ]; - } - function isAtTriggerLocation(sourceFile, node, onSecondTry) { - if (onSecondTry === void 0) { onSecondTry = false; } - switch (node.kind) { - case 185: - return isAtTopLevelRequire(node); - case 183: - return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) - || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); - case 231: - return isVariableDeclarationTriggerLocation(ts.firstOrUndefined(node.declarations)); - case 230: - return isVariableDeclarationTriggerLocation(node); - default: - return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) - || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, true); - } - function isVariableDeclarationTriggerLocation(decl) { - return !!decl && !!decl.initializer && ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); - } - } - function isAtTopLevelRequire(call) { - if (!ts.isRequireCall(call, true)) { - return false; - } - var propAccess = call.parent; - var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; - if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { - return true; - } - if (!ts.isVariableDeclaration(varDecl)) { - return false; - } - var varDeclList = varDecl.parent; - if (varDeclList.kind !== 231) { - return false; - } - var varStatement = varDeclList.parent; - return varStatement.kind === 212 && varStatement.parent.kind === 272; - } - function getEditsForAction(context, _actionName) { - ts.Debug.assertEqual(actionName, _actionName); - var file = context.file, program = context.program; - ts.Debug.assert(ts.isSourceFileJavaScript(file)); - var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); - if (moduleExportsChangedToDefault) { - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, file, changes); - } - } - }); - return { edits: edits, renameFilename: undefined, renameLocation: undefined }; - } - function fixImportOfModuleExports(importingFile, exportingFile, changes) { - for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); - if (!imported || imported.resolvedFileName !== exportingFile.fileName) { - continue; - } - var parent = moduleSpecifier.parent; - switch (parent.kind) { - case 252: { - var importEq = parent.parent; - changes.replaceNode(importingFile, importEq, makeImport(importEq.name, undefined, moduleSpecifier.text)); - break; - } - case 185: { - var call = parent; - if (ts.isRequireCall(call, false)) { - changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); - } - break; - } - } - } - } - function convertFileToEs6Module(sourceFile, checker, changes, target) { - var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; - var exports = collectExportRenames(sourceFile, checker, identifiers); - convertExportsAccesses(sourceFile, exports, changes); - var moduleExportsChangedToDefault = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); - moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; - } - return moduleExportsChangedToDefault; - } - function collectExportRenames(sourceFile, checker, identifiers) { - var res = ts.createMap(); - forEachExportReference(sourceFile, function (node) { - var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; - if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 107455, true))) { - res.set(text, makeUniqueName("_" + text, identifiers)); - } - }); - return res; - } - function convertExportsAccesses(sourceFile, exports, changes) { - forEachExportReference(sourceFile, function (node, isAssignmentLhs) { - if (isAssignmentLhs) { + var codefix; + (function (codefix) { + var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + var fixIdAddInitializer = "addMissingPropertyInitializer"; + var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); + if (!propertyDeclaration) return; - } - var text = node.name.text; - changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); - }); - } - function forEachExportReference(sourceFile, cb) { - sourceFile.forEachChild(function recur(node) { - if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { - var parent = node.parent; - cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58); - } - node.forEachChild(recur); - }); - } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { - switch (statement.kind) { - case 212: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); - return false; - case 214: { - var expression = statement.expression; - switch (expression.kind) { - case 185: { - if (ts.isRequireCall(expression, true)) { - changes.replaceNode(sourceFile, statement, makeImport(undefined, undefined, expression.arguments[0].text)); - } - return false; - } - case 198: { - var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return operatorToken.kind === 58 && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); - } - } - } - default: - return false; - } - } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { - var declarationList = statement.declarationList; - var foundImport = false; - var newNodes = ts.flatMap(declarationList.declarations, function (decl) { - var name = decl.name, initializer = decl.initializer; - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { - foundImport = true; - return []; - } - if (ts.isRequireCall(initializer, true)) { - foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); - } - else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) { - foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); - } - else { - return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); - } - }); - if (foundImport) { - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - } - } - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { - switch (name.kind) { - case 178: - case 179: { - var tmp = makeUniqueName(propertyName, identifiers); - return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), - makeConst(undefined, name, ts.createIdentifier(tmp)), - ]; - } - case 71: - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; - default: - ts.Debug.assertNever(name); - } - } - function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { - if (!ts.isPropertyAccessExpression(left)) { - return false; - } - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { - changes.deleteNode(sourceFile, statement); - } - else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); - } - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - return changedToDefaultExport; - } - } - else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { - convertNamedExport(sourceFile, statement, left.name, right, changes, exports); - } - return false; - var _a; - } - function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { - switch (prop.kind) { - case 155: - case 156: - case 269: - case 270: - return undefined; - case 268: - return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); - case 153: - return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84)], prop); - default: - ts.Debug.assertNever(prop); - } - }); - } - function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { - var text = propertyName.text; - var rename = exports.get(text); - if (rename !== undefined) { - var newNodes = [ - makeConst(undefined, rename, right), - makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + var result = [ + getActionForAddMissingUndefinedType(context, propertyDeclaration), + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) ]; - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - } - else { - changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); - } - } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84), ts.createToken(79)]; - switch (exported.kind) { - case 190: - case 191: { - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 203: { - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 185: - if (ts.isRequireCall(exported, true)) { - return convertReExportAll(exported.arguments[0], checker); + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + return result; + }, + fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); + if (!propertyDeclaration) + return; + switch (context.fixId) { + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag.file, propertyDeclaration); + break; + case fixIdAddInitializer: + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return; + addInitializer(changes, diag.file, propertyDeclaration, initializer); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); } - default: - return [[ts.createExportAssignment(undefined, undefined, false, exported)], true]; + }); + }, + }); + function getPropertyDeclaration(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, false); + return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + } + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var undefinedTypeNode = ts.createKeywordTypeNode(140); + var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types)); + } + function getActionForAddMissingInitializer(context, propertyDeclaration) { + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 2) { + return ts.createLiteral(""); + } + else if (type.flags & 4) { + return ts.createNumericLiteral("0"); + } + else if (type.flags & 8) { + return ts.createFalse(); + } + else if (type.flags & 224) { + return ts.createLiteral(type.value); + } + else if (type.flags & 131072) { + return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); + } + else if (ts.getObjectFlags(type) & 1) { + var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || ts.hasModifier(classDeclaration, 128)) + return undefined; + var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; }); + if (constructorDeclaration && constructorDeclaration.parameters.length) + return undefined; + return ts.createNew(ts.createIdentifier(type.symbol.name), undefined, undefined); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "useDefaultImport"; + var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var info = getInfo(sourceFile, start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); }, + }); + function getInfo(sourceFile, pos) { + var name = ts.getTokenAtPosition(sourceFile, pos, false); + if (!ts.isIdentifier(name)) + return undefined; + var parent = name.parent; + if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) { + return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression }; + } + else if (ts.isNamespaceImport(parent)) { + var importNode = parent.parent.parent; + return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function convertReExportAll(reExported, checker) { - var moduleSpecifier = reExported.text; - var moduleSymbol = checker.getSymbolAtLocation(reExported); - var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; - return exports.has("export=") - ? [[reExportDefault(moduleSpecifier)], true] - : !exports.has("default") - ? [[reExportStar(moduleSpecifier)], false] - : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + function doChange(changes, sourceFile, info) { + changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, undefined, info.moduleSpecifier)); } - function reExportStar(moduleSpecifier) { - return makeExportDeclaration(undefined, moduleSpecifier); - } - function reExportDefault(moduleSpecifier) { - return makeExportDeclaration([ts.createExportSpecifier(undefined, "default")], moduleSpecifier); - } - function convertExportsDotXEquals(name, exported) { - var modifiers = [ts.createToken(84)]; - switch (exported.kind) { - case 190: { - var expressionName = exported.name; - if (expressionName && expressionName.text !== name) { - return exportConst(); - } - } - case 191: - return functionExpressionToDeclaration(name, modifiers, exported); - case 203: - return classExpressionToDeclaration(name, modifiers, exported); - default: - return exportConst(); - } - function exportConst() { - return makeConst(modifiers, ts.createIdentifier(name), exported); - } - } - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { - switch (name.kind) { - case 178: { - var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { - return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) - ? undefined - : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); - }); - if (importSpecifiers) { - return [makeImport(undefined, importSpecifiers, moduleSpecifier)]; - } - } - case 179: { - var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); - return [ - makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier), - makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), - ]; - } - case 71: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); - default: - ts.Debug.assertNever(name); - } - } - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { - var nameSymbol = checker.getSymbolAtLocation(name); - var namedBindingsNames = ts.createMap(); - var needDefaultImport = false; - for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { - var use = _a[_i]; - if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { - continue; - } - var parent = use.parent; - if (ts.isPropertyAccessExpression(parent)) { - var expression = parent.expression, propertyName = parent.name.text; - ts.Debug.assert(expression === use); - var idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); - } - changes.replaceNode(file, parent, ts.createIdentifier(idName)); - } - else { - needDefaultImport = true; - } - } - var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { - var propertyName = _a[0], idName = _a[1]; - return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); - })); - if (!namedBindings) { - needDefaultImport = true; - } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; - } - function makeUniqueName(name, identifiers) { - while (identifiers.original.has(name) || identifiers.additional.has(name)) { - name = "_" + name; - } - identifiers.additional.set(name, true); - return name; - } - function collectFreeIdentifiers(file) { - var map = ts.createMultiMap(); - file.forEachChild(function recur(node) { - if (ts.isIdentifier(node) && isFreeIdentifier(node)) { - map.add(node.text, node); - } - node.forEachChild(recur); - }); - return map; - } - function isFreeIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 183: - return parent.name !== node; - case 180: - return parent.propertyName !== node; - default: - return true; - } - } - function functionExpressionToDeclaration(name, additionalModifiers, fn) { - return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); - } - function classExpressionToDeclaration(name, additionalModifiers, cls) { - return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); - } - function makeSingleImport(localName, propertyName, moduleSpecifier) { - return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier) - : makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); - } - function makeImport(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifier)); - } - function makeImportSpecifier(propertyName, name) { - return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); - } - function makeConst(modifiers, name, init) { - return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, undefined, init)], 2)); - } - function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { - return ts.createExportDeclaration(undefined, undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); - } - })(refactor = ts.refactor || (ts.refactor = {})); + })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -81407,7 +82379,7 @@ var ts; } else if (ts.isVariableStatement(node)) { var numInitializers = 0; - var lastInitializer = undefined; + var lastInitializer = void 0; for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.initializer) { @@ -81514,7 +82486,7 @@ var ts; switch (node.kind) { case 232: case 233: - if (node.parent.kind === 272 && node.parent.externalModuleIndicator === undefined) { + if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } break; @@ -81757,12 +82729,12 @@ var ts; var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); - var returnType = undefined; + var returnType; var parameters = []; var callArguments = []; var writes; usagesInScope.forEach(function (usage, name) { - var typeNode = undefined; + var typeNode; if (!isJS) { var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); type = checker.getBaseTypeOfLiteralType(type); @@ -81943,7 +82915,7 @@ var ts; var maxInsertionPos = node.pos; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, true); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -81951,11 +82923,11 @@ var ts; if (oldVariableDeclaration) { changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else if (node.parent.kind === 214 && scope === ts.findAncestor(node, isScope)) { var newVariableStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2)); - changeTracker.replaceNode(context.file, node.parent, newVariableStatement, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { var newVariableStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2)); @@ -81971,7 +82943,7 @@ var ts; } else { var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } } } @@ -81981,7 +82953,7 @@ var ts; return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function getContainingVariableDeclarationIfInList(node, scope) { - var prevNode = undefined; + var prevNode; while (node !== undefined && node !== scope) { if (ts.isVariableDeclaration(node) && node.initializer === prevNode && @@ -82001,15 +82973,15 @@ var ts; ts.Debug.assert(fileName === renameFilename); for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) { var change = textChanges_3[_b]; - var span_15 = change.span, newText = change.newText; + var span = change.span, newText = change.newText; var index = newText.indexOf(functionNameText); if (index !== -1) { - lastPos = span_15.start + delta + index; + lastPos = span.start + delta + index; if (!isDeclaredBeforeUse) { return lastPos; } } - delta += newText.length - span_15.length; + delta += newText.length - span.length; } } ts.Debug.assert(isDeclaredBeforeUse); @@ -82017,7 +82989,7 @@ var ts; return lastPos; } function getFirstDeclaration(type) { - var firstDeclaration = undefined; + var firstDeclaration; var symbol = type.symbol; if (symbol && symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -82131,7 +83103,7 @@ var ts; function getNodeToInsertPropertyBefore(maxPos, scope) { var members = scope.members; ts.Debug.assert(members.length > 0); - var prevMember = undefined; + var prevMember; var allProperties = true; for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { var member = members_6[_i]; @@ -82151,7 +83123,7 @@ var ts; } function getNodeToInsertConstantBefore(node, scope) { ts.Debug.assert(!ts.isClassLike(scope)); - var prevScope = undefined; + var prevScope; for (var curr = node; curr !== scope; curr = curr.parent) { if (isScope(curr)) { prevScope = curr; @@ -82159,7 +83131,7 @@ var ts; } for (var curr = (prevScope || node).parent;; curr = curr.parent) { if (isBlockLike(curr)) { - var prevStatement = undefined; + var prevStatement = void 0; for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement.pos > node.pos) { @@ -82211,13 +83183,13 @@ var ts; var visibleDeclarationsInExtractedRange = []; var exposedVariableSymbolSet = ts.createMap(); var exposedVariableDeclarations = []; - var firstExposedNonVariableDeclaration = undefined; + var firstExposedNonVariableDeclaration; var expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : undefined; - var expressionDiagnostic = undefined; + var expressionDiagnostic; if (expression === undefined) { var statements = targetRange.range; var start = ts.first(statements).getStart(); @@ -82283,14 +83255,14 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_10 = function (i) { + var _loop_12 = 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; + var readonlyClassPropertyWrite; usagesPerScope[i].usages.forEach(function (value) { if (value.usage === 2) { hasWrite = true; @@ -82319,7 +83291,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_10(i); + _loop_12(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { @@ -82552,153 +83524,217 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var refactor; - (function (refactor) { - var installTypesForPackage; - (function (installTypesForPackage) { - var refactorName = "Install missing types package"; - var actionName = "install"; - var description = "Install missing types package"; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { - return undefined; + var sourcemaps; + (function (sourcemaps) { + sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; + function decode(host, mapPath, map, program, fallbackCache) { + if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } + var currentDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot || currentDirectory; + var decodedMappings; + var generatedOrderedMappings; + var sourceOrderedMappings; + return { + getOriginalPosition: getOriginalPosition, + getGeneratedPosition: getGeneratedPosition + }; + function getGeneratedPosition(loc) { + var maps = getGeneratedOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); + if (targetIndex < 0 && maps.length > 0) { + targetIndex = ~targetIndex; } - var action = getAction(context); - return action && [ - { - name: refactorName, - description: description, - actions: [ - { - description: action.description, - name: actionName, - }, - ], - }, - ]; + if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { + return loc; + } + return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; } - function getEditsForAction(context, _actionName) { - ts.Debug.assertEqual(actionName, _actionName); - var action = getAction(context); - return { - edits: [], - renameFilename: undefined, - renameLocation: undefined, - commands: action.commands, + function getOriginalPosition(loc) { + var maps = getSourceOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); + if (targetIndex < 0 && maps.length > 0) { + targetIndex = ~targetIndex; + } + return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; + } + function getSourceFileLike(fileName, location) { + var file = program && program.getSourceFile(fileName); + if (!file) { + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + return fallbackCache.get(path); + } + return file; + } + function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { + var file = getSourceFileLike(fileName, directory); + if (!file) { + return -1; + } + return ts.getPositionOfLineAndCharacter(file, line, character); + } + function getDecodedMappings() { + return decodedMappings || (decodedMappings = calculateDecodedMappings()); + } + function getSourceOrderedMappings() { + return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); + } + function getGeneratedOrderedMappings() { + return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); + } + function calculateDecodedMappings() { + var state = { + encodedText: map.mappings, + currentNameIndex: undefined, + sourceMapNamesLength: map.names ? map.names.length : undefined, + currentEmittedColumn: 0, + currentEmittedLine: 0, + currentSourceColumn: 0, + currentSourceLine: 0, + currentSourceIndex: 0, + positions: [], + decodingIndex: 0, + processPosition: processPosition, }; - } - 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 242: - case 252: - 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 description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); - refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition, program = context.program; - if (!ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { - return undefined; - } - var importInfo = getConvertibleImportAtPosition(file, startPosition); - if (!importInfo) { - return undefined; - } - var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); - if (!(resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) { - return undefined; - } - return [ - { - name: actionName, - description: description, - actions: [ - { - description: 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 241: - var eq = node; - var moduleReference = eq.moduleReference; - return moduleReference.kind === 252 && ts.isStringLiteral(moduleReference.expression) - ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression } - : undefined; - case 242: - var d = node; - var importClause = d.importClause; - return importClause && !importClause.name && importClause.namedBindings.kind === 244 && ts.isStringLiteral(d.moduleSpecifier) - ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier } - : undefined; - case 244: - case 252: - case 91: - case 71: - case 9: - case 39: - break; - default: - return undefined; + while (!hasCompletedDecoding(state)) { + decodeSinglePosition(state); + if (state.error) { + host.log("Encountered error while decoding sourcemap found at " + mapPath + ": " + state.error); + return []; } - node = node.parent; } + return state.positions; } - })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); - })(refactor = ts.refactor || (ts.refactor = {})); + function compareProcessedPositionSourcePositions(a, b) { + return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || + ts.compareValues(a.sourcePosition, b.sourcePosition); + } + function compareProcessedPositionEmittedPositions(a, b) { + return ts.compareValues(a.emittedPosition, b.emittedPosition); + } + function processPosition(position) { + var sourcePath = map.sources[position.sourceIndex]; + return { + emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), + sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), + sourcePath: sourcePath, + }; + } + } + sourcemaps.decode = decode; + function hasCompletedDecoding(state) { + return state.decodingIndex === state.encodedText.length; + } + function decodeSinglePosition(state) { + while (state.decodingIndex < state.encodedText.length) { + var char = state.encodedText.charCodeAt(state.decodingIndex); + if (char === 59) { + state.currentEmittedLine++; + state.currentEmittedColumn = 0; + state.decodingIndex++; + continue; + } + if (char === 44) { + state.decodingIndex++; + continue; + } + state.currentEmittedColumn += base64VLQFormatDecode(); + if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { + return; + } + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { + return; + } + state.currentSourceIndex += base64VLQFormatDecode(); + if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { + return; + } + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { + return; + } + state.currentSourceLine += base64VLQFormatDecode(); + if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { + return; + } + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { + return; + } + state.currentSourceColumn += base64VLQFormatDecode(); + if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { + return; + } + if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { + if (state.currentNameIndex === undefined) { + state.currentNameIndex = 0; + } + state.currentNameIndex += base64VLQFormatDecode(); + } + if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { + return; + } + capturePosition(); + return; + } + createErrorIfCondition(true, "No encoded entry found"); + return; + function capturePosition() { + state.positions.push(state.processPosition({ + emittedColumn: state.currentEmittedColumn, + emittedLine: state.currentEmittedLine, + sourceColumn: state.currentSourceColumn, + sourceIndex: state.currentSourceIndex, + sourceLine: state.currentSourceLine, + nameIndex: state.currentNameIndex + })); + } + function createErrorIfCondition(condition, errormsg) { + if (state.error) { + return true; + } + if (condition) { + state.error = errormsg; + } + return condition; + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; state.decodingIndex++) { + if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { + return; + } + var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); + moreDigits = (currentByte & 32) !== 0; + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + if ((value & 1) === 0) { + value = value >> 1; + } + else { + value = value >> 1; + value = -value; + } + return value; + } + } + function base64FormatDecode(char) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + } + function isSourceMappingSegmentEnd(encodedText, pos) { + return (pos === encodedText.length || + encodedText.charCodeAt(pos) === 44 || + encodedText.charCodeAt(pos) === 59); + } + })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); })(ts || (ts = {})); var ts; (function (ts) { - ts.servicesVersion = "0.7"; + ts.servicesVersion = "0.8"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : @@ -82757,99 +83793,15 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { - ts.scanner.setTextPos(pos); - while (pos < end) { - var token = ts.scanner.scan(); - var textPos = ts.scanner.getTextPos(); - if (textPos <= end) { - if (token === 71) { - ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(this) + " to have an Identifier in its trivia"); - } - nodes.push(createNode(token, pos, textPos, this)); - } - pos = textPos; - if (token === 1) { - break; - } - } - return pos; - }; - NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(293, nodes.pos, nodes.end, this); - list._children = []; - var pos = nodes.pos; - for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { - var node = nodes_9[_i]; - if (pos < node.pos) { - pos = this.addSyntheticNodes(list._children, pos, node.pos); - } - list._children.push(node); - pos = node.end; - } - if (pos < nodes.end) { - this.addSyntheticNodes(list._children, pos, nodes.end); - } - return list; - }; - NodeObject.prototype.createChildren = function (sourceFile) { - var _this = this; - if (!ts.isNodeKind(this.kind)) { - this._children = ts.emptyArray; - return; - } - if (ts.isJSDocCommentContainingNode(this)) { - var children_4 = []; - this.forEachChild(function (child) { children_4.push(child); }); - this._children = children_4; - return; - } - var children = []; - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - var pos = this.pos; - var processNode = function (node) { - pos = _this.addSyntheticNodes(children, pos, node.pos); - children.push(node); - pos = node.end; - }; - var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); - } - children.push(_this.createSyntaxList(nodes)); - pos = nodes.end; - }; - if (this.jsDoc) { - for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - processNode(jsDocComment); - } - } - pos = this.pos; - ts.forEachChild(this, processNode, processNodes); - if (pos < this.end) { - this.addSyntheticNodes(children, pos, this.end); - } - ts.scanner.setText(undefined); - this._children = children; - }; NodeObject.prototype.getChildCount = function (sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children.length; + return this.getChildren(sourceFile).length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children[index]; + return this.getChildren(sourceFile)[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; + return this._children || (this._children = createChildren(this, sourceFile)); }; NodeObject.prototype.getFirstToken = function (sourceFile) { this.assertHasRealPosition(); @@ -82876,6 +83828,64 @@ var ts; }; return NodeObject; }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + ts.forEach(node.jsDoc, processNode); + pos = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 71) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(293, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } var TokenOrIdentifierObject = (function () { function TokenOrIdentifierObject(pos, end) { this.pos = pos; @@ -83110,7 +84120,7 @@ var ts; } function findInheritedJSDocComments(declaration, propertyName, typeChecker) { var foundDocs = false; - return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { + return ts.flatMap(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { if (foundDocs) { return ts.emptyArray; } @@ -83127,15 +84137,6 @@ var ts; 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) { @@ -83191,20 +84192,8 @@ var ts; } function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); - if (name) { - var result_6 = ts.getTextOfIdentifierOrLiteral(name); - if (result_6 !== undefined) { - return result_6; - } - if (name.kind === 146) { - var expr = name.expression; - if (expr.kind === 183) { - return expr.name.text; - } - return ts.getTextOfIdentifierOrLiteral(expr); - } - } - return undefined; + return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) : + name.kind === 146 && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined); } function visit(node) { switch (node.kind) { @@ -83536,6 +84525,29 @@ var ts; return ThrottledCancellationToken; }()); ts.ThrottledCancellationToken = ThrottledCancellationToken; + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + var text = host.readFile(path); + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } + ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -83548,6 +84560,7 @@ var ts; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } + var sourcemappedFileCache; function log(message) { if (host.log) { host.log(message); @@ -83628,6 +84641,7 @@ var ts; var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); hostCache = undefined; + sourcemappedFileCache = createSourceFileLikeCache(host); program.getTypeChecker(); return; function fileExists(fileName) { @@ -83690,18 +84704,24 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return semanticDiagnostics.concat(declarationDiagnostics); } + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program); + } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } + if (options === void 0) { options = ts.defaultPreferences; } + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), fullPreferences); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName, preferences); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -83714,41 +84734,39 @@ var ts; if (node === sourceFile) { return undefined; } - if (ts.isLabelName(node)) { - return undefined; - } var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { switch (node.kind) { case 71: + if (ts.isLabelName(node)) { + return undefined; + } case 183: case 145: case 99: case 173: case 97: var type = typeChecker.getTypeAtLocation(node); - if (type) { - return { - kind: "", - kindModifiers: "", - textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type.symbol ? type.symbol.getJsDocTags() : undefined - }; - } + return type && { + kind: "", + kindModifiers: "", + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type.symbol ? type.symbol.getJsDocTags() : undefined + }; } return undefined; } - var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; return { - kind: displayPartsDocumentationsAndKind.symbolKind, + kind: symbolKind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: displayPartsDocumentationsAndKind.displayParts, - documentation: displayPartsDocumentationsAndKind.documentation, - tags: displayPartsDocumentationsAndKind.tags + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags, }; } function getSymbolAtLocationForQuickInfo(node, checker) { @@ -83756,30 +84774,151 @@ var ts; && ts.isPropertyAssignment(node.parent) && node.parent.name === node) { var type = checker.getContextualType(node.parent.parent); - if (type) { - var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); - if (property) { - return property; - } + var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); + if (property) { + return property; } } return checker.getSymbolAtLocation(node); } + var sourceMapCommentRegExp = /^\/\/[@#] sourceMappingURL=(.+)$/gm; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; + } + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + sourceMapCommentRegExp.lastIndex = starts[index]; + var comment = sourceMapCommentRegExp.exec(mappedFile.text); + if (comment) { + return comment[1]; + } + } + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, program, sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function makeGetTargetOfMappedPosition(extract, create) { + return getTargetOfMappedPosition; + function getTargetOfMappedPosition(input) { + var info = extract(input); + if (ts.endsWith(info.fileName, ".d.ts")) { + var file = program.getSourceFile(info.fileName); + if (!file) { + var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); + file = sourcemappedFileCache.get(path); + } + if (!file) { + return input; + } + var mapper = getSourceMapper(info.fileName, file); + var newLoc = mapper.getOriginalPosition(info); + if (newLoc === info) + return input; + return getTargetOfMappedPosition(create(newLoc, input)); + } + return input; + } + } + var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + containerKind: info.containerKind, + containerName: info.containerName, + fileName: newLoc.fileName, + kind: info.kind, + name: info.name, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + } + }); }); + function getTargetOfMappedDeclarationFiles(infos) { + return ts.map(infos, getTargetOfMappedDeclarationInfo); + } function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position)); } function getDefinitionAndBoundSpan(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + var result = ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + if (!result) + return result; + var mappedDefs = getTargetOfMappedDeclarationFiles(result.definitions); + if (mappedDefs === result.definitions) { + return result; + } + return { + definitions: mappedDefs, + textSpan: result.textSpan + }; } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); + return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position)); + } + var getTargetOfMappedImplementationLocation = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + fileName: newLoc.fileName, + kind: info.kind, + displayParts: info.displayParts, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + } + }); }); + function getTargetOfMappedImplementationLocations(infos) { + return ts.map(infos, getTargetOfMappedImplementationLocation); } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return getTargetOfMappedImplementationLocations(ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position)); } function getOccurrencesAtPosition(fileName, position) { var canonicalFileName = getCanonicalFileName(ts.normalizeSlashes(fileName)); @@ -83975,29 +85114,32 @@ var ts; } return []; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); 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, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); }); } - function getCombinedCodeFix(scope, fixId, formatOptions) { + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions) { + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -84061,7 +85203,7 @@ var ts; if (!ts.isInComment(sourceFile, matchPosition)) { continue; } - var descriptor = undefined; + var descriptor = void 0; for (var i = 0; i < descriptors.length; i++) { if (matchArray[i + firstDescriptorCaptureIndex]) { descriptor = descriptors[i]; @@ -84105,7 +85247,7 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } - function getRefactorContext(file, positionOrRange, formatOptions) { + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; return { file: file, @@ -84115,23 +85257,27 @@ var ts; host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, + preferences: preferences, }; } - function getApplicableRefactors(fileName, positionOrRange) { + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); } - function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -84506,7 +85652,7 @@ var ts; message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), start: diagnostic.start, length: diagnostic.length, - category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), + category: ts.diagnosticCategoryName(diagnostic), code: diagnostic.code }; } @@ -84546,7 +85692,7 @@ var ts; }; LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { var newLine = ts.getNewLineOrDefaultFromHost(this.host); - return ts.realizeDiagnostics(diagnostics, newLine); + return realizeDiagnostics(diagnostics, newLine); }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; @@ -84578,6 +85724,10 @@ var ts; return _this.realizeDiagnostics(diagnostics); }); }; + LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + }; LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { var _this = this; return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { @@ -84664,15 +85814,15 @@ var ts; return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; }); }); }; - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = options === undefined ? undefined : JSON.parse(options); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options) { @@ -84823,8 +85973,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { - var ref = refs_2[_i]; + for (var _i = 0, refs_3 = refs; _i < refs_3.length; _i++) { + var ref = refs_3[_i]; result.push({ path: ts.normalizeSlashes(ref.fileName), position: ref.pos, @@ -85178,36 +86328,6 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } - function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, comparer) { - var newIndex = 0; - var oldIndex = 0; - var newLen = newItems.length; - var oldLen = oldItems.length; - while (newIndex < newLen && oldIndex < oldLen) { - var newItem = newItems[newIndex]; - var oldItem = oldItems[oldIndex]; - var compareResult = comparer(newItem, oldItem); - if (compareResult === -1) { - inserted(newItem); - newIndex++; - } - else if (compareResult === 1) { - deleted(oldItem); - oldIndex++; - } - else { - newIndex++; - oldIndex++; - } - } - while (newIndex < newLen) { - inserted(newItems[newIndex++]); - } - while (oldIndex < oldLen) { - deleted(oldItems[oldIndex++]); - } - } - server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; function indent(str) { return "\n " + str; } @@ -85255,6 +86375,7 @@ var ts; CommandTypes["GeterrForProject"] = "geterrForProject"; CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; + CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync"; CommandTypes["NavBar"] = "navbar"; CommandTypes["NavBarFull"] = "navbar-full"; CommandTypes["Navto"] = "navto"; @@ -85288,7 +86409,8 @@ var ts; CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; CommandTypes["Cleanup"] = "cleanup"; - CommandTypes["OutliningSpans"] = "outliningSpans"; + CommandTypes["GetOutliningSpans"] = "getOutliningSpans"; + CommandTypes["GetOutliningSpansFull"] = "outliningSpans"; CommandTypes["TodoComments"] = "todoComments"; CommandTypes["Indentation"] = "indentation"; CommandTypes["DocCommentTemplate"] = "docCommentTemplate"; @@ -85456,7 +86578,10 @@ var ts; if (this.isOpen) { return this.switchToScriptVersionCache(); } - return !this.pendingReloadFromDisk && this.svc; + if (this.pendingReloadFromDisk) { + this.reloadWithFileText(); + } + return this.svc; }; TextStorage.prototype.getOrLoadText = function () { if (this.text === undefined || this.pendingReloadFromDisk) { @@ -85541,9 +86666,8 @@ var ts; ScriptInfo.prototype.getRealpathIfDifferent = function () { return this.realpath && this.realpath !== this.path ? this.realpath : undefined; }; - ScriptInfo.prototype.getFormatCodeSettings = function () { - return this.formatCodeSettings; - }; + ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatSettings; }; + ScriptInfo.prototype.getPreferences = function () { return this.preferences; }; ScriptInfo.prototype.attachToProject = function (project) { var isNew = !this.isAttached(project); if (isNew) { @@ -85624,12 +86748,18 @@ var ts; p.registerFileUpdate(this.path); } }; - ScriptInfo.prototype.setFormatOptions = function (formatSettings) { + ScriptInfo.prototype.setOptions = function (formatSettings, preferences) { if (formatSettings) { - if (!this.formatCodeSettings) { - this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); + if (!this.formatSettings) { + this.formatSettings = server.getDefaultFormatCodeSettings(this.host); } - server.mergeMapLikes(this.formatCodeSettings, formatSettings); + server.mergeMapLikes(this.formatSettings, formatSettings); + } + if (preferences) { + if (!this.preferences) { + this.preferences = ts.clone(ts.defaultPreferences); + } + server.mergeMapLikes(this.preferences, preferences); } }; ScriptInfo.prototype.getLatestVersion = function () { @@ -85862,7 +86992,7 @@ var ts; var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); ts.mutateMap(missingFileWatches, newMissingFilePathMap, { createNewValue: createMissingFileWatch, - onDeleteValue: closeFileWatcher + onDeleteValue: ts.closeFileWatcher }); } ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; @@ -85894,75 +87024,74 @@ var ts; return program.isEmittedFile(file); } ts.isEmittedFileOfProgram = isEmittedFileOfProgram; - function addFileWatcher(host, file, cb) { - return host.watchFile(file, cb); + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); } - 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); + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); } - 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); + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); return { close: function () { - if (!logOnlyTrigger) { - log(watcherCaption + "Close: " + info); - } + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); watcher.close(); } }; } - function closeFileWatcher(watcher) { - watcher.close(); + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : ""); } - ts.closeFileWatcher = closeFileWatcher; function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } @@ -85975,12 +87104,14 @@ var ts; 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 cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var nonRelaticeModuleNameCache = ts.createMap(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); @@ -86041,6 +87172,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); + nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); } function finishCachingPerDirectoryResolution() { @@ -86054,7 +87186,7 @@ var ts; clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); if (!resolutionHost.getGlobalCache) { return primaryResult; } @@ -86094,15 +87226,8 @@ var ts; 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) { + watchFailedLookupLocationOfResolution(resolution); + if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { @@ -86173,8 +87298,9 @@ var ts; if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { return { dir: rootDir, dirPath: rootPath }; } - var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); - var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { while (ts.stringContains(dirPath, "/node_modules/")) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); @@ -86197,69 +87323,87 @@ var ts; 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; - } + function watchFailedLookupLocationOfResolution(resolution) { + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + 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]; + if (resolution.refCount !== undefined) { + resolution.refCount++; + return; + } + resolution.refCount = 1; + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_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; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; if (!ignore) { - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - if (dirWatcher) { - dirWatcher.refCount++; + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + if (dirPath === rootPath) { + setAtRoot = true; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + setDirectoryWatcher(dir, dirPath); } } } + if (setAtRoot) { + setDirectoryWatcher(rootDir, rootPath); + } + } + function setDirectoryWatcher(dir, dirPath) { + 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); + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + return; } - } - function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { - var failedLookupLocations = _a.failedLookupLocations; - for (var i = startIndex; i < failedLookupLocations.length; i++) { - var failedLookupLocation = failedLookupLocations[i]; + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + if (!ignore) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; - if (!ignore) { - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - dirWatcher.refCount--; - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + dirWatcher.refCount--; } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { @@ -86333,7 +87477,8 @@ var ts; } else { var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); - if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { isChangedFailedLookupLocation = function (location) { var locationPath = resolutionHost.toPath(location); return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); @@ -86357,13 +87502,27 @@ var ts; function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); } - function createTypeRootsWatch(_typeRootPath, typeRoot) { + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } resolutionHost.onChangedAutomaticTypeDirectiveNames(); + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } }, 1); } function updateTypeRootsWatch() { @@ -86827,6 +87986,7 @@ var ts; server.isScriptInfo = isScriptInfo; var Project = (function () { function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { + var _this = this; this.projectName = projectName; this.projectKind = projectKind; this.projectService = projectService; @@ -86845,6 +88005,7 @@ var ts; this.hasChangedAutomaticTypeDirectiveNames = false; this.directoryStructureHost = directoryStructureHost; this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); + this.getCanonicalFileName = this.projectService.toCanonicalFileName; this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { this.compilerOptions = ts.getDefaultCompilerOptions(); @@ -86856,7 +88017,10 @@ var ts; } this.setInternalCompilerOptionsForEmittingJsFiles(); var host = this.projectService.host; - if (host.trace) { + if (this.projectService.logger.loggingEnabled()) { + this.trace = function (s) { return _this.writeLog(s); }; + } + else if (host.trace) { this.trace = function (s) { return host.trace(s); }; } if (host.realpath) { @@ -86998,13 +88162,13 @@ var ts; 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); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution", this); }; Project.prototype.onInvalidatedResolution = function () { this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); }; Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { - return this.projectService.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory", this); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory", this); }; Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { this.hasChangedAutomaticTypeDirectiveNames = true; @@ -87388,10 +88552,10 @@ var ts; } var oldExternalFiles = this.externalFiles || server.emptyArray; this.externalFiles = this.getExternalFiles(); - server.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, function (inserted) { + ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.compareStringsCaseSensitive, function (inserted) { var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost); scriptInfo.attachToProject(_this); - }, function (removed) { return _this.detachScriptInfoFromProject(removed); }, ts.compareStringsCaseSensitive); + }, function (removed) { return _this.detachScriptInfoFromProject(removed); }); var elapsed = ts.timestamp() - start; this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " Version: " + this.getProjectVersion() + " structureChanged: " + hasChanges + " Elapsed: " + elapsed + "ms"); return hasChanges; @@ -87405,7 +88569,7 @@ var ts; }; Project.prototype.addMissingFileWatcher = function (missingFilePath) { var _this = this; - var fileWatcher = this.projectService.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { + var fileWatcher = this.projectService.watchFactory.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { if (_this.projectKind === ProjectKind.Configured) { _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); } @@ -87414,7 +88578,7 @@ var ts; fileWatcher.close(); _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this); } - }, "Missing file from program", this); + }, ts.PollingInterval.Medium, "Missing file from program", this); return fileWatcher; }; Project.prototype.isWatchedMissingFile = function (path) { @@ -87437,8 +88601,8 @@ var ts; 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]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var file = sourceFiles_7[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -87518,7 +88682,7 @@ var ts; } var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_11 = function (globalPluginName) { + var _loop_13 = function (globalPluginName) { if (!globalPluginName) return "continue"; if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) @@ -87529,7 +88693,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_11(globalPluginName); + _loop_13(globalPluginName); } } }; @@ -87945,6 +89109,9 @@ var ts; ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + function getDetailWatchInfo(watchType, project) { + return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; + } var ProjectService = (function () { function ProjectService(opts) { var _this = this; @@ -87970,6 +89137,7 @@ var ts; this.typingsInstaller = opts.typingsInstaller || server.nullTypingsInstaller; this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = opts.eventHandler; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; @@ -87991,31 +89159,16 @@ var ts; this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + preferences: ts.defaultPreferences, hostInfo: "Unknown host", extraFileExtensions: [] }; 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; - } + var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose : + this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None; + var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop; + this.watchFactory = ts.getWatchFactory(watchLogLevel, log, getDetailWatchInfo); } - 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); }; @@ -88204,17 +89357,15 @@ var ts; return project.dirty && project.updateGraph(); }; ProjectService.prototype.getFormatCodeOptions = function (file) { - var formatCodeSettings; - if (file) { - var info = this.getScriptInfoForNormalizedPath(file); - if (info) { - formatCodeSettings = info.getFormatCodeSettings(); - } - } - return formatCodeSettings || this.hostConfiguration.formatCodeOptions; + var info = this.getScriptInfoForNormalizedPath(file); + return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions; }; - ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind) { - var info = this.getScriptInfoForNormalizedPath(fileName); + ProjectService.prototype.getPreferences = function (file) { + var info = this.getScriptInfoForNormalizedPath(file); + return info && info.getPreferences() || this.hostConfiguration.preferences; + }; + ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind, path) { + var info = this.getScriptInfoForPath(path); if (!info) { this.logger.msg("Error: got watch notification for unknown file: " + fileName); } @@ -88243,7 +89394,7 @@ var ts; }; ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { var _this = this; - return this.watchDirectory(this.host, directory, function (fileOrDirectory) { + return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) { var fileOrDirectoryPath = _this.toPath(fileOrDirectory); project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); var configFilename = project.getConfigFilePath(); @@ -88463,7 +89614,7 @@ var ts; }; 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"); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root"); this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback"); }; ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) { @@ -88726,7 +89877,7 @@ var ts; var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost); project.configFileSpecs = configFileSpecs; - project.configFileWatcher = this.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, "Config file for the program", project); + project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); if (!lastFileExceededProgramSize) { project.watchWildcards(projectOptions.wildcardDirectories); } @@ -88741,8 +89892,8 @@ var ts; 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]; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; var newRootFile = propertyReader.getFileName(f); var normalizedPath = server.toNormalizedPath(newRootFile); var isDynamic = server.isDynamicFileName(normalizedPath); @@ -88821,7 +89972,7 @@ var ts; this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { - if (!this.eventHandler) { + if (!this.eventHandler || this.suppressDiagnosticEvents) { return; } this.eventHandler({ @@ -88894,7 +90045,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_12 = function (project) { + var _loop_14 = function (project) { if (project.languageServiceEnabled && !project.getCompilerOptions().preserveSymlinks && !ts.contains(info.containingProjects, project)) { @@ -88909,7 +90060,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_12(project); + _loop_14(project); } } } @@ -88918,8 +90069,8 @@ var ts; var _this = this; ts.Debug.assert(!info.fileWatcher); 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"); + var fileName = info.fileName; + info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); } }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { @@ -88982,7 +90133,7 @@ var ts; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { - info.setFormatOptions(convertFormatOptions(args.formatOptions)); + info.setOptions(convertFormatOptions(args.formatOptions), args.preferences); this.logger.info("Host configuration update for file " + args.file); } } @@ -88995,6 +90146,9 @@ var ts; server.mergeMapLikes(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); this.logger.info("Format host information updated"); } + if (args.preferences) { + server.mergeMapLikes(this.hostConfiguration.preferences, args.preferences); + } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; this.reloadProjects(); @@ -89136,13 +90290,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_13 = function (proj) { + var _loop_15 = 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_13(proj); + _loop_15(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -89242,7 +90396,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_14 = function (name) { + var _loop_16 = 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]; @@ -89257,7 +90411,7 @@ var ts; } } if (rule.exclude) { - var _loop_15 = function (exclude) { + var _loop_17 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -89280,7 +90434,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_15(exclude); + _loop_17(exclude); } } else { @@ -89295,11 +90449,11 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_14(name); + _loop_16(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_16 = function (i) { + var _loop_18 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -89333,7 +90487,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_16(i); + _loop_18(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -89486,7 +90640,7 @@ var ts; end: scriptInfo.positionToLineOffset(diag.start + diag.length), text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), code: diag.code, - category: ts.DiagnosticCategory[diag.category].toLowerCase(), + category: ts.diagnosticCategoryName(diag), source: diag.source }; } @@ -89498,7 +90652,7 @@ var ts; var end = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length)); var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n"); var code = diag.code, source = diag.source; - var category = ts.DiagnosticCategory[diag.category].toLowerCase(); + var category = ts.diagnosticCategoryName(diag); return includeFileName ? { start: start, end: end, text: text, code: code, category: category, source: source, fileName: diag.file && diag.file.fileName } : { start: start, end: end, text: text, code: code, category: category, source: source }; } @@ -89712,8 +90866,11 @@ var ts; _a[server.CommandNames.QuickinfoFull] = function (request) { return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); }, - _a[server.CommandNames.OutliningSpans] = function (request) { - return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); + _a[server.CommandNames.GetOutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, true)); + }, + _a[server.CommandNames.GetOutliningSpansFull] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, false)); }, _a[server.CommandNames.TodoComments] = function (request) { return _this.requiredResponse(_this.getTodoComments(request.arguments)); @@ -89791,6 +90948,9 @@ var ts; _a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments)); }, + _a[server.CommandNames.SuggestionDiagnosticsSync] = function (request) { + return _this.requiredResponse(_this.getSuggestionDiagnosticsSync(request.arguments)); + }, _a[server.CommandNames.Geterr] = function (request) { _this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); }); return _this.notRequired(); @@ -89907,6 +91067,7 @@ var ts; this.hrtime = opts.hrtime; this.logger = opts.logger; this.canUseEvents = opts.canUseEvents; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; var throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = this.canUseEvents ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); }) @@ -89929,6 +91090,7 @@ var ts; typingsInstaller: this.typingsInstaller, throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, + suppressDiagnosticEvents: this.suppressDiagnosticEvents, globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads @@ -89977,8 +91139,10 @@ var ts; 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); }); + if (!this.suppressDiagnosticEvents) { + var checkList_1 = this.createCheckList(openFiles); + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, true); }); + } this.event({ openFiles: openFiles }, "projectsUpdatedInBackground"); @@ -90029,52 +91193,57 @@ var ts; this.send(res); }; Session.prototype.semanticCheck = function (file, project) { - try { - var diags = server.emptyArray; - if (!isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { - diags = project.getLanguageService().getSemanticDiagnostics(file); - } - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); - } - catch (err) { - this.logError(err, "semantic check"); - } + var diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) + ? server.emptyArray + : project.getLanguageService().getSemanticDiagnostics(file); + this.sendDiagnosticsEvent(file, project, diags, "semanticDiag"); }; Session.prototype.syntacticCheck = function (file, project) { + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag"); + }; + Session.prototype.infoCheck = function (file, project) { + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); + }; + Session.prototype.sendDiagnosticsEvent = function (file, project, diagnostics, kind) { try { - var diags = project.getLanguageService().getSyntacticDiagnostics(file); - if (diags) { - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); - } + this.event({ file: file, diagnostics: diagnostics.map(function (diag) { return formatDiag(file, project, diag); }) }, kind); } catch (err) { - this.logError(err, "syntactic check"); + this.logError(err, kind); } }; Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { var _this = this; if (requireOpen === void 0) { requireOpen = true; } + ts.Debug.assert(!this.suppressDiagnosticEvents); var seq = this.changeSeq; var followMs = Math.min(ms, 200); var index = 0; var checkOne = function () { - if (_this.changeSeq === seq) { - var checkSpec_1 = checkList[index]; - index++; - if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { - _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - if (_this.changeSeq === seq) { - next.immediate(function () { - _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); - if (checkList.length > index) { - next.delay(followMs, checkOne); - } - }); - } - } + if (_this.changeSeq !== seq) { + return; } + var _a = checkList[index], fileName = _a.fileName, project = _a.project; + index++; + if (!project.containsFile(fileName, requireOpen)) { + return; + } + _this.syntacticCheck(fileName, project); + if (_this.changeSeq !== seq) { + return; + } + next.immediate(function () { + _this.semanticCheck(fileName, project); + if (_this.changeSeq !== seq) { + return; + } + next.immediate(function () { + _this.infoCheck(fileName, project); + if (checkList.length > index) { + next.delay(followMs, checkOne); + } + }); + }); }; if (checkList.length > index && this.changeSeq === seq) { next.delay(ms, checkOne); @@ -90128,7 +91297,7 @@ var ts; message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), start: d.start, length: d.length, - category: ts.DiagnosticCategory[d.category].toLowerCase(), + category: ts.diagnosticCategoryName(d), code: d.code, startLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start)), endLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length)) @@ -90144,7 +91313,7 @@ var ts; message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), start: d.start, length: d.length, - category: ts.DiagnosticCategory[d.category].toLowerCase(), + category: ts.diagnosticCategoryName(d), code: d.code, source: d.source, startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), @@ -90270,6 +91439,13 @@ var ts; } return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; + Session.prototype.getSuggestionDiagnosticsSync = function (args) { + var configFile = this.getConfigFileAndProject(args).configFile; + if (configFile) { + return server.emptyArray; + } + return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, args.includeLinePosition); + }; Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); @@ -90516,9 +91692,22 @@ var ts; var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, true); return { file: file, project: project }; }; - Session.prototype.getOutliningSpans = function (args) { + Session.prototype.getOutliningSpans = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; - return languageService.getOutliningSpans(file); + var spans = languageService.getOutliningSpans(file); + if (simplifiedResult) { + var scriptInfo_1 = this.projectService.getScriptInfoForNormalizedPath(file); + return spans.map(function (s) { return ({ + textSpan: _this.toLocationTextSpan(s.textSpan, scriptInfo_1), + hintSpan: _this.toLocationTextSpan(s.hintSpan, scriptInfo_1), + bannerText: s.bannerText, + autoCollapse: s.autoCollapse + }); }); + } + else { + return spans; + } }; Session.prototype.getTodoComments = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; @@ -90538,7 +91727,7 @@ var ts; Session.prototype.getIndentation = function (args) { 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 options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); var indentation = languageService.getIndentationAtPosition(file, position, options); return { position: position, indentation: indentation }; }; @@ -90587,7 +91776,7 @@ var ts; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file)); if (!edits) { return undefined; } @@ -90595,24 +91784,24 @@ var ts; }; Session.prototype.getFormattingEditsForRangeFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; - var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); }; Session.prototype.getFormattingEditsForDocumentFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; - var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsForDocument(file, options); }; Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; - var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); }; Session.prototype.getFormattingEditsAfterKeystroke = function (args) { 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 formatOptions = this.getFormatOptions(file); 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; @@ -90657,7 +91846,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, args); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { @@ -90679,7 +91868,7 @@ var ts; 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 project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file)); }); return simplifiedResult ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(project, action); }) })); }) @@ -90726,12 +91915,12 @@ var ts; return undefined; } if (simplifiedResult) { - var span_16 = helpItems.applicableSpan; + var span = helpItems.applicableSpan; return { items: helpItems.items, applicableSpan: { - start: scriptInfo.positionToLineOffset(span_16.start), - end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(span.start + span.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, @@ -90751,6 +91940,9 @@ var ts; }); }; Session.prototype.getDiagnostics = function (next, delay, fileNames) { + if (this.suppressDiagnosticEvents) { + return; + } var checkList = this.createCheckList(fileNames); if (checkList.length > 0) { this.updateErrorCheck(next, checkList, delay); @@ -90917,7 +92109,7 @@ var ts; return locationOrSpan.line !== undefined; }; Session.prototype.extractPositionAndRange = function (args, scriptInfo) { - var position = undefined; + var position; var textRange; if (this.isLocation(args)) { position = getPosition(args); @@ -90935,13 +92127,13 @@ var ts; 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); + return project.getLanguageService().getApplicableRefactors(file, position || textRange, this.getPreferences(file)); }; Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { 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, this.projectService.getFormatCodeOptions(file), position || textRange, args.refactor, args.action); + var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), position || textRange, args.refactor, args.action, this.getPreferences(file)); if (result === undefined) { return { edits: [] @@ -90964,8 +92156,7 @@ var ts; var scope = _a.scope; ts.Debug.assert(scope.type === "file"); var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; - var formatOptions = this.projectService.getFormatCodeOptions(file); - var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, formatOptions); + var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(project, changes); } @@ -90981,8 +92172,7 @@ var ts; 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); - var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); if (!codeActions) { return undefined; } @@ -90997,8 +92187,7 @@ var ts; var scope = _a.scope, fixId = _a.fixId; ts.Debug.assert(scope.type === "file"); var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; - var formatOptions = this.projectService.getFormatCodeOptions(file); - var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, formatOptions); + var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return { changes: this.mapTextChangesToCodeEdits(project, res.changes), commands: res.commands }; } @@ -91016,7 +92205,7 @@ var ts; return {}; }; Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { - var startPosition = undefined, endPosition = undefined; + var startPosition, endPosition; if (args.startPosition !== undefined) { startPosition = args.startPosition; } @@ -91035,9 +92224,9 @@ var ts; }; Session.prototype.mapCodeAction = function (project, _a) { var _this = this; - var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands, fixId = _a.fixId; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands, fixId = _a.fixId, fixAllDescription = _a.fixAllDescription; var changes = unmappedChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); - return { description: description, changes: changes, commands: commands, fixId: fixId }; + return { description: description, changes: changes, commands: commands, fixId: fixId, fixAllDescription: fixAllDescription }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; @@ -91070,6 +92259,9 @@ var ts; : spans; }; Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { + if (this.suppressDiagnosticEvents) { + return; + } var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; @@ -91193,6 +92385,12 @@ var ts; this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack); } }; + Session.prototype.getFormatOptions = function (file) { + return this.projectService.getFormatCodeOptions(file); + }; + Session.prototype.getPreferences = function (file) { + return this.projectService.getPreferences(file); + }; return Session; }()); server.Session = Session; @@ -92012,7 +93210,7 @@ var ts; }; Logger.prototype.close = function () { if (this.fd >= 0) { - fs.close(this.fd); + fs.close(this.fd, ts.noop); } }; Logger.prototype.getLogFileName = function () { @@ -92293,9 +93491,8 @@ var ts; }()); var IOSession = (function (_super) { __extends(IOSession, _super); - function IOSession(options) { + function IOSession() { var _this = this; - 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); @@ -92304,9 +93501,10 @@ var ts; setImmediate(function () { return _this.event(body, eventName); }); } }; + var host = sys; var typingsInstaller = disableAutomaticTypingAcquisition ? undefined - : new NodeTypingsInstaller(telemetryEnabled, logger, host, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, event); + : new NodeTypingsInstaller(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, event); _this = _super.call(this, { host: host, cancellationToken: cancellationToken, @@ -92316,10 +93514,11 @@ var ts; byteLength: Buffer.byteLength, hrtime: process.hrtime, logger: logger, - canUseEvents: canUseEvents, - globalPlugins: options.globalPlugins, - pluginProbeLocations: options.pluginProbeLocations, - allowLocalPluginLoads: options.allowLocalPluginLoads + canUseEvents: true, + suppressDiagnosticEvents: suppressDiagnosticEvents, + globalPlugins: globalPlugins, + pluginProbeLocations: pluginProbeLocations, + allowLocalPluginLoads: allowLocalPluginLoads, }) || this; _this.eventPort = eventPort; if (_this.canUseEvents && _this.eventPort) { @@ -92447,7 +93646,7 @@ var ts; if (err) { if (err.code === "ENOENT") { if (watchedFile.mtime.getTime() !== 0) { - watchedFile.mtime = new Date(0); + watchedFile.mtime = ts.missingFileModifiedTime; watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Deleted); } } @@ -92456,17 +93655,7 @@ var ts; } } else { - var oldTime = watchedFile.mtime.getTime(); - var newTime = stats.mtime.getTime(); - if (oldTime !== newTime) { - watchedFile.mtime = stats.mtime; - var eventKind = oldTime === 0 - ? ts.FileWatcherEventKind.Created - : newTime === 0 - ? ts.FileWatcherEventKind.Deleted - : ts.FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); - } + ts.onWatchedFileStat(watchedFile, stats.mtime); } }); } @@ -92495,7 +93684,7 @@ var ts; callback: callback, mtime: sys.fileExists(fileName) ? getModifiedTime(fileName) - : new Date(0) + : ts.missingFileModifiedTime }; watchedFiles.push(file); if (watchedFiles.length === 1) { @@ -92665,30 +93854,13 @@ var ts; var useSingleInferredProject = server.hasArgument("--useSingleInferredProject"); var useInferredProjectPerProjectRoot = server.hasArgument("--useInferredProjectPerProjectRoot"); var disableAutomaticTypingAcquisition = server.hasArgument("--disableAutomaticTypingAcquisition"); + var suppressDiagnosticEvents = server.hasArgument("--suppressDiagnosticEvents"); var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); - var options = { - host: sys, - cancellationToken: cancellationToken, - eventPort: eventPort, - canUseEvents: true, - useSingleInferredProject: useSingleInferredProject, - useInferredProjectPerProjectRoot: useInferredProjectPerProjectRoot, - disableAutomaticTypingAcquisition: disableAutomaticTypingAcquisition, - globalTypingsCacheLocation: getGlobalTypingsCacheLocation(), - typingSafeListLocation: typingSafeListLocation, - typesMapLocation: typesMapLocation, - npmLocation: npmLocation, - telemetryEnabled: telemetryEnabled, - logger: logger, - globalPlugins: globalPlugins, - pluginProbeLocations: pluginProbeLocations, - allowLocalPluginLoads: allowLocalPluginLoads - }; logger.info("Starting TS Server"); logger.info("Version: " + ts.version); logger.info("Arguments: " + process.argv.join(" ")); logger.info("Platform: " + os.platform() + " NodeVersion: " + nodeVersion + " CaseSensitive: " + sys.useCaseSensitiveFileNames); - var ioSession = new IOSession(options); + var ioSession = new IOSession(); process.on("uncaughtException", function (err) { ioSession.logError(err, "unknown"); }); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 8739616ce14..7a121848f47 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -59,7 +59,8 @@ 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; + 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.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -389,7 +390,7 @@ declare namespace ts { FirstJSDocNode = 274, LastJSDocNode = 292, FirstJSDocTagNode = 284, - LastJSDocTagNode = 292, + LastJSDocTagNode = 292 } enum NodeFlags { None = 0, @@ -417,7 +418,7 @@ declare namespace ts { ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, ContextFlags = 6387712, - TypeExcludesFlags = 20480, + TypeExcludesFlags = 20480 } enum ModifierFlags { None = 0, @@ -438,6 +439,7 @@ declare namespace ts { NonPublicAccessibilityModifier = 24, TypeScriptModifier = 2270, ExportDefault = 513, + All = 3071 } enum JsxFlags { None = 0, @@ -445,7 +447,7 @@ declare namespace ts { IntrinsicNamedElement = 1, /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - IntrinsicElement = 3, + IntrinsicElement = 3 } interface Node extends TextRange { kind: SyntaxKind; @@ -643,8 +645,9 @@ declare namespace ts { questionToken?: QuestionToken; body?: Block | Expression; } - type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; + /** @deprecated Use SignatureDeclaration */ + type FunctionLike = SignatureDeclaration; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -652,7 +655,7 @@ declare namespace ts { } interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; - parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + parent?: ObjectTypeDeclaration; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { @@ -686,7 +689,7 @@ declare namespace ts { type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + parent?: ObjectTypeDeclaration; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -1078,11 +1081,13 @@ declare namespace ts { kind: SyntaxKind.JsxOpeningElement; parent?: JsxElement; tagName: JsxTagNameExpression; + typeArguments?: NodeArray; attributes: JsxAttributes; } interface JsxSelfClosingElement extends PrimaryExpression { kind: SyntaxKind.JsxSelfClosingElement; tagName: JsxTagNameExpression; + typeArguments?: NodeArray; attributes: JsxAttributes; } interface JsxFragment extends PrimaryExpression { @@ -1261,6 +1266,7 @@ declare namespace ts { variableDeclaration?: VariableDeclaration; block: Block; } + type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; @@ -1553,7 +1559,7 @@ declare namespace ts { PreFinally = 2048, AfterFinally = 4096, Label = 12, - Condition = 96, + Condition = 96 } interface FlowLock { locked?: boolean; @@ -1725,7 +1731,7 @@ declare namespace ts { enum ExitStatus { Success = 0, DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, + DiagnosticsPresent_OutputsGenerated = 2 } interface EmitResult { emitSkipped: boolean; @@ -1750,9 +1756,9 @@ declare namespace ts { /** 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 & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; - } | undefined; + }) | undefined; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ @@ -1801,7 +1807,7 @@ declare namespace ts { */ getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; - isImplementationOfOverload(node: FunctionLike): boolean | undefined; + isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; @@ -1811,7 +1817,7 @@ declare namespace ts { getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; - getJsxIntrinsicTagNames(): Symbol[]; + getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; @@ -1847,7 +1853,7 @@ declare namespace ts { InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, - InReverseMappedType = 33554432, + InReverseMappedType = 33554432 } enum TypeFormatFlags { None = 0, @@ -1870,14 +1876,14 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469291, + NodeBuilderFlagsMask = 9469291 } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8, + UseAliasDefinedOutsideCurrentScope = 8 } /** * @deprecated @@ -1914,7 +1920,7 @@ declare namespace ts { } enum TypePredicateKind { This = 0, - Identifier = 1, + Identifier = 1 } interface TypePredicateBase { kind: TypePredicateKind; @@ -1960,28 +1966,28 @@ declare namespace ts { JSContainer = 67108864, Enum = 384, Variable = 3, - Value = 107455, - Type = 793064, + Value = 67216319, + Type = 67901928, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 107454, - BlockScopedVariableExcludes = 107455, - ParameterExcludes = 107455, + FunctionScopedVariableExcludes = 67216318, + BlockScopedVariableExcludes = 67216319, + ParameterExcludes = 67216319, PropertyExcludes = 0, - EnumMemberExcludes = 900095, - FunctionExcludes = 106927, - ClassExcludes = 899519, - InterfaceExcludes = 792968, - RegularEnumExcludes = 899327, - ConstEnumExcludes = 899967, - ValueModuleExcludes = 106639, + EnumMemberExcludes = 68008959, + FunctionExcludes = 67215791, + ClassExcludes = 68008383, + InterfaceExcludes = 67901832, + RegularEnumExcludes = 68008191, + ConstEnumExcludes = 68008831, + ValueModuleExcludes = 67215503, NamespaceModuleExcludes = 0, - MethodExcludes = 99263, - GetAccessorExcludes = 41919, - SetAccessorExcludes = 74687, - TypeParameterExcludes = 530920, - TypeAliasExcludes = 793064, + MethodExcludes = 67208127, + GetAccessorExcludes = 67150783, + SetAccessorExcludes = 67183551, + TypeParameterExcludes = 67639784, + TypeAliasExcludes = 67901928, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -1989,7 +1995,7 @@ declare namespace ts { HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500, + ClassMember = 106500 } interface Symbol { flags: SymbolFlags; @@ -2016,7 +2022,7 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default", + Default = "default" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2091,7 +2097,7 @@ declare namespace ts { Instantiable = 7897088, StructuredOrInstantiable = 8355840, Narrowable = 142575359, - NotUnionOrUnit = 134283777, + NotUnionOrUnit = 134283777 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2132,7 +2138,7 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, - ClassOrInterface = 3, + ClassOrInterface = 3 } interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2189,31 +2195,46 @@ declare namespace ts { indexType: Type; constraint?: Type; } + type TypeVariable = TypeParameter | IndexedAccessType; interface IndexType extends InstantiableType { type: InstantiableType | UnionOrIntersectionType; } - interface ConditionalType extends InstantiableType { + interface ConditionalRoot { + node: ConditionalTypeNode; checkType: Type; extendsType: Type; trueType: Type; falseType: Type; + isDistributive: boolean; + inferTypeParameters: TypeParameter[]; + outerTypeParameters?: TypeParameter[]; + instantiations?: Map; + aliasSymbol: Symbol; + aliasTypeArguments: Type[]; + } + interface ConditionalType extends InstantiableType { + root: ConditionalRoot; + checkType: Type; + extendsType: Type; + resolvedTrueType?: Type; + resolvedFalseType?: Type; } interface SubstitutionType extends InstantiableType { - typeParameter: TypeParameter; + typeVariable: TypeVariable; substitute: Type; } enum SignatureKind { Call = 0, - Construct = 1, + Construct = 1 } interface Signature { - declaration: SignatureDeclaration; + declaration?: SignatureDeclaration; typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { String = 0, - Number = 1, + Number = 1 } interface IndexInfo { type: Type; @@ -2222,41 +2243,14 @@ declare namespace ts { } enum InferencePriority { NakedTypeVariable = 1, - MappedType = 2, - ReturnType = 4, - NoConstraints = 8, - AlwaysStrict = 16, + HomomorphicMappedType = 2, + MappedTypeConstraint = 4, + ReturnType = 8, + LiteralKeyof = 16, + NoConstraints = 32, + AlwaysStrict = 64, + PriorityImpliesCombination = 28 } - interface InferenceInfo { - typeParameter: TypeParameter; - candidates: Type[]; - contraCandidates: Type[]; - inferredType: Type; - priority: InferencePriority; - topLevel: boolean; - isFixed: boolean; - } - enum InferenceFlags { - None = 0, - InferUnionTypes = 1, - NoDefault = 2, - AnyDefault = 4, - } - /** - * 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, - } - type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2292,11 +2286,12 @@ declare namespace ts { enum DiagnosticCategory { Warning = 0, Error = 1, - Message = 2, + Suggestion = 2, + Message = 3 } enum ModuleResolutionKind { Classic = 1, - NodeJs = 2, + NodeJs = 2 } interface PluginImport { name: string; @@ -2312,6 +2307,7 @@ declare namespace ts { charset?: string; checkJs?: boolean; declaration?: boolean; + declarationMap?: boolean; emitDeclarationOnly?: boolean; declarationDir?: string; disableSizeLimit?: boolean; @@ -2390,17 +2386,17 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6, + ESNext = 6 } enum JsxEmit { None = 0, Preserve = 1, React = 2, - ReactNative = 3, + ReactNative = 3 } enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1, + LineFeed = 1 } interface LineAndCharacter { /** 0-based. */ @@ -2414,7 +2410,7 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, - JSON = 6, + JSON = 6 } enum ScriptTarget { ES3 = 0, @@ -2424,11 +2420,11 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, - Latest = 6, + Latest = 6 } enum LanguageVariant { Standard = 0, - JSX = 1, + JSX = 1 } /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { @@ -2442,7 +2438,7 @@ declare namespace ts { } enum WatchDirectoryFlags { None = 0, - Recursive = 1, + Recursive = 1 } interface ExpandResult { fileNames: string[]; @@ -2512,7 +2508,7 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", - Json = ".json", + Json = ".json" } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; @@ -2582,7 +2578,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216, + NoAsciiEscaping = 16777216 } interface EmitHelper { readonly name: string; @@ -2595,7 +2591,7 @@ declare namespace ts { Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4, + Unspecified = 4 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2762,6 +2758,7 @@ declare namespace ts { newLine?: NewLineKind; omitTrailingSemicolon?: boolean; } + /** @deprecated See comment on SymbolWriter */ interface SymbolTracker { trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError?(): void; @@ -2812,9 +2809,9 @@ declare namespace ts { SingleElement = 524288, Modifiers = 131328, HeritageClauses = 256, - SingleLineTypeLiteralMembers = 448, - MultiLineTypeLiteralMembers = 65, - TupleTypeElements = 336, + SingleLineTypeLiteralMembers = 384, + MultiLineTypeLiteralMembers = 16449, + TupleTypeElements = 272, UnionTypeConstituents = 260, IntersectionTypeConstituents = 264, ObjectBindingPatternElements = 262576, @@ -2830,12 +2827,12 @@ declare namespace ts { VariableDeclarationList = 272, SingleLineFunctionBodyStatements = 384, MultiLineFunctionBodyStatements = 1, - ClassHeritageClauses = 256, + ClassHeritageClauses = 0, ClassMembers = 65, InterfaceMembers = 65, EnumMembers = 81, CaseBlockClauses = 65, - NamedImportsOrExportsElements = 432, + NamedImportsOrExportsElements = 262576, JsxElementOrFragmentChildren = 131072, JsxElementAttributes = 131328, CaseOrDefaultClauseStatements = 81985, @@ -2845,11 +2842,11 @@ declare namespace ts { TypeArguments = 26896, TypeParameters = 26896, Parameters = 1296, - IndexSignatureParameters = 4432, + IndexSignatureParameters = 4432 } } declare namespace ts { - const versionMajorMinor = "2.8"; + const versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ const version: string; } @@ -2863,15 +2860,10 @@ declare namespace ts { enum FileWatcherEventKind { Created = 0, Changed = 1, - Deleted = 2, + Deleted = 2 } type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; - interface WatchedFile { - fileName: string; - callback: FileWatcherCallback; - mtime?: Date; - } interface System { args: string[]; newLine: string; @@ -2906,6 +2898,8 @@ declare namespace ts { setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; clearScreen?(): void; + base64decode?(input: string): string; + base64encode?(input: string): string; } interface FileWatcher { close(): void; @@ -3011,7 +3005,7 @@ declare namespace ts { * 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; + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -3049,9 +3043,9 @@ 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; + function getJSDocTags(node: Node): ReadonlyArray; /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ - function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3205,6 +3199,7 @@ declare namespace ts { function isJSDocVariadicType(node: Node): node is JSDocVariadicType; function isJSDoc(node: Node): node is JSDoc; function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocClassTag(node: Node): node is JSDocClassTag; function isJSDocParameterTag(node: Node): node is JSDocParameterTag; function isJSDocReturnTag(node: Node): node is JSDocReturnTag; function isJSDocTypeTag(node: Node): node is JSDocTypeTag; @@ -3228,7 +3223,7 @@ declare namespace ts { function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node): node is FunctionLike; + function isFunctionLike(node: Node): node is SignatureDeclaration; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; @@ -3246,7 +3241,8 @@ declare namespace ts { function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; function isTemplateLiteral(node: Node): node is TemplateLiteral; function isAssertionExpression(node: Node): node is AssertionExpression; - function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; 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. */ @@ -3275,8 +3271,8 @@ declare namespace ts { reScanTemplateToken(): SyntaxKind; scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): SyntaxKind; - scanJsxToken(): SyntaxKind; + reScanJsxToken(): JsxTokenSyntaxKind; + scanJsxToken(): JsxTokenSyntaxKind; scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; @@ -3290,7 +3286,7 @@ declare namespace ts { tryScan(callback: () => T): T; } function tokenToString(t: SyntaxKind): string | undefined; - function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; + function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, 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. */ @@ -3451,6 +3447,8 @@ declare namespace ts { function createLoopVariable(): Identifier; /** Create a unique name based on the supplied text. */ function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; /** Create a unique name generated for a node. */ function getGeneratedNameForNode(node: Node): Identifier; function createToken(token: TKind): Token; @@ -3459,6 +3457,8 @@ declare namespace ts { function createNull(): NullLiteral & Token; function createTrue(): BooleanLiteral & Token; function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; @@ -3659,7 +3659,7 @@ declare namespace ts { function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; @@ -3681,10 +3681,10 @@ declare namespace ts { function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; - function createJsxSelfClosingElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; - function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; - function createJsxOpeningElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; - function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; + function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; @@ -3713,7 +3713,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; 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; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ @@ -4080,10 +4080,17 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; } + interface UserPreferences { + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + } interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): Diagnostic[]; getSemanticDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): Diagnostic[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. @@ -4096,7 +4103,7 @@ declare namespace ts { getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, name: string, options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined): CompletionEntryDetails; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | 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; @@ -4126,8 +4133,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; - getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4137,9 +4144,9 @@ declare namespace ts { 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; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings): ReadonlyArray; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -4149,9 +4156,12 @@ declare namespace ts { fileName: string; } type OrganizeImportsScope = CombinedCodeFixScope; - interface GetCompletionsAtPositionOptions { - includeExternalModuleExports: boolean; - includeInsertTextCompletions: boolean; + /** @deprecated Use UserPreferences */ + interface GetCompletionsAtPositionOptions extends UserPreferences { + /** @deprecated Use includeCompletionsForModuleExports */ + includeExternalModuleExports?: boolean; + /** @deprecated Use includeCompletionsWithInsertText */ + includeInsertTextCompletions?: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4232,6 +4242,7 @@ declare namespace ts { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + fixAllDescription?: string; } interface CombinedCodeActions { changes: ReadonlyArray; @@ -4317,7 +4328,7 @@ declare namespace ts { none = "none", definition = "definition", reference = "reference", - writtenReference = "writtenReference", + writtenReference = "writtenReference" } interface HighlightSpan { fileName?: string; @@ -4339,7 +4350,7 @@ declare namespace ts { enum IndentStyle { None = 0, Block = 1, - Smart = 2, + Smart = 2 } interface EditorOptions { BaseIndentSize?: number; @@ -4434,7 +4445,7 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21, + regularExpressionLiteral = 21 } interface SymbolDisplayPart { text: string; @@ -4494,7 +4505,7 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { - /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isGlobalCompletionScope`. */ + /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */ isGlobalCompletion: boolean; isMemberCompletion: boolean; /** @@ -4545,7 +4556,7 @@ declare namespace ts { enum OutputFileType { JavaScript = 0, SourceMap = 1, - Declaration = 2, + Declaration = 2 } enum EndOfLineState { None = 0, @@ -4554,7 +4565,7 @@ declare namespace ts { InDoubleQuoteStringLiteral = 3, InTemplateHeadOrNoSubstitutionTemplate = 4, InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, + InTemplateSubstitutionPosition = 6 } enum TokenClass { Punctuation = 0, @@ -4565,7 +4576,7 @@ declare namespace ts { Identifier = 5, NumberLiteral = 6, StringLiteral = 7, - RegExpLiteral = 8, + RegExpLiteral = 8 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -4664,7 +4675,7 @@ declare namespace ts { /** * */ - jsxAttribute = "JSX attribute", + jsxAttribute = "JSX attribute" } enum ScriptElementKindModifier { none = "", @@ -4675,7 +4686,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional", + optionalModifier = "optional" } enum ClassificationTypeNames { comment = "comment", @@ -4700,7 +4711,7 @@ declare namespace ts { jsxSelfClosingTagName = "jsx self closing tag name", jsxAttribute = "jsx attribute", jsxText = "jsx text", - jsxAttributeStringLiteralValue = "jsx attribute string literal value", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" } enum ClassificationType { comment = 1, @@ -4726,7 +4737,7 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24, + jsxAttributeStringLiteralValue = 24 } } declare namespace ts { @@ -4820,7 +4831,7 @@ declare namespace ts { } declare namespace ts { /** The version of the language service API */ - const servicesVersion = "0.7"; + const servicesVersion = "0.8"; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; @@ -4964,7 +4975,7 @@ declare namespace ts.server { terse = 0, normal = 1, requestTime = 2, - verbose = 3, + verbose = 3 } const emptyArray: SortedReadonlyArray; interface Logger { @@ -4981,7 +4992,7 @@ declare namespace ts.server { enum Msg { Err = "Err", Info = "Info", - Perf = "Perf", + Perf = "Perf" } namespace Msg { /** @deprecated Only here for backwards-compatibility. Prefer just `Msg`. */ @@ -4994,7 +5005,7 @@ declare namespace ts.server { function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; } function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings; - function mergeMapLikes(target: MapLike, source: MapLike): void; + function mergeMapLikes(target: T, source: Partial): void; type NormalizedPath = string & { __normalizedPathTag: any; }; @@ -5054,10 +5065,12 @@ declare namespace ts.server.protocol { GeterrForProject = "geterrForProject", SemanticDiagnosticsSync = "semanticDiagnosticsSync", SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", NavBar = "navbar", Navto = "navto", NavTree = "navtree", NavTreeFull = "navtree-full", + /** @deprecated */ Occurrences = "occurrences", DocumentHighlights = "documentHighlights", Open = "open", @@ -5075,6 +5088,7 @@ declare namespace ts.server.protocol { OpenExternalProject = "openExternalProject", OpenExternalProjects = "openExternalProjects", CloseExternalProject = "closeExternalProject", + GetOutliningSpans = "getOutliningSpans", TodoComments = "todoComments", Indentation = "indentation", DocCommentTemplate = "docCommentTemplate", @@ -5085,7 +5099,7 @@ declare namespace ts.server.protocol { GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", - OrganizeImports = "organizeImports", + OrganizeImports = "organizeImports" } /** * A TypeScript Server message @@ -5233,6 +5247,31 @@ declare namespace ts.server.protocol { */ onlyMultiLine: boolean; } + /** + * Request to obtain outlining spans in file. + */ + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.GetOutliningSpans; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + } + /** + * Response to OutliningSpansRequest request. + */ + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } /** * A request to get indentation for a location in file */ @@ -5658,6 +5697,7 @@ declare namespace ts.server.protocol { openingBrace: string; } /** + * @deprecated * Get occurrences request; value of command field is * "occurrences". Return response giving spans that are relevant * in the file at a given line and column. @@ -5665,6 +5705,7 @@ declare namespace ts.server.protocol { interface OccurrencesRequest extends FileLocationRequest { command: CommandTypes.Occurrences; } + /** @deprecated */ interface OccurrencesResponseItem extends FileSpan { /** * True if the occurrence is a write location, false otherwise. @@ -5675,6 +5716,7 @@ declare namespace ts.server.protocol { */ isInString?: true; } + /** @deprecated */ interface OccurrencesResponse extends Response { body?: OccurrencesResponseItem[]; } @@ -5937,6 +5979,7 @@ declare namespace ts.server.protocol { * The format options to use during formatting and other code editing features. */ formatOptions?: FormatCodeSettings; + preferences?: UserPreferences; /** * The host's additional supported .js file extensions */ @@ -6271,6 +6314,8 @@ declare namespace ts.server.protocol { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; } /** * Format and format on key response message. @@ -6309,15 +6354,13 @@ declare namespace ts.server.protocol { */ 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.`. + * @deprecated Use UserPreferences.includeCompletionsForModuleExports */ - includeExternalModuleExports: boolean; + 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"]`. + * @deprecated Use UserPreferences.includeCompletionsWithInsertText */ - includeInsertTextCompletions: boolean; + includeInsertTextCompletions?: boolean; } /** * Completions request; value of command field is "completions". @@ -6572,6 +6615,12 @@ declare namespace ts.server.protocol { interface SemanticDiagnosticsSyncResponse extends Response { body?: Diagnostic[] | DiagnosticWithLinePosition[]; } + interface SuggestionDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SuggestionDiagnosticsSync; + arguments: SuggestionDiagnosticsSyncRequestArgs; + } + type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; + type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; /** * Synchronous request for syntactic diagnostics of one file. */ @@ -6668,7 +6717,7 @@ declare namespace ts.server.protocol { */ text: string; /** - * The category of the diagnostic message, e.g. "error" vs. "warning" + * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". */ category: string; /** @@ -6696,8 +6745,9 @@ declare namespace ts.server.protocol { */ diagnostics: Diagnostic[]; } + type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; /** - * Event message for "syntaxDiag" and "semanticDiag" event types. + * Event message for DiagnosticEventKind event types. * These events provide syntactic and semantic errors for a file. */ interface DiagnosticEvent extends Event { @@ -7039,7 +7089,7 @@ declare namespace ts.server.protocol { enum IndentStyle { None = "None", Block = "Block", - Smart = "Smart", + Smart = "Smart" } interface EditorSettings { baseIndentSize?: number; @@ -7067,6 +7117,20 @@ declare namespace ts.server.protocol { placeOpenBraceOnNewLineForControlBlocks?: boolean; insertSpaceBeforeTypeAnnotation?: boolean; } + interface UserPreferences { + readonly quotePreference?: "double" | "single"; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + readonly includeCompletionsForModuleExports?: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + } interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -7140,7 +7204,7 @@ declare namespace ts.server.protocol { None = "None", Preserve = "Preserve", ReactNative = "ReactNative", - React = "React", + React = "React" } enum ModuleKind { None = "None", @@ -7150,15 +7214,15 @@ declare namespace ts.server.protocol { System = "System", ES6 = "ES6", ES2015 = "ES2015", - ESNext = "ESNext", + ESNext = "ESNext" } enum ModuleResolutionKind { Classic = "Classic", - Node = "Node", + Node = "Node" } enum NewLineKind { Crlf = "Crlf", - Lf = "Lf", + Lf = "Lf" } enum ScriptTarget { ES3 = "ES3", @@ -7167,7 +7231,7 @@ declare namespace ts.server.protocol { ES2015 = "ES2015", ES2016 = "ES2016", ES2017 = "ES2017", - ESNext = "ESNext", + ESNext = "ESNext" } } declare namespace ts.server { @@ -7182,7 +7246,7 @@ declare namespace ts.server { } type CommandNames = protocol.CommandTypes; const CommandNames: any; - function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; + function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; type Event = (body: T, eventName: string) => void; interface EventSender { event: Event; @@ -7201,6 +7265,8 @@ declare namespace ts.server { */ canUseEvents: boolean; eventHandler?: ProjectServiceEventHandler; + /** Has no effect if eventHandler is also specified. */ + suppressDiagnosticEvents?: boolean; throttleWaitMilliseconds?: number; globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; @@ -7219,116 +7285,123 @@ declare namespace ts.server { private hrtime; protected logger: Logger; protected canUseEvents: boolean; + private suppressDiagnosticEvents?; private eventHandler; constructor(opts: SessionOptions); - private sendRequestCompletedEvent(requestId); - private defaultEventHandler(event); - private projectsUpdatedInBackgroundEvent(openFiles); + private sendRequestCompletedEvent; + private defaultEventHandler; + private projectsUpdatedInBackgroundEvent; logError(err: Error, cmd: string): void; send(msg: protocol.Message): 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 updateErrorCheck(next, checkList, ms, requireOpen?); - private cleanProjects(caption, projects); - private cleanup(); - private getEncodedSemanticClassifications(args); - private getProject(projectFileName); - private getConfigFileAndProject(args); - private getConfigFileDiagnostics(configFile, project, includeLinePosition); - private convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics); - private getCompilerOptionsDiagnostics(args); - 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); - private getSyntacticDiagnosticsSync(args); - private getSemanticDiagnosticsSync(args); - private getDocumentHighlights(args, simplifiedResult); - private setCompilerOptionsForInferredProjects(args); - private getProjectInfo(args); - private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles); - private getRenameInfo(args); - private getProjects(args); - private getDefaultProject(args); - private getRenameLocations(args, simplifiedResult); - private getReferences(args, simplifiedResult); + private doOutput; + private semanticCheck; + private syntacticCheck; + private infoCheck; + private sendDiagnosticsEvent; + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ + private updateErrorCheck; + private cleanProjects; + private cleanup; + private getEncodedSemanticClassifications; + private getProject; + private getConfigFileAndProject; + private getConfigFileDiagnostics; + private convertToDiagnosticsWithLinePositionFromDiagnosticFile; + private getCompilerOptionsDiagnostics; + private convertToDiagnosticsWithLinePosition; + private getDiagnosticsWorker; + private getDefinition; + private getDefinitionAndBoundSpan; + private mapDefinitionInfo; + private toFileSpan; + private getTypeDefinition; + private getImplementation; + private getOccurrences; + private getSyntacticDiagnosticsSync; + private getSemanticDiagnosticsSync; + private getSuggestionDiagnosticsSync; + private getDocumentHighlights; + private setCompilerOptionsForInferredProjects; + private getProjectInfo; + private getProjectInfoWorker; + private getRenameInfo; + private getProjects; + private getDefaultProject; + private getRenameLocations; + private getReferences; /** * @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 getPositionInFile(args, file); - private getFileAndProject(args); - private getFileAndLanguageServiceForSyntacticOperation(args); - private getFileAndProjectWorker(uncheckedFileName, projectFileName); - private getOutliningSpans(args); - private getTodoComments(args); - private getDocCommentTemplate(args); - private getSpanOfEnclosingComment(args); - private getIndentation(args); - private getBreakpointStatement(args); - private getNameOrDottedNameSpan(args); - private isValidBraceCompletion(args); - private getQuickInfoWorker(args, simplifiedResult); - private getFormattingEditsForRange(args); - private getFormattingEditsForRangeFull(args); - private getFormattingEditsForDocumentFull(args); - private getFormattingEditsAfterKeystrokeFull(args); - private getFormattingEditsAfterKeystroke(args); - private getCompletions(args, simplifiedResult); - 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 mapLocationNavigationBarItems(items, scriptInfo); - private getNavigationBarItems(args, simplifiedResult); - private toLocationNavigationTree(tree, scriptInfo); - private toLocationTextSpan(span, scriptInfo); - private getNavigationTree(args, simplifiedResult); - private getNavigateToItems(args, simplifiedResult); - private getSupportedCodeFixes(); - private isLocation(locationOrSpan); - private extractPositionAndRange(args, scriptInfo); - private getApplicableRefactors(args); - private getEditsForRefactor(args, simplifiedResult); - private organizeImports({scope}, simplifiedResult); - private getCodeFixes(args, simplifiedResult); - private getCombinedCodeFix({scope, fixId}, simplifiedResult); - private applyCodeActionCommand(args); - private getStartAndEndPosition(args, scriptInfo); - private mapCodeAction(project, {description, changes: unmappedChanges, commands, fixId}); - private mapTextChangesToCodeEdits(project, textChanges); - private mapTextChangesToCodeEditsUsingScriptinfo(textChanges, scriptInfo); - private convertTextChangeToCodeEdit(change, scriptInfo); - private getBraceMatching(args, simplifiedResult); - private getDiagnosticsForProject(next, delay, fileName); + private openClientFile; + private getPosition; + private getPositionInFile; + private getFileAndProject; + private getFileAndLanguageServiceForSyntacticOperation; + private getFileAndProjectWorker; + private getOutliningSpans; + private getTodoComments; + private getDocCommentTemplate; + private getSpanOfEnclosingComment; + private getIndentation; + private getBreakpointStatement; + private getNameOrDottedNameSpan; + private isValidBraceCompletion; + private getQuickInfoWorker; + private getFormattingEditsForRange; + private getFormattingEditsForRangeFull; + private getFormattingEditsForDocumentFull; + private getFormattingEditsAfterKeystrokeFull; + private getFormattingEditsAfterKeystroke; + private getCompletions; + private getCompletionEntryDetails; + private getCompileOnSaveAffectedFileList; + private emitFile; + private getSignatureHelpItems; + private createCheckList; + private getDiagnostics; + private change; + private reload; + private saveToTmp; + private closeClientFile; + private mapLocationNavigationBarItems; + private getNavigationBarItems; + private toLocationNavigationTree; + private toLocationTextSpan; + private getNavigationTree; + private getNavigateToItems; + private getSupportedCodeFixes; + private isLocation; + private extractPositionAndRange; + private getApplicableRefactors; + private getEditsForRefactor; + private organizeImports; + private getCodeFixes; + private getCombinedCodeFix; + private applyCodeActionCommand; + private getStartAndEndPosition; + private mapCodeAction; + private mapTextChangesToCodeEdits; + private mapTextChangesToCodeEditsUsingScriptinfo; + private convertTextChangeToCodeEdit; + private getBraceMatching; + private getDiagnosticsForProject; getCanonicalFileName(fileName: string): string; exit(): void; - private notRequired(); - private requiredResponse(response); + private notRequired; + private requiredResponse; private handlers; addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; - private setCurrentRequest(requestId); - private resetCurrentRequest(requestId); + private setCurrentRequest; + private resetCurrentRequest; executeWithRequestId(requestId: number, f: () => T): T; executeCommand(request: protocol.Request): HandlerResponse; onMessage(message: string): void; + private getFormatOptions; + private getPreferences; } interface HandlerResponse { response?: {}; @@ -7346,22 +7419,24 @@ declare namespace ts.server { * All projects that include this file */ readonly containingProjects: Project[]; - private formatCodeSettings; + private formatSettings; + private preferences; private textStorage; constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path); isScriptOpen(): boolean; open(newText: string): void; close(fileExists?: boolean): void; getSnapshot(): IScriptSnapshot; - private ensureRealPath(); + private ensureRealPath; getFormatCodeSettings(): FormatCodeSettings; + getPreferences(): UserPreferences; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; detachFromProject(project: Project): void; detachAllProjects(): void; getDefaultProject(): Project; registerFileUpdate(): void; - setFormatOptions(formatSettings: FormatCodeSettings): void; + setOptions(formatSettings: FormatCodeSettings, preferences: UserPreferences): void; getLatestVersion(): string; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): void; @@ -7422,7 +7497,7 @@ declare namespace ts.server { enum ProjectKind { Inferred = 0, Configured = 1, - External = 2, + External = 2 } function allRootFilesAreJsOrDts(project: Project): boolean; function allFilesAreJsOrDts(project: Project): boolean; @@ -7513,7 +7588,7 @@ declare namespace ts.server { getNewLine(): string; getProjectVersion(): string; getScriptFileNames(): string[]; - private getOrCreateScriptInfoAndAttachToProject(fileName); + private getOrCreateScriptInfoAndAttachToProject; getScriptKind(fileName: string): ScriptKind; getScriptVersion(filename: string): string; getScriptSnapshot(filename: string): IScriptSnapshot; @@ -7530,14 +7605,14 @@ declare namespace ts.server { getDirectories(path: string): string[]; log(s: string): void; error(s: string): void; - private setInternalCompilerOptionsForEmittingJsFiles(); + private setInternalCompilerOptionsForEmittingJsFiles; /** * Get the errors that dont have any file name associated */ getGlobalProjectErrors(): ReadonlyArray; getAllProjectErrors(): ReadonlyArray; getLanguageService(ensureSynchronized?: boolean): LanguageService; - private shouldEmitFile(scriptInfo); + private shouldEmitFile; getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; /** * Returns true if emit was conducted @@ -7551,7 +7626,7 @@ declare namespace ts.server { getExternalFiles(): SortedReadonlyArray; getSourceFile(path: Path): SourceFile; close(): void; - private detachScriptInfoIfNotRoot(uncheckedFilename); + private detachScriptInfoIfNotRoot; isClosed(): boolean; hasRoots(): boolean; getRootFiles(): NormalizedPath[]; @@ -7574,10 +7649,10 @@ declare namespace ts.server { */ updateGraph(): boolean; protected removeExistingTypings(include: string[]): string[]; - private updateGraphWorker(); - private detachScriptInfoFromProject(uncheckedFileName); - private addMissingFileWatcher(missingFilePath); - private isWatchedMissingFile(path); + private updateGraphWorker; + private detachScriptInfoFromProject; + private addMissingFileWatcher; + private isWatchedMissingFile; getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; getScriptInfo(uncheckedFileName: string): ScriptInfo; filesToString(writeProjectFileNames: boolean): string; @@ -7585,7 +7660,7 @@ declare namespace ts.server { protected removeRoot(info: ScriptInfo): void; protected enableGlobalPlugins(): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; - private enableProxy(pluginModuleFactory, configEntry); + private enableProxy; } /** * If a file is opened and no tsconfig (or jsconfig) is found, @@ -7739,6 +7814,7 @@ declare namespace ts.server { function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; + preferences: UserPreferences; hostInfo: string; extraFileExtensions?: JsFileExtensionInfo[]; } @@ -7754,6 +7830,7 @@ declare namespace ts.server { useInferredProjectPerProjectRoot: boolean; typingsInstaller: ITypingsInstaller; eventHandler?: ProjectServiceEventHandler; + suppressDiagnosticEvents?: boolean; throttleWaitMilliseconds?: number; globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; @@ -7820,6 +7897,7 @@ declare namespace ts.server { readonly typingsInstaller: ITypingsInstaller; readonly throttleWaitMilliseconds?: number; private readonly eventHandler?; + private readonly suppressDiagnosticEvents?; readonly globalPlugins: ReadonlyArray; readonly pluginProbeLocations: ReadonlyArray; readonly allowLocalPluginLoads: boolean; @@ -7827,14 +7905,13 @@ declare namespace ts.server { /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; constructor(opts: ProjectServiceOptions); - private createWatcherLog(watchType, project); toPath(fileName: string): Path; - private loadTypesMap(); + private loadTypesMap; updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; - private delayEnsureProjectForOpenFiles(); - private delayUpdateProjectGraph(project); - private sendProjectsUpdatedInBackgroundEvent(); - private delayUpdateProjectGraphs(projects); + private delayEnsureProjectForOpenFiles; + private delayUpdateProjectGraph; + private sendProjectsUpdatedInBackgroundEvent; + private delayUpdateProjectGraphs; setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void; findProject(projectName: string): Project | undefined; getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project; @@ -7846,47 +7923,48 @@ declare namespace ts.server { * - if updates reflect some change in structure or there was pending request to ensure projects for open files * ensure that each open script info has project */ - private ensureProjectStructuresUptoDate(); - private updateProjectIfDirty(project); - getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; - private onSourceFileChanged(fileName, eventKind); - private handleDeletedFile(info); - private onConfigChangedForConfiguredProject(project, eventKind); + private ensureProjectStructuresUptoDate; + private updateProjectIfDirty; + getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; + getPreferences(file: NormalizedPath): UserPreferences; + private onSourceFileChanged; + private handleDeletedFile; + private onConfigChangedForConfiguredProject; /** * 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 onConfigFileChangeForOpenScriptInfo; + private removeProject; /** * 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 deleteScriptInfo(info); - private configFileExists(configFileName, canonicalConfigFilePath, info); - private setConfigFileExistenceByNewConfiguredProject(project); + private closeOpenFile; + private deleteOrphanScriptInfoNotInAnyProject; + private deleteScriptInfo; + private configFileExists; + private setConfigFileExistenceByNewConfiguredProject; /** * 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); + private configFileExistenceImpactsRootOfInferredProject; + private setConfigFileExistenceInfoByClosedConfiguredProject; + private logConfigFileWatchUpdate; /** * Create the watcher for the configFileExistenceInfo */ - private createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); + private createConfigFileWatcherOfConfigFileExistence; /** * Close the config file watcher in the cached ConfigFileExistenceInfo * if there arent any open files that are root of inferred project */ - private closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + private closeConfigFileWatcherOfConfigFileExistenceInfo; /** * This is called on file close, so that we stop watching the config file for this script info */ - private stopWatchingConfigFilesForClosedScriptInfo(info); + private stopWatchingConfigFilesForClosedScriptInfo; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because @@ -7895,7 +7973,7 @@ declare namespace ts.server { * The server must start searching from the directory containing * the newly opened file. */ - private forEachConfigFileLocation(info, action, projectRootPath?); + private forEachConfigFileLocation; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because @@ -7904,31 +7982,31 @@ declare namespace ts.server { * 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, cachedDirectoryStructureHost); + private getConfigFileNameForFile; + private printProjects; + private findConfiguredProjectByProjectName; + private getConfiguredProjectByCanonicalConfigFilePath; + private findExternalProjectByProjectName; + private convertConfigFileContentToProjectOptions; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ - private getFilenameForExceededTotalSizeLimitForNonTsFiles(name, options, fileNames, propertyReader); - private createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles); - private sendProjectTelemetry(projectKey, project, projectOptions?); - 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(currentDirectory, isSingleInferredProject?, projectRootPath?); + private getFilenameForExceededTotalSizeLimitForNonTsFiles; + private createExternalProject; + private sendProjectTelemetry; + private addFilesToNonInferredProjectAndUpdateGraph; + private createConfiguredProject; + private updateNonInferredProjectFiles; + private updateNonInferredProject; + private sendConfigFileDiagEvent; + private getOrCreateInferredProjectForProjectRootPathIfEnabled; + private getOrCreateSingleInferredProjectIfEnabled; + private createInferredProject; getScriptInfo(uncheckedFileName: string): ScriptInfo; - private watchClosedScriptInfo(info); - private stopWatchingScriptInfo(info); + private watchClosedScriptInfo; + private stopWatchingScriptInfo; getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { fileExists(path: string): boolean; }): ScriptInfo; - private getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent?, scriptKind?, hasMixedContent?, hostToQueryFileExistsOn?); + private getOrCreateScriptInfoWorker; /** * 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 */ @@ -7941,7 +8019,7 @@ declare namespace ts.server { * This does not reload contents of open files from disk. But we could do that if needed */ reloadProjects(): void; - private delayReloadConfiguredProjectForFiles(configFileExistenceInfo, ignoreIfNotRootOfInferredProject); + private delayReloadConfiguredProjectForFiles; /** * 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 @@ -7949,11 +8027,11 @@ declare namespace ts.server { * 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); + private reloadConfiguredProjectForFiles; /** * Remove the root of inferred project if script info is part of another project */ - private removeRootOfInferredProjectIfNowPartOfOtherProject(info); + private removeRootOfInferredProjectIfNowPartOfOtherProject; /** * This function is to update the project structure for every inferred project. * It is called on the premise that all the configured projects are @@ -7961,27 +8039,27 @@ declare namespace ts.server { * 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 ensureProjectForOpenFiles(); + private ensureProjectForOpenFiles; /** * 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; - private findExternalProjetContainingOpenScriptInfo(info); + private findExternalProjetContainingOpenScriptInfo; 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 closeConfiguredProjectReferencedFromExternalProject(configFile); + private collectChanges; + private closeConfiguredProjectReferencedFromExternalProject; closeExternalProject(uncheckedFileName: string): void; openExternalProjects(projects: protocol.ExternalProject[]): void; /** Makes a filename safe to insert in a RegExp */ private static readonly filenameEscapeRegexp; - private static escapeFilenameForRegex(filename); + private static escapeFilenameForRegex; resetSafeList(): void; applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; openExternalProject(proj: protocol.ExternalProject): void; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index a75f0454587..35331332adf 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -41,7 +41,7 @@ var ts; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; })(Comparison = ts.Comparison || (ts.Comparison = {})); - // token > SyntaxKind.Identifer => token is a keyword + // token > SyntaxKind.Identifier => 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) { @@ -474,6 +474,7 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -500,6 +501,7 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["OptimisticUnique"] = 5] = "OptimisticUnique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; // Flags GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; @@ -729,32 +731,32 @@ var ts; SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // 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"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "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["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "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["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -949,11 +951,15 @@ var ts; var InferencePriority; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; - InferencePriority[InferencePriority["NoConstraints"] = 8] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 16] = "AlwaysStrict"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + /* @internal */ var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; @@ -970,6 +976,7 @@ var ts; * 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. */ + /* @internal */ var Ternary; (function (Ternary) { Ternary[Ternary["False"] = 0] = "False"; @@ -990,13 +997,23 @@ var ts; SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + // F.prototype = { ... } + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; - DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + /* @internal */ + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; @@ -1391,9 +1408,9 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; @@ -1409,12 +1426,12 @@ var ts; ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; @@ -1426,6 +1443,68 @@ var ts; ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + /* @internal */ + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + /** + * Triple slash comment of the form + * /// + */ + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + /** + * Single line comment of the form + * // @pragma-name argval1 argval2 + * or + * /// @pragma-name argval1 argval2 + */ + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + /** + * Multiline non-jsdoc pragma of the form + * /* @pragma-name argval1 argval2 * / + */ + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + /** + * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas` + */ + /* @internal */ + function _contextuallyTypePragmas(args) { + return args; + } + // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't + // fancy effectively defining it twice, once in value-space and once in type-space + /* @internal */ + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + }); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1526,7 +1605,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.8"; + ts.versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1546,6 +1625,10 @@ var ts; /* @internal */ (function (ts) { ts.emptyArray = []; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -2087,22 +2170,6 @@ var ts; }; } ts.singleIterator = singleIterator; - /** - * 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++) { - if (!f(array[i], i)) { - return [array.slice(0, i), array.slice(i)]; - } - } - return [array.slice(0), []]; - } - return undefined; - } - ts.span = span; /** * Maps contiguous spans of values with the same key. * @@ -2363,7 +2430,6 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2522,7 +2588,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return elementAt(array, 0); + return array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -2534,7 +2600,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return elementAt(array, -1); + return array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -2752,19 +2818,21 @@ var ts; } ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } var result = createMap(); 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); + result.set(makeKey(value), makeValue(value)); } return result; } ts.arrayToMap = arrayToMap; function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } 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; + result[makeKey(value)] = makeValue(value); } return result; } @@ -2773,6 +2841,20 @@ var ts; return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } ts.arrayToSet = arrayToSet; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -2830,15 +2912,6 @@ var ts; } } } - function group(values, getGroupId) { - var groupIdToGroup = createMultiMap(); - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - groupIdToGroup.add(getGroupId(value), value); - } - return arrayFrom(groupIdToGroup.values()); - } - ts.group = group; /** * Tests whether a value is an array. */ @@ -2958,7 +3031,6 @@ var ts; return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.formatStringFromArgs = formatStringFromArgs; - ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } @@ -3390,6 +3462,10 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAreDeclarationMapsEnabled(options) { + return !!(options.declaration && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined @@ -3809,7 +3885,6 @@ 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); }); @@ -3842,7 +3917,7 @@ var ts; } } }; - for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + for (var _i = 0, _b = sort(files, compareStringsCaseSensitive); _i < _b.length; _i++) { var current = _b[_i]; _loop_1(current); } @@ -3852,7 +3927,7 @@ var ts; return; } } - for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -3884,7 +3959,7 @@ var ts; // 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); })) { + if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -4289,7 +4364,7 @@ var ts; ts.matchedText = matchedText; /** Return the object corresponding to the best pattern to match `candidate`. */ function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; + var matchedValue; // use length of prefix as betterness criteria var longestMatchPrefixLength = -1; for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { @@ -4382,6 +4457,38 @@ var ts; return t === undefined ? undefined : [t]; } ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(ts || (ts = {})); /// var ts; @@ -4393,7 +4500,7 @@ var ts; */ /* @internal */ function setStackTraceLimit() { - if (Error.stackTraceLimit < 100) { + if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. Error.stackTraceLimit = 100; } } @@ -4404,6 +4511,314 @@ var ts; FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + /* @internal */ + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + function getPriorityValues(highPriorityValue) { + var mediumPriorityValue = highPriorityValue * 2; + var lowPriorityValue = mediumPriorityValue * 4; + return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; + } + function pollingInterval(watchPriority) { + return pollingIntervalsForPriority[watchPriority]; + } + var pollingIntervalsForPriority = getPriorityValues(250); + /* @internal */ + function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { + return host.watchFile(fileName, callback, pollingInterval(watchPriority)); + } + ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; + /* @internal */ + ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + function createPollingIntervalBasedLevels(levels) { + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + var _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + /* @internal */ + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + // Remove from watchedFiles + ts.unorderedRemoveItem(watchedFiles, file); + // Do not update polling interval queue since that will happen as part of polling + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + // Set the next polling index and timeout + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + // Always poll complete list of changedFilesInLastPoll + pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length); + // Finally do the actual polling of the queue + pollPollingIntervalQueue(queue); + // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue + // as pollPollingIntervalQueue wont schedule for next poll + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + // Max visit would be all elements of the queue + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + // Changed files go to changedFilesInLastPoll queue + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + // Restart unchangedPollCount for unchanged file and move to low polling interval queue + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from nextDefinedValueIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + /** + * Returns true if file status changed + */ + /*@internal*/ + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + var eventKind = oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + watchedFile.callback(watchedFile.fileName, eventKind); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + /** + * Watch the directory recursively using host provided method to watch child directories + * that means if this is recursive watcher, watch the children directories as well + * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) + */ + /*@internal*/ + function createRecursiveDirectoryWatcher(host) { + return createDirectoryWatcher; + /** + * Create the directory watcher for the dirPath. + */ + function createDirectoryWatcher(dirName, callback) { + var watcher = host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callback(fileName); + // Iterate through existing children and update the watches if needed + updateChildWatches(result, callback); + }); + var result = { + close: function () { + watcher.close(); + result.childWatches.forEach(ts.closeFileWatcher); + result = undefined; + }, + dirName: dirName, + childWatches: ts.emptyArray + }; + updateChildWatches(result, callback); + return result; + } + function updateChildWatches(watcher, callback) { + // Iterate through existing children and update the watches if needed + if (watcher) { + watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + } + } + /** + * Watch the directories in the parentDir + */ + function watchChildDirectories(parentDir, existingChildWatches, callback) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(ts.getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + /** + * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list + */ + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(ts.getNormalizedAbsolutePath(childName, parentDir), callback); + addChildDirectoryWatcher(result); + } + /** + * Add child directory watcher to the new ChildDirectoryWatcher list + */ + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -4436,82 +4851,110 @@ var ts; catch (_a) { _crypto = undefined; } - var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } - function createMD5HashUsingNativeCrypto(data) { - var hash = _crypto.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - } - function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - // One file can have multiple watchers - var fileWatcherCallbacks = ts.createMultiMap(); - return { addFile: addFile, removeFile: removeFile }; - function reduceDirWatcherRefCountForFile(fileName) { - var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers.get(dirName); - if (watcher) { - watcher.referenceCount -= 1; - if (watcher.referenceCount <= 0) { - watcher.close(); - dirWatchers.delete(dirName); - } - } - } - function addDirWatcher(dirPath) { - var watcher = dirWatchers.get(dirPath); - if (watcher) { - watcher.referenceCount += 1; - return; - } - watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); - watcher.referenceCount = 1; - dirWatchers.set(dirPath, watcher); - return; - } - function addFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.add(filePath, callback); - } - function addFile(fileName, callback) { - addFileWatcherCallback(fileName, callback); - addDirWatcher(ts.getDirectoryPath(fileName)); - return { fileName: fileName, callback: callback }; - } - function removeFile(watchedFile) { - removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback); - reduceDirWatcherRefCountForFile(watchedFile.fileName); - } - function removeFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.remove(filePath, callback); - } - function fileEventHandler(eventName, relativeFileName, baseDirPath) { - // 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) { - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); - } - } - } - } - } - var watchedFileSet = createWatchedFileSet(); + var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch ( /*ignore*/_a) { /*ignore*/ } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: function (path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + // Could not enable source maps. + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + base64decode: Buffer.from ? function (input) { + return Buffer.from(input, "base64").toString("utf8"); + } : function (input) { + return new Buffer(input, "base64").toString("utf8"); + }, + base64encode: Buffer.from ? function (input) { + return Buffer.from(input).toString("base64"); + } : function (input) { + return new Buffer(input).toString("base64"); + } + }; + return nodeSystem; function isFileSystemCaseSensitive() { // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { @@ -4527,46 +4970,187 @@ var ts; return ch === up ? ch.toLowerCase() : up; }); } - var platform = _os.platform(); - var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + // Use polling interval based on priority when create watch using host.watchFile + return fsWatchFile; + case "DynamicPriorityPolling": + // Use polling interval but change the interval depending on file changes and their default polling interval + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + // Use notifications from FS to watch with falling back to fs.watchFile + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + // Use notifications from FS to watch with falling back to dynamic watch file + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + // Use notifications from FS to watch with falling back to fs.watchFile + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + // Default to do not use polling interval as it is before this experiment branch + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + // 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 fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + filePathComparer: useCaseSensitiveFileNames ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive, + directoryExists: directoryExists, + getAccessileSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + // 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, dirName); + // Some applications save a working file via rename operations + var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } function fsWatchFile(fileName, callback, pollingInterval) { _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; 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) { + // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears) + // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + // Already deleted file, no need to callback again + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + // If there is no change in modified time, ignore the event + else if (+curr.mtime === +prev.mtime) { return; } + else { + // File changed + eventKind = FileWatcherEventKind.Changed; + } callback(fileName, eventKind); } } - function fsWatchDirectory(directoryName, callback, recursive) { + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + // Change + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return 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 ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { var options; - /** Watcher for the directory depending on whether it is missing or present */ - var watcher = !directoryExists(directoryName) ? - watchMissingDirectory() : - watchPresentDirectory(); + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); return { close: function () { - // Close the watcher (either existing directory watcher or missing directory watcher) + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) watcher.close(); + watcher = undefined; } }; /** - * Watch the directory that is currently present - * and when the watched directory is deleted, switch to missing directory watcher + * Invoke the callback with rename and update the watcher if not closed + * @param createWatcher */ - function watchPresentDirectory() { + function invokeCallbackAndUpdateWatcher(createWatcher) { + // Call the callback for current directory + callback("rename", ""); + // If watcher is not closed, update it + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { // 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) { @@ -4577,34 +5161,56 @@ var ts; 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; + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + return watchPresentFileSystemEntryWithFsWatchFile(); + } } /** - * Watch the directory that is missing - * and switch to existing directory when the directory is created + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point */ - function watchMissingDirectory() { - return fsWatchFile(directoryName, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { - watcher.close(); - watcher = watchPresentDirectory(); - // Call the callback for current directory + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + // Call the callback for current file or directory // For now it could be callback for the inner directory creation, // but just return current directory, better than current no-op - callback("rename", ""); + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); } - }); + }, pollingInterval); } } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -4685,11 +5291,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); @@ -4711,110 +5312,27 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } - var nodeSystem = { - clearScreen: function () { - process.stdout.write("\x1Bc"); - }, - args: process.argv.slice(2), - newLine: _os.EOL, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - write: function (s) { - process.stdout.write(s); - }, - readFile: readFile, - writeFile: writeFile, - watchFile: function (fileName, callback, pollingInterval) { - if (useNonPollingWatchers) { - var watchedFile_1 = watchedFileSet.addFile(fileName, callback); - return { - close: function () { return watchedFileSet.removeFile(watchedFile_1); } - }; - } - else { - 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) - 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, - directoryExists: directoryExists, - createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { - _fs.mkdirSync(directoryName); - } - }, - getExecutingFilePath: function () { - return __filename; - }, - getCurrentDirectory: function () { - return process.cwd(); - }, - getDirectories: getDirectories, - getEnvironmentVariable: function (name) { - return process.env[name] || ""; - }, - readDirectory: readDirectory, - getModifiedTime: function (path) { - try { - return _fs.statSync(path).mtime; - } - catch (e) { - return undefined; - } - }, - createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, - getMemoryUsage: function () { - if (global.gc) { - global.gc(); - } - return process.memoryUsage().heapUsed; - }, - getFileSize: function (path) { - try { - var stat = _fs.statSync(path); - if (stat.isFile()) { - return stat.size; - } - } - catch (_a) { } - return 0; - }, - exit: function (exitCode) { - process.exit(exitCode); - }, - realpath: function (path) { - try { - return _fs.realpathSync(path); - } - catch (_a) { - return path; - } - }, - debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), - tryEnableSourceMapsForHost: function () { - try { - require("source-map-support").install(); - } - catch (_a) { - // Could not enable source maps. - } - }, - setTimeout: setTimeout, - clearTimeout: clearTimeout - }; - return nodeSystem; + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -4883,6 +5401,7 @@ var ts; return sys; })(); if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ : 0 /* None */; @@ -5481,6 +6000,7 @@ var ts; Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), 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}'."), @@ -5552,7 +6072,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), 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."), @@ -5592,6 +6112,8 @@ var ts; 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."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), 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."), @@ -5725,7 +6247,7 @@ var ts; Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), - Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), @@ -5769,6 +6291,8 @@ var ts; Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused."), 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."), @@ -5828,6 +6352,7 @@ var ts; 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."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), 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."), @@ -5848,14 +6373,20 @@ var ts; 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"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), 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}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), 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}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{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"), @@ -5892,6 +6423,33 @@ var ts; Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_this_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_this_to_all_unresolved_variables_matching_a_member_name_95037", "Add 'this.' to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), }; })(ts || (ts = {})); /// @@ -6144,9 +6702,9 @@ var ts; return false; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; - function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { @@ -6180,18 +6738,15 @@ var ts; ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } - if (nodeIsMissing(node)) { - return ""; - } - var text = sourceFile.text; - return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; - function getTextOfNodeFromSourceText(sourceText, node) { + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -6286,8 +6841,7 @@ var ts; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 237 /* ModuleDeclaration */ && - (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { @@ -6318,21 +6872,22 @@ var ts; } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(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 272 /* SourceFile */: return ts.isExternalModule(node.parent); case 238 /* ModuleBlock */: - return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } - ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -6400,6 +6955,10 @@ var ts; } } ts.isAnyImportSyntax = isAnyImportSyntax; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -6463,6 +7022,11 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, startNode.pos); + return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -6810,6 +7374,10 @@ var ts; return false; } ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 231 /* VariableDeclarationList */ && node.parent.parent.kind === 212 /* VariableStatement */; @@ -7247,6 +7815,10 @@ var ts; return isInJavaScriptFile(file); } ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isSourceFileNotJavaScript(file) { + return !isInJavaScriptFile(file); + } + ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { return node && !!(node.flags & 65536 /* JavaScriptFile */); } @@ -7263,7 +7835,7 @@ var ts; (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { if (callExpression.kind !== 185 /* CallExpression */) { return false; } @@ -7275,7 +7847,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 /* StringLiteral */ || arg.kind === 13 /* NoSubstitutionTemplateLiteral */; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -7287,17 +7859,117 @@ var ts; } 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. + * Given the symbol of a declaration, find the symbol of its Javascript container-like initializer, + * if it has one. Otherwise just return the original symbol. + * + * Container-like initializer behave like namespaces, so the binder needs to add contained symbols + * to their exports. An example is a function with assignments to `this` inside. */ - function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 230 /* VariableDeclaration */) { - var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 190 /* FunctionExpression */ || declaration.initializer.kind === 203 /* ClassExpression */); + function getJSInitializerSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return symbol; + } + var declaration = symbol.valueDeclaration; + var e = getDeclaredJavascriptInitializer(declaration) || getAssignedJavascriptInitializer(declaration); + return e && e.symbol ? e.symbol : symbol; + } + ts.getJSInitializerSymbol = getJSInitializerSymbol; + /** Get the declaration initializer, when the initializer is container-like (See getJavascriptInitializer) */ + function getDeclaredJavascriptInitializer(node) { + if (node && ts.isVariableDeclaration(node) && node.initializer) { + return getJavascriptInitializer(node.initializer, /*isPrototypeAssignment*/ false) || + ts.isIdentifier(node.name) && getDefaultedJavascriptInitializer(node.name, node.initializer, /*isPrototypeAssignment*/ false); + } + } + ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + /** + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * We treat the right hand side of assignments with container-like initalizers as declarations. + */ + function getAssignedJavascriptInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + } + ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + /** + * Recognized Javascript container-like initializers are: + * 1. (function() {})() -- IIFEs + * 2. function() { } -- Function expressions + * 3. class { } -- Class expressions + * 4. {} -- Empty object literals + * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` + * + * This function returns the provided initializer, or undefined if it is not valid. + */ + function getJavascriptInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 190 /* FunctionExpression */ || e.kind === 191 /* ArrowFunction */ ? initializer : undefined; + } + if (initializer.kind === 190 /* FunctionExpression */ || initializer.kind === 203 /* ClassExpression */) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getJavascriptInitializer = getJavascriptInitializer; + /** + * A defaulted Javascript initializer matches the pattern + * `Lhs = Lhs || JavascriptInitializer` + * or `var Lhs = Lhs || JavascriptInitializer` + * + * The second Lhs is required to be the same as the first except that it may be prefixed with + * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. + */ + function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ + function getOuterNameOfJsInitializer(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + /** + * Is the 'declared' name the same as the one in the initializer? + * @return true for identical entity names, as well as ones where the initializer is prefixed with + * 'window', 'self' or 'global'. For example: + * + * var my = my || {} + * var min = window.min || {} + * my.app = self.my.app || class { } + */ + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 99 /* ThisKeyword */ || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); } return false; } - ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; function getRightMostAssignedExpression(node) { while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) { node = node.right; @@ -7316,69 +7988,78 @@ var ts; /// 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 */; - } - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || expr.left.kind !== 183 /* PropertyAccessExpression */) { + if (!isInJavaScriptFile(expr) || + expr.operatorToken.kind !== 58 /* EqualsToken */ || + !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } var lhs = expr.left; - if (lhs.expression.kind === 71 /* Identifier */) { - var lhsId = lhs.expression; - if (lhsId.escapedText === "exports") { - // exports.name = expr - return 1 /* ExportsProperty */; - } - else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { - // module.exports = expr - return 2 /* ModuleExports */; - } - else { - // F.x = expr - return 5 /* Property */; - } - } - else if (lhs.expression.kind === 99 /* ThisKeyword */) { + if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (lhs.expression.kind === 183 /* 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 */) { - // module.exports.name = expr - var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { - return 1 /* ExportsProperty */; - } - if (innerPropertyAccess.name.escapedText === "prototype") { - return 3 /* PrototypeProperty */; - } + else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + // module.exports = expr + return 2 /* ModuleExports */; + } + else if (isEntityNameExpression(lhs.expression)) { + if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(expr.right)) { + // F.prototype = { ... } + return 6 /* Prototype */; } + else if (isPrototypeAccess(lhs.expression)) { + // F.G....prototype.x = expr + return 3 /* PrototypeProperty */; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + // exports.name = expr OR module.exports.name = expr + return 1 /* ExportsProperty */; + } + // F.G...x = expr + return 5 /* Property */; } return 0 /* None */; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && expr.parent && expr.parent.kind === 214 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function importFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + return node.parent; + case 252 /* ExternalModuleReference */: + return node.parent.parent; + case 185 /* CallExpression */: + return node.parent; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(node)); + } + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; function getExternalModuleName(node) { - if (node.kind === 242 /* ImportDeclaration */) { - return node.moduleSpecifier; - } - if (node.kind === 241 /* ImportEqualsDeclaration */) { - var reference = node.moduleReference; - if (reference.kind === 252 /* ExternalModuleReference */) { - return reference.expression; - } - } - if (node.kind === 248 /* ExportDeclaration */) { - return node.moduleSpecifier; - } - if (isModuleWithStringLiteralName(node)) { - return node.name; + switch (node.kind) { + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + return node.moduleSpecifier; + case 241 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 252 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + default: + return ts.Debug.assertNever(node); } } ts.getExternalModuleName = getExternalModuleName; @@ -7428,6 +8109,14 @@ var ts; node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 54 /* BarBarToken */ && + node.expression.right.right; + } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { case 212 /* VariableStatement */: @@ -7467,7 +8156,8 @@ var ts; (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node) { + if (parent && parent.parent && parent.parent.parent && + (getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || @@ -7506,7 +8196,8 @@ var ts; ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { var host = getJSDocHost(node); - var decl = getSourceOfAssignment(host) || + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || @@ -7531,7 +8222,7 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined; + return node.dotDotDotToken !== undefined || node.type && node.type.kind === 281 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -7616,6 +8307,10 @@ var ts; return false; } ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -7630,6 +8325,13 @@ var ts; return walkUp(node, 189 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 189 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 183 /* PropertyAccessExpression */ && node.kind !== 184 /* ElementAccessExpression */) { @@ -7648,16 +8350,9 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - // True if the given identifier, string literal, or number literal is the name of a declaration node + // True if `name` is the name of a declaration node function isDeclarationName(name) { - switch (name.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - return ts.isDeclaration(name.parent) && name.parent.name === name; - default: - return false; - } + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; // See GH#16030 @@ -7750,6 +8445,13 @@ var ts; return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; @@ -7784,38 +8486,6 @@ var ts; return undefined; } ts.getAncestor = getAncestor; - function getFileReferenceFromReferencePath(comment, commentRange) { - var simpleReferenceRegEx = /^\/\/\/\s*= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode) + return "\\x00"; + } + // Otherwise, keep printing a literal \0 for the null character + return "\\0"; + } return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { @@ -8592,49 +9268,38 @@ 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, checkJSDoc) { - if (ts.hasType(node)) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocType(node); - } + function getEffectiveTypeAnnotationNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; /** * 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 (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocReturnType(node); - } + function getEffectiveReturnTypeNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; /** * 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 (checkJSDoc || isInJavaScriptFile(node)) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; - } + function getEffectiveTypeParameterDeclarations(node) { + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getJSDocTypeParameterDeclarations(node) { + var templateTag = ts.getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** * 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) { + function getEffectiveSetAccessorTypeAnnotationNode(node) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); + return parameter && getEffectiveTypeAnnotationNode(parameter); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -8738,7 +9403,7 @@ var ts; } return currentDetachedCommentInfo; function isPinnedCommentLocal(comment) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } ts.emitDetachedComments = emitDetachedComments; @@ -8939,10 +9604,17 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 183 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node) || (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node); @@ -8979,7 +9651,7 @@ var ts; var length = input.length; for (var i = 0; i < length; i++) { var charCode = input.charCodeAt(i); - // handel utf8 + // handle utf8 if (charCode < 0x80) { output.push(charCode); } @@ -9036,6 +9708,78 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -9355,6 +10099,7 @@ var ts; map.delete(key); onDeleteValue(existingValue, key); } + // If present notify about existing values else if (onExistingValue) { onExistingValue(existingValue, valueInNewMap, key); } @@ -9416,6 +10161,42 @@ var ts; return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + /** Add a value to a set, and return true if it wasn't already present. */ + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9451,27 +10232,20 @@ var ts; } ts.textSpanContainsTextSpan = textSpanContainsTextSpan; function textSpanOverlapsWith(span, other) { - var overlapStart = Math.max(span.start, other.start); - var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); - return overlapStart < overlapEnd; + return textSpanOverlap(span, other) !== undefined; } ts.textSpanOverlapsWith = textSpanOverlapsWith; function textSpanOverlap(span1, span2) { - var overlapStart = Math.max(span1.start, span2.start); - var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (overlapStart < overlapEnd) { - return createTextSpanFromBounds(overlapStart, overlapEnd); - } - return undefined; + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; } ts.textSpanOverlap = textSpanOverlap; function textSpanIntersectsWithTextSpan(span, other) { - return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); } ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; function textSpanIntersectsWith(span, start, length) { - var end = start + length; - return start <= textSpanEnd(span) && end >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); } ts.textSpanIntersectsWith = textSpanIntersectsWith; function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { @@ -9485,12 +10259,9 @@ var ts; } ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; function textSpanIntersection(span1, span2) { - var intersectStart = Math.max(span1.start, span2.start); - var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (intersectStart <= intersectEnd) { - return createTextSpanFromBounds(intersectStart, intersectEnd); - } - return undefined; + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; } ts.textSpanIntersection = textSpanIntersection; function createTextSpan(start, length) { @@ -9503,6 +10274,13 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; + /* @internal */ + function createTextRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos); + return { pos: pos, end: end }; + } + ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -9755,6 +10533,7 @@ var ts; return false; } try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } catch (e) { @@ -9881,6 +10660,11 @@ var ts; return declaration.name || nameForNamelessJSDocTypedef(declaration); } ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + /** @internal */ + function isNamedDeclaration(node) { + return !!node.name; // A 'name' property should always be a DeclarationName. + } + ts.isNamedDeclaration = isNamedDeclaration; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -9937,7 +10721,7 @@ var ts; 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; + return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; /** @@ -9947,33 +10731,33 @@ var ts; * for example on a variable declaration whose initializer is a function expression. */ function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 287 /* JSDocParameterTag */); + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } ts.hasJSDocParameterTags = hasJSDocParameterTags; /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 286 /* JSDocClassTag */); + return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 288 /* JSDocReturnTag */); + return getFirstJSDocTag(node, ts.isJSDocReturnTag); } ts.getJSDocReturnTag = getJSDocReturnTag; /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 290 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); } 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, 289 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -9992,12 +10776,9 @@ var ts; * tag directly on the node would be returned. */ function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 289 /* JSDocTypeTag */); - if (!tag && node.kind === 148 /* Parameter */) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); } return tag && tag.typeExpression && tag.typeExpression.type; } @@ -10024,14 +10805,12 @@ var ts; } 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; }); + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); } /** 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; }); + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); @@ -10657,6 +11436,10 @@ var ts; return node.kind === 285 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 286 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { return node.kind === 287 /* JSDocParameterTag */; } @@ -10778,6 +11561,16 @@ var ts; return false; } ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { return isModifierKind(node.kind); } @@ -11082,7 +11875,7 @@ var ts; case 97 /* SuperKeyword */: case 207 /* NonNullExpression */: case 208 /* MetaProperty */: - case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression + case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: return false; @@ -11167,7 +11960,6 @@ var ts; || isPartiallyEmittedExpression(node); } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; - // Statement function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { case 218 /* ForStatement */: @@ -11441,6 +12233,45 @@ var ts; return !!node.type; } ts.hasType = hasType; + /* True if the node could have a type node a `.type` */ + /* @internal */ + function couldHaveType(node) { + switch (node.kind) { + case 148 /* Parameter */: + case 150 /* PropertySignature */: + case 151 /* PropertyDeclaration */: + case 152 /* MethodSignature */: + case 153 /* MethodDeclaration */: + case 154 /* Constructor */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + case 157 /* CallSignature */: + case 158 /* ConstructSignature */: + case 159 /* IndexSignature */: + case 160 /* TypePredicate */: + case 162 /* FunctionType */: + case 163 /* ConstructorType */: + case 172 /* ParenthesizedType */: + case 174 /* TypeOperator */: + case 176 /* MappedType */: + case 188 /* TypeAssertionExpression */: + case 190 /* FunctionExpression */: + case 191 /* ArrowFunction */: + case 206 /* AsExpression */: + case 230 /* VariableDeclaration */: + case 232 /* FunctionDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 274 /* JSDocTypeExpression */: + case 277 /* JSDocNullableType */: + case 278 /* JSDocNonNullableType */: + case 279 /* JSDocOptionalType */: + case 280 /* JSDocFunctionType */: + case 281 /* JSDocVariadicType */: + return true; + } + return false; + } + ts.couldHaveType = couldHaveType; /** True if has initializer node attached to it. */ /* @internal */ function hasInitializer(node) { @@ -11473,6 +12304,31 @@ var ts; return node.kind === 161 /* TypeReference */ || node.kind === 205 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; } @@ -13268,6 +14124,13 @@ var ts; return token = 26 /* CommaToken */; case 46 /* dot */: return token = 23 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 13 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { @@ -13406,6 +14269,13 @@ var ts; } } } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; /** * 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, @@ -13774,6 +14644,7 @@ var ts; case 254 /* JsxSelfClosingElement */: case 255 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); case 261 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); @@ -14099,7 +14970,9 @@ var ts; sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); - processReferenceComments(sourceFile); + // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); ts.Debug.assert(token() === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); @@ -14112,6 +14985,9 @@ var ts; fixupParentReferences(sourceFile); } return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } } function addJSDocComment(node) { var comments = ts.getJSDocCommentRanges(node, sourceFile.text); @@ -14262,9 +15138,7 @@ var ts; return inContext(16384 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), 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. @@ -14276,9 +15150,14 @@ var ts; // node we finish so that it can't be reused incrementally. parseErrorBeforeNextFinishedNode = true; } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); + parseErrorAtPosition(scanner.getTextPos(), length, message); } function getNodePos() { return scanner.getStartPos(); @@ -14560,25 +15439,26 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76 /* ConstKeyword */) { - // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; + switch (token()) { + case 76 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 83 /* EnumKeyword */; + case 84 /* ExportKeyword */: + nextToken(); + if (token() === 79 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); + case 79 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 115 /* StaticKeyword */: + case 125 /* GetKeyword */: + case 136 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === 84 /* ExportKeyword */) { - nextToken(); - if (token() === 79 /* DefaultKeyword */) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - } - if (token() === 79 /* DefaultKeyword */) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === 115 /* StaticKeyword */) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); @@ -15303,9 +16183,20 @@ var ts; nextToken(); return finishNode(node); } - function parseJSDocAllType() { + function parseJSDocAllType(postFixEquals) { var result = createNode(275 /* JSDocAllType */); + if (postFixEquals) { + return createJSDocPostfixType(279 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(278 /* JSDocNonNullableType */); nextToken(); + result.type = parseNonArrayType(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { @@ -15353,14 +16244,21 @@ var ts; parameter.name = parseIdentifierName(); parseExpected(56 /* ColonToken */); } - parameter.type = parseType(); + parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocNodeWithType(kind) { - var result = createNode(kind); - nextToken(); - result.type = parseNonArrayType(); - return finishNode(result); + function parseJSDocType() { + var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + var type = parseType(); + if (dotdotdot) { + var variadic = createNode(281 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 58 /* EqualsToken */) { + return createJSDocPostfixType(279 /* JSDocOptionalType */, type); + } + return type; } function parseTypeQuery() { var node = createNode(164 /* TypeQuery */); @@ -15767,13 +16665,15 @@ var ts; // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 39 /* AsteriskToken */: - return parseJSDocAllType(); + return parseJSDocAllType(/*postfixEquals*/ false); + case 61 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); case 55 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); case 89 /* FunctionKeyword */: return parseJSDocFunctionType(); case 51 /* ExclamationToken */: - return parseJSDocNodeWithType(278 /* JSDocNonNullableType */); + return parseJSDocNonNullableType(); case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -15855,13 +16755,6 @@ var ts; var type = parseNonArrayType(); 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(279 /* JSDocOptionalType */, type); - break; case 51 /* ExclamationToken */: type = createJSDocPostfixType(278 /* JSDocNonNullableType */, type); break; @@ -15923,12 +16816,6 @@ var ts; return parseTypeOperator(operator); case 126 /* InferKeyword */: return parseInferType(); - case 24 /* DotDotDotToken */: { - var result = createNode(281 /* JSDocVariadicType */); - nextToken(); - result.type = parsePostfixTypeOrHigher(); - return finishNode(result); - } } return parsePostfixTypeOrHigher(); } @@ -16542,7 +17429,7 @@ var ts; // 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 newPrecedence = ts.getBinaryOperatorPrecedence(token()); // 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 @@ -16597,50 +17484,7 @@ var ts; if (inDisallowInContext() && token() === 92 /* InKeyword */) { return false; } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54 /* BarBarToken */: - return 1; - case 53 /* AmpersandAmpersandToken */: - return 2; - case 49 /* BarToken */: - return 3; - case 50 /* CaretToken */: - return 4; - case 48 /* AmpersandToken */: - return 5; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 6; - 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 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 8; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 9; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 10; - case 40 /* AsteriskAsteriskToken */: - return 11; - } - // -1 is lower than all other precedences. Returning it will cause binary expression - // parsing to stop. - return -1; + return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { var node = createNode(198 /* BinaryExpression */, left.pos); @@ -16716,7 +17560,7 @@ var ts; if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); return token() === 40 /* AsteriskAsteriskToken */ ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } /** @@ -16733,12 +17577,13 @@ var ts; var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40 /* AsteriskAsteriskToken */) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; if (simpleUnaryExpression.kind === 188 /* 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); + parseErrorAt(pos, end, 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 { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; @@ -16990,7 +17835,7 @@ var ts; 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)); + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } @@ -17034,8 +17879,21 @@ var ts; currentToken = scanner.scanJsxToken(); return finishNode(node); } - function parseJsxChild() { - switch (token()) { + function parseJsxChild(openingTag, token) { + switch (token) { + case 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)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 28 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; case 10 /* JsxText */: case 11 /* JsxTextAllWhiteSpaces */: return parseJsxText(); @@ -17043,8 +17901,9 @@ var ts; return parseJsxExpression(/*inExpressionContext*/ false); case 27 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); } - ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTag) { var list = []; @@ -17052,30 +17911,10 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28 /* LessThanSlashToken */) { - // Closing tag + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; - } - 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 /* ConflictMarkerTrivia */) { - break; - } - var child = parseJsxChild(); - if (child) { - list.push(child); - } + list.push(child); } parsingContext = saveParsingContext; return createNodeArray(list, listPos); @@ -17089,11 +17928,13 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(27 /* LessThanToken */); if (token() === 29 /* GreaterThanToken */) { - parseExpected(29 /* GreaterThanToken */); + // See below for explanation of scanJsxText var node_1 = createNode(258 /* JsxOpeningFragment */, fullStart); + scanJsxText(); return finishNode(node_1); } var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; if (token() === 29 /* GreaterThanToken */) { @@ -17115,6 +17956,7 @@ var ts; node = createNode(254 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; + node.typeArguments = typeArguments; node.attributes = attributes; return finishNode(node); } @@ -17137,7 +17979,9 @@ var ts; } function parseJsxExpression(inExpressionContext) { var node = createNode(263 /* JsxExpression */); - parseExpected(17 /* OpenBraceToken */); + if (!parseExpected(17 /* OpenBraceToken */)) { + return undefined; + } if (token() !== 18 /* CloseBraceToken */) { node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); @@ -17195,8 +18039,7 @@ var ts; var node = createNode(259 /* 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); + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { parseExpected(29 /* GreaterThanToken */); @@ -17332,7 +18175,7 @@ var ts; case 48 /* AmpersandToken */: // foo & case 49 /* BarToken */: // foo | case 18 /* CloseBraceToken */: // foo } - case 1 /* EndOfFileToken */:// 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. @@ -17601,7 +18444,7 @@ var ts; parseExpected(88 /* ForKeyword */); var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); parseExpected(19 /* OpenParenToken */); - var initializer = undefined; + var initializer; if (token() !== 25 /* SemicolonToken */) { if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); @@ -18244,18 +19087,6 @@ var ts; node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } function isClassMemberStart() { var idToken; if (token() === 57 /* AtToken */) { @@ -18270,7 +19101,7 @@ var ts; // 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)) { + if (ts.isClassMemberModifier(idToken)) { return true; } nextToken(); @@ -18302,7 +19133,7 @@ var ts; case 51 /* ExclamationToken */: // Non-null assertion on property name 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. + case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -18617,7 +19448,7 @@ var ts; // import ModuleSpecifier; if (identifier || // import id token() === 39 /* AsteriskToken */ || // import * - token() === 17 /* OpenBraceToken */) { + token() === 17 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); parseExpected(142 /* FromKeyword */); } @@ -18731,8 +19562,7 @@ var ts; node.name = identifierName; } if (kind === 246 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - // Report error identifier expected - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } @@ -18767,87 +19597,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function processReferenceComments(sourceFile) { - 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 /* SingleLineCommentTrivia */) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*= pos_2); pos_2 = child.end; - }); + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); ts.Debug.assert(pos_2 <= node.end); } } @@ -19806,6 +20560,12 @@ var ts; // Adjust the pos or end (or both) of the intersecting element accordingly. adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } @@ -19870,15 +20630,15 @@ var ts; var lastNodeEntirelyBeforePosition; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } } return bestResult; - function getLastChild(node) { + function getLastDescendant(node) { while (true) { - var lastChild = getLastChildWorker(node); + var lastChild = ts.getLastChild(node); if (lastChild) { node = lastChild; } @@ -19887,15 +20647,6 @@ var ts; } } } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } function visit(child) { if (ts.nodeIsMissing(child)) { // Missing nodes are effectively invisible to us. We never even consider them @@ -20060,6 +20811,209 @@ var ts; function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + /*@internal*/ + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var pragmas = []; + // 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 (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + /*@internal*/ + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to + // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { + var _b = _a.arguments, name = _b.name, path = _b.path; + return ({ name: name, path: path }); + }); + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + // TODO: It's probably fine to issue this diagnostic on all instances of the pragma + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + // _last_ of either nocheck or check in a file is the "winner" + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; // Accessed directly + default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; // Missing required argument, don't parse + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; // Split on spaces and match up positionally with definition + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; // Missing required argument, fail to parse it + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } })(ts || (ts = {})); /// /// @@ -20125,6 +21079,13 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, { name: "watch", shortName: "w", @@ -20206,9 +21167,10 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "es2018.promise": "lib.es2018.promise.d.ts", + "es2018.regexp": "lib.es2018.regexp.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, @@ -20248,6 +21210,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, { name: "emitDeclarationOnly", type: "boolean", @@ -21860,7 +22829,7 @@ var ts; function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); - var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; // 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. @@ -22050,22 +23019,6 @@ 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. @@ -22076,7 +23029,7 @@ var ts; for (var key in opts) { if (opts.hasOwnProperty(key)) { var type = getOptionFromName(key); - if (type !== undefined) { + if (type !== undefined) { // Ignore unknown options out[key] = getOptionValueWithEmptyStrings(opts[key], type); } } @@ -22086,11 +23039,11 @@ var ts; ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; function getOptionValueWithEmptyStrings(value, option) { switch (option.type) { - case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "". + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". return ""; - case "string":// Could be any arbitrary string -- use empty string instead. + case "string": // Could be any arbitrary string -- use empty string instead. return ""; - case "number":// Allow numbers, but be sure to check it's actually a 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 : ""; @@ -22351,8 +23304,11 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createMap(); - var moduleNameToDirectoryMap = ts.createMap(); + return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + /*@internal*/ + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); @@ -22436,7 +23392,7 @@ var ts; } } } - ts.createModuleResolutionCache = createModuleResolutionCache; + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -22447,7 +23403,7 @@ var ts; var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } } else { @@ -22637,7 +23593,7 @@ var ts; 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; + var matchedPattern; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); @@ -22913,7 +23869,7 @@ var ts; var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = readJson(packageJsonPath, host); - if (subModuleName === "") { + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); if (typeof path === "string") { subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); @@ -23009,7 +23965,7 @@ var ts; } else { var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { + if (rest !== "") { // If "rest" is empty, we just did this search above. 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; @@ -23039,7 +23995,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -23086,6 +24042,7 @@ var ts; return "@types/" + getMangledNameForScopedPackage(packageName); } ts.getTypesPackageName = getTypesPackageName; + /* @internal */ function getMangledNameForScopedPackage(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); @@ -23095,6 +24052,7 @@ var ts; } return packageName; } + ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); @@ -23111,12 +24069,13 @@ var ts; typesPackageName; } ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { var result = cache && cache.get(containingDirectory); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } + failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } @@ -23137,7 +24096,7 @@ var ts; if (!ts.isExternalModuleNameRelative(moduleName)) { // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -23275,7 +24234,6 @@ var ts; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; - ContainerFlags[ContainerFlags["IsInferenceContainer"] = 256] = "IsInferenceContainer"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -23291,8 +24249,8 @@ var ts; var languageVersion; var parent; var container; + var thisParentContainer; // Container one level up var blockScopeContainer; - var inferenceContainer; var lastContainer; var seenThisKeyword; // state used by control flow analysis @@ -23347,8 +24305,8 @@ var ts; languageVersion = undefined; parent = undefined; container = undefined; + thisParentContainer = undefined; blockScopeContainer = undefined; - inferenceContainer = undefined; lastContainer = undefined; seenThisKeyword = false; currentFlow = undefined; @@ -23379,19 +24337,14 @@ var ts; function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = [node]; - } - else { - symbol.declarations.push(node); - } + symbol.declarations = ts.append(symbol.declarations, node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 107455 /* Value */) { + if (symbolFlags & 67216319 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 237 /* ModuleDeclaration */)) { @@ -23421,7 +24374,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } - return ts.getEscapedTextOfIdentifierOrLiteral(name); + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { case 154 /* Constructor */: @@ -23451,7 +24404,7 @@ var ts; case 148 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 280 /* JSDocFunctionType */); + ts.Debug.assert(node.parent.kind === 280 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -23461,7 +24414,7 @@ var ts; } } function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? 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. @@ -23524,7 +24477,7 @@ var ts; symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } else { - if (node.name) { + if (ts.isNamedDeclaration(node)) { node.name.parent = node; } // Report errors every position with duplicate declaration @@ -23562,7 +24515,12 @@ var ts; } } addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { @@ -23594,7 +24552,7 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. var isJSDocTypedefInJSDocNamespace = ts.isJSDocTypedefTag(node) && node.name && node.name.kind === 71 /* Identifier */ && node.name.isInJSDocNamespace; if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67216319 /* 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; @@ -23613,11 +24571,12 @@ var ts; // and block-container. Then after we pop out of processing the children, we restore // these saved values. var saveContainer = container; + var saveThisParentContainer = thisParentContainer; var savedBlockScopeContainer = blockScopeContainer; // 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 + // may contain locals, we eagerly 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). // @@ -23632,6 +24591,9 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 191 /* ArrowFunction */) { + thisParentContainer = container; + } container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { container.locals = ts.createSymbolTable(); @@ -23697,17 +24659,11 @@ var ts; bindChildren(node); node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; } - else if (containerFlags & 256 /* IsInferenceContainer */) { - var saveInferenceContainer = inferenceContainer; - inferenceContainer = node; - node.locals = undefined; - bindChildren(node); - inferenceContainer = saveInferenceContainer; - } else { bindChildren(node); } container = saveContainer; + thisParentContainer = saveThisParentContainer; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { @@ -23727,12 +24683,17 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } - function bindEach(nodes) { + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 232 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 232 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } if (nodes === undefined) { return; } if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); + ts.forEach(nodes, bindFunction); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -23740,7 +24701,7 @@ var ts; var nodeArrayFlags = 0 /* None */; for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { var node = nodes_2[_i]; - bind(node); + bindFunction(node); nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; } nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; @@ -23839,6 +24800,15 @@ var ts; case 291 /* JSDocTypedefTag */: bindJSDocTypedefTag(node); break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 272 /* SourceFile */: + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + case 211 /* Block */: + case 238 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; default: bindEachChild(node); break; @@ -24501,8 +25471,6 @@ var ts; case 235 /* TypeAliasDeclaration */: case 176 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 170 /* ConditionalType */: - return 256 /* IsInferenceContainer */; case 272 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; case 153 /* MethodDeclaration */: @@ -24651,7 +25619,7 @@ var ts; 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)) { + if (ts.isModuleAugmentationExternal(node)) { declareModuleSymbol(node); } else { @@ -24665,10 +25633,8 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } else { @@ -24687,7 +25653,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -24735,8 +25701,8 @@ var ts; continue; } 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)); + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -24775,7 +25741,7 @@ var ts; } } function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* 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. @@ -24821,8 +25787,8 @@ var ts; 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)); + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -24834,8 +25800,8 @@ var ts; 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.idText(identifier))); + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -24998,7 +25964,7 @@ 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); + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, 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'"; @@ -25015,7 +25981,7 @@ var ts; while (parentNode && parentNode.kind !== 291 /* JSDocTypedefTag */) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); break; } // falls through @@ -25042,13 +26008,16 @@ var ts; bindModuleExportsAssignment(node); break; case 3 /* PrototypeProperty */: - bindPrototypePropertyAssignment(node); + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); break; case 4 /* ThisProperty */: bindThisPropertyAssignment(node); break; case 5 /* Property */: - bindStaticPropertyAssignment(node); + bindSpecialPropertyAssignment(node); break; case 0 /* None */: // Nothing to do @@ -25073,7 +26042,7 @@ var ts; seenThisKeyword = true; return; case 160 /* TypePredicate */: - return checkTypePredicate(node); + break; // Binding the children will handle everything case 147 /* TypeParameter */: return bindTypeParameter(node); case 148 /* Parameter */: @@ -25090,7 +26059,7 @@ var ts; case 269 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 271 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); case 157 /* CallSignature */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: @@ -25101,15 +26070,15 @@ var ts; // 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 */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); case 232 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 154 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 155 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); case 156 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); case 162 /* FunctionType */: case 280 /* JSDocFunctionType */: case 163 /* ConstructorType */: @@ -25135,9 +26104,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 234 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); case 235 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); case 236 /* EnumDeclaration */: return bindEnumDeclaration(node); case 237 /* ModuleDeclaration */: @@ -25185,7 +26154,7 @@ var ts; case 291 /* JSDocTypedefTag */: { var fullName = node.fullName; if (!fullName || fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); } break; } @@ -25197,16 +26166,6 @@ var ts; function bindAnonymousTypeWorker(node) { return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71 /* Identifier */) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 173 /* ThisType */) { - seenThisKeyword = true; - } - bind(type); - } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -25281,7 +26240,18 @@ var ts; // 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 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, function (id, original) { + if (!original) { + return undefined; + } + var s = ts.getJSInitializerSymbol(original); + addDeclarationToSymbol(s, id, 1536 /* Module */ | 67108864 /* JSContainer */); + return s; + }); + if (symbol) { + declareSymbol(symbol.exports, symbol, lhs, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + } } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' @@ -25300,14 +26270,24 @@ var ts; } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - switch (container.kind) { + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { case 232 /* FunctionDeclaration */: case 190 /* 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 */); + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = getJSInitializerSymbolFromName(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } break; case 154 /* Constructor */: case 151 /* PropertyDeclaration */: @@ -25316,111 +26296,145 @@ var ts; case 156 /* 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 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; + case 272 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); } } 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 === 183 /* PropertyAccessExpression */) && - node.parent.parent.kind === 272 /* SourceFile */) { - bindStaticPropertyAssignment(node); + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 272 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + 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, /*isPrototypeProperty*/ true); + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); } /** - * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function or class, or not declared. + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; */ function bindStaticPropertyAssignment(node) { - // Look up the function in the local scope, since static assignments should - // follow the function declaration - var leftSideOfAssignment = node.kind === 183 /* PropertyAccessExpression */ ? node : node.left; - var target = leftSideOfAssignment.expression; - 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 === 198 /* BinaryExpression */) { - leftSideOfAssignment.parent = node; - } - if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, 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); - } - } + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function lookupSymbolForName(name) { - return lookupSymbolForNameWorker(container, name); + function getJSInitializerSymbolFromName(name, lookupContainer) { + return ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(name, lookupContainer)); } - 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 === 198 /* BinaryExpression */ || propertyAccess.parent.kind === 214 /* ExpressionStatement */); - var isLegalPosition; - if (propertyAccess.parent.kind === 198 /* BinaryExpression */) { - var initializerKind = propertyAccess.parent.right.kind; - isLegalPosition = (initializerKind === 203 /* ClassExpression */ || initializerKind === 190 /* FunctionExpression */) && - propertyAccess.parent.parent.parent.kind === 272 /* SourceFile */; + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var symbol = getJSInitializerSymbolFromName(name); + var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) + ? propertyAccess.parent.parent.parent.kind === 272 /* SourceFile */ && + !!ts.getJavascriptInitializer(propertyAccess.parent.right, ts.isPrototypeAccess(propertyAccess.parent.left)) + : propertyAccess.parent.parent.kind === 272 /* SourceFile */; + if (!isPrototypeProperty && (!symbol || !(symbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; + var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + forEachIdentifierInEntityName(propertyAccess.expression, function (id, original) { + if (original) { + // Note: add declaration to original symbol, not the special-syntax's symbol, so that namespaces work for type lookup + addDeclarationToSymbol(original, id, flags_1); + return original; + } + else { + return symbol = declareSymbol(symbol ? symbol.exports : container.locals, symbol, id, flags_1, excludeFlags_1); + } + }); } - else { - isLegalPosition = propertyAccess.parent.parent.kind === 272 /* 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 */ | 1024 /* NamespaceModule */))) { + if (!symbol || !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */ | 4096 /* ObjectLiteral */))) { 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())); + (symbol.members || (symbol.members = ts.createSymbolTable())) : + (symbol.exports || (symbol.exports = ts.createSymbolTable())); // Declare the method/property - declareSymbol(symbolTable, targetSymbol, propertyAccess, 4 /* Property */, 0 /* PropertyExcludes */); + var symbolFlags = 4 /* Property */ | (isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); + var symbolExcludes = 0 /* PropertyExcludes */ & ~(isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); + declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(node.expression)); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e)); + } + else { + var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); + ts.Debug.assert(!!s && !!s.exports); + return action(e.name, s.exports.get(e.name.escapedText)); + } } function bindCallExpression(node) { // 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)) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { setCommonJsModuleIndicator(node); } } function bindClassLikeDeclaration(node) { if (node.kind === 233 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; @@ -25453,8 +26467,8 @@ var ts; } function bindEnumDeclaration(node) { return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) - : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); } function bindVariableDeclarationOrBindingElement(node) { if (inStrictMode) { @@ -25474,10 +26488,10 @@ var ts; // 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 */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); } } } @@ -25491,7 +26505,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -25509,10 +26523,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -25539,20 +26553,31 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + function getInferTypeContainer(node) { + while (node) { + var parent_2 = node.parent; + if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) { + return parent_2; + } + node = parent_2; + } + return undefined; + } function bindTypeParameter(node) { if (node.parent.kind === 171 /* InferType */) { - if (inferenceContainer) { - if (!inferenceContainer.locals) { - inferenceContainer.locals = ts.createSymbolTable(); + var container_1 = getInferTypeContainer(node.parent); + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); } - declareSymbol(inferenceContainer.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } } // reachability checks @@ -25612,7 +26637,7 @@ var ts; } function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { return isExportsOrModuleExportsOrAlias(sourceFile, node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); } function lookupSymbolForNameWorker(container, name) { var local = container.locals && container.locals.get(name); @@ -26873,7 +27898,7 @@ var ts; node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (node) { node = ts.getParseTreeNode(node, ts.isParameter); return node ? isOptionalParameter(node) : false; @@ -26912,7 +27937,7 @@ var ts; resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, @@ -26924,13 +27949,13 @@ var ts; node = ts.getParseTreeNode(node, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, + getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; }, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); - var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -26999,6 +28024,7 @@ var ts; var anyArrayType; var autoArrayType; var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; // 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 @@ -27015,11 +28041,9 @@ var ts; var deferredGlobalAsyncIteratorType; var deferredGlobalAsyncIterableIteratorType; var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; var deferredNodes; var deferredUnusedIdentifierNodes; + var seenDeferredUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -27044,6 +28068,19 @@ var ts; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); + // Suggestion diagnostics must have a file. Keyed by source file name. + var suggestionDiagnostics = ts.createMultiMap(); + function addSuggestionDiagnostic(diag) { + suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + function addErrorOrSuggestionDiagnostic(isError, diag) { + if (isError) { + diagnostics.add(diag); + } + else { + addSuggestionDiagnostic(diag); + } + } var TypeFacts; (function (TypeFacts) { TypeFacts[TypeFacts["None"] = 0] = "None"; @@ -27069,8 +28106,7 @@ var ts; 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["All"] = 4194303] = "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. @@ -27100,10 +28136,10 @@ var ts; 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["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); @@ -27135,12 +28171,6 @@ var ts; var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - /** Things we lazy load from the JSX namespace */ - var jsxTypes = ts.createUnderscoreEscapedMap(); var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var definitelyAssignableRelation = ts.createMap(); @@ -27196,6 +28226,7 @@ var ts; TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType"; TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject"; TypeIncludes[TypeIncludes["Union"] = 2048] = "Union"; + TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard"; })(TypeIncludes || (TypeIncludes = {})); var MembersOrExportsResolutionKind; (function (MembersOrExportsResolutionKind) { @@ -27343,7 +28374,23 @@ var ts; }; } } - function getJsxNamespace() { + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } if (!_jsxNamespace) { _jsxNamespace = "React"; if (compilerOptions.jsxFactory) { @@ -27382,35 +28429,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 107455 /* BlockScopedVariableExcludes */; + result |= 67216319 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 107454 /* FunctionScopedVariableExcludes */; + result |= 67216318 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; + result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 106927 /* FunctionExcludes */; + result |= 67215791 /* FunctionExcludes */; if (flags & 32 /* Class */) - result |= 899519 /* ClassExcludes */; + result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 792968 /* InterfaceExcludes */; + result |= 67901832 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) - result |= 899327 /* RegularEnumExcludes */; + result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) - result |= 899967 /* ConstEnumExcludes */; + result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 106639 /* ValueModuleExcludes */; + result |= 67215503 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 99263 /* MethodExcludes */; + result |= 67208127 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 41919 /* GetAccessorExcludes */; + result |= 67150783 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 74687 /* SetAccessorExcludes */; + result |= 67183551 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 530920 /* TypeParameterExcludes */; + result |= 67639784 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 793064 /* TypeAliasExcludes */; + result |= 67901928 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -27439,7 +28486,7 @@ var ts; } function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - source.flags & 67108864 /* JSContainer */ || target.flags & 67108864 /* JSContainer */) { + (source.flags | 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 @@ -27463,6 +28510,13 @@ var ts; target.exports = ts.createSymbolTable(); mergeSymbolTable(target.exports, source.exports); } + if ((source.flags | target.flags) & 67108864 /* JSContainer */) { + var sourceInitializer = ts.getJSInitializerSymbol(source); + var targetInitializer = ts.getJSInitializerSymbol(target); + if (sourceInitializer !== source || targetInitializer !== target) { + mergeSymbol(targetInitializer, sourceInitializer); + } + } recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { @@ -27475,10 +28529,12 @@ var ts; ? 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)); + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); } } @@ -27599,8 +28655,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -27736,7 +28792,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -27745,7 +28801,7 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + if (meaning & 67216319 /* 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 @@ -27753,7 +28809,7 @@ var ts; useResult = lastLocation.kind === 148 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 148 /* Parameter */); + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } else if (location.kind === 170 /* ConditionalType */) { @@ -27825,7 +28881,7 @@ var ts; 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 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -27835,7 +28891,7 @@ var ts; case 233 /* ClassDeclaration */: case 203 /* ClassExpression */: case 234 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064 /* Type */)) { + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -27862,7 +28918,7 @@ var ts; // 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 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -27882,7 +28938,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 234 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -28004,14 +29060,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // 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 */) { + if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 240 /* 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)); @@ -28027,7 +29083,7 @@ var ts; case 234 /* InterfaceDeclaration */: case 236 /* EnumDeclaration */: case 235 /* TypeAliasDeclaration */: - case 237 /* ModuleDeclaration */:// For `namespace N { N; }` + case 237 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -28104,8 +29160,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~1920 /* Namespace */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -28124,12 +29181,12 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67216319 /* 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 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* 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; @@ -28138,15 +29195,15 @@ var ts; return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - 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 (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* 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 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* 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; @@ -28207,14 +29264,18 @@ var ts; ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */)); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { 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, "default" /* Default */, dontResolveAlias)) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); + if (defaultExportSymbol && defaultExportSymbol.valueDeclaration && isSyntacticDefault(defaultExportSymbol.valueDeclaration)) { 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 @@ -28251,7 +29312,7 @@ var ts; if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && hasSyntheticDefault) { + else if (hasSyntheticDefault) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -28284,7 +29345,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -28339,7 +29400,15 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + var moduleName = getFullyQualifiedName(moduleSymbol); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } return symbol; } @@ -28357,7 +29426,7 @@ var ts; resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(node.expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { @@ -28370,7 +29439,7 @@ var ts; case 246 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 250 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 247 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 240 /* NamespaceExportDeclaration */: @@ -28381,7 +29450,7 @@ var ts; * 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 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } return symbol && (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */; } function resolveSymbol(symbol, dontResolveAlias) { @@ -28413,7 +29482,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -28461,7 +29530,7 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 241 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -28474,39 +29543,43 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === namespaceMeaning ? 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 === 145 /* QualifiedName */ || name.kind === 183 /* PropertyAccessExpression */) { - var left = void 0; - if (name.kind === 145 /* QualifiedName */) { - left = name.left; - } - else if (name.kind === 183 /* PropertyAccessExpression */) { - 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 left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); + var namespace = resolveEntityName(left, namespaceMeaning, 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); + if (ts.isInJavaScriptFile(name)) { + var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + if (initializer) { + namespace = getSymbolOfNode(initializer); + } + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { @@ -28550,6 +29623,9 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); } @@ -28571,10 +29647,8 @@ var ts; 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.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + else { + addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); } // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. return undefined; @@ -28597,6 +29671,12 @@ var ts; } return undefined; } + function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = packageId && ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)); + return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } // 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) { @@ -28772,7 +29852,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); + return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -28872,13 +29952,21 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // 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 */; + return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { return undefined; } - var visitedSymbolTables = []; + var id = "" + getSymbolId(symbol); + var visitedSymbolTables; + if (visitedSymbolTablesMap.has(id)) { + visitedSymbolTables = visitedSymbolTablesMap.get(id); + } + else { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) @@ -28895,7 +29983,7 @@ var ts; // 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); + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && @@ -28913,7 +30001,8 @@ var ts; // Check if symbol is any of the alias return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 /* Alias */ - && symbolFromSymbolTable.escapedName !== "export=" + && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ + && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.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))) { @@ -28976,11 +30065,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } /** @@ -29089,7 +30178,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 146 /* ComputedPropertyName */) { // Typeof value - meaning = 107455 /* Value */ | 1048576 /* ExportValue */; + meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 145 /* QualifiedName */ || entityName.kind === 183 /* PropertyAccessExpression */ || entityName.parent.kind === 241 /* ImportEqualsDeclaration */) { @@ -29099,7 +30188,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 793064 /* Type */; + meaning = 67901928 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -29150,6 +30239,7 @@ var ts; } } function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; } if (writer === void 0) { writer = ts.createTextWriter(""); } var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); @@ -29232,7 +30322,8 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined + symbolStack: undefined, + inferTypeParameters: undefined }; } function typeToTypeNodeHelper(type, context) { @@ -29256,12 +30347,12 @@ var ts; } if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67901928 /* 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 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { @@ -29275,6 +30366,9 @@ var ts; } if (type.flags & 1024 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeQueryNode(symbolToName(type.symbol, context, 67216319 /* Value */, /*expectsIdentifier*/ false)); + } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } @@ -29316,7 +30410,10 @@ var ts; return typeReferenceToTypeNode(type); } if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - var name = type.symbol ? symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); + if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + } + var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -29356,13 +30453,16 @@ var ts; } if (type.flags & 2097152 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); - var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); - var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 4194304 /* Substitution */) { - return typeToTypeNodeHelper(type.typeParameter, context); + return typeToTypeNodeHelper(type.typeVariable, context); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { @@ -29381,14 +30481,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 203 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); + return createTypeQueryNodeFromSymbol(symbol, 67216319 /* 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) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 67901928 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -29465,7 +30565,7 @@ var ts; } function symbolToTypeReferenceName(symbol) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display - var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); return entityName; } function typeReferenceToTypeNode(type) { @@ -29493,7 +30593,8 @@ var ts; } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 203 /* ClassExpression */) { + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } else { @@ -29527,7 +30628,7 @@ var ts; } } } - var entityName = undefined; + var entityName = void 0; var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); @@ -29602,12 +30703,12 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } } - var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { @@ -29704,7 +30805,7 @@ var ts; if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); + var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); @@ -29938,9 +31039,6 @@ var ts; node.parent.kind === 238 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } - function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; - } function isDefaultBindingContext(location) { return location.kind === 272 /* SourceFile */ || ts.isAmbientModule(location); } @@ -29981,8 +31079,8 @@ var ts; return "(Anonymous function)"; } } - if (symbol.syntheticLiteralTypeOrigin) { - var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (symbol.nameType && symbol.nameType.flags & 32 /* StringLiteral */) { + var stringValue = symbol.nameType.value; if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; } @@ -30079,10 +31177,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 247 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 250 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -30103,7 +31201,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -30289,8 +31387,7 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var propType = getTypeOfPropertyOfType(parentType, text); - var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); + var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -30373,7 +31470,8 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); // Use type from type annotation if one is present var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); if (declaredType) { @@ -30440,12 +31538,19 @@ var ts; return undefined; } function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments + var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); + if (specialDeclaration) { + return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + } var types = []; + var constructorTypes; var definedInConstructor = false; var definedInMethod = false; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; + var declarationInConstructor = false; var expression = declaration.kind === 198 /* BinaryExpression */ ? declaration : declaration.kind === 183 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 198 /* BinaryExpression */) : undefined; @@ -30453,7 +31558,13 @@ var ts; return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 154 /* Constructor */) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + declarationInConstructor = thisContainer.kind === 154 /* Constructor */ || + thisContainer.kind === 232 /* FunctionDeclaration */ || + (thisContainer.kind === 190 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + if (declarationInConstructor) { definedInConstructor = true; } else { @@ -30475,11 +31586,34 @@ var ts; } 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_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); + var anyedType = type_2; + if (isEmptyArrayLiteralType(type_2)) { + anyedType = anyArrayType; + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + } + types.push(anyedType); + if (declarationInConstructor) { + (constructorTypes || (constructorTypes = [])).push(anyedType); + } } } - var type = jsDocType || getUnionType(types, 2 /* Subtype */); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + var type = jsDocType; + if (!type) { + // use only the constructor types unless only null | undefined (including widening variants) were assigned there + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~12288 /* Nullable */); }) === neverType) { + if (noImplicitAny) { + reportImplicitAnyError(symbol.valueDeclaration, anyType); + } + return anyType; + } + return widened; } // 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 @@ -30500,12 +31634,12 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var hasComputedProperties = false; + var objectFlags = 128 /* ObjectLiteral */; 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; + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; return; } if (e.dotDotDotToken) { @@ -30520,12 +31654,11 @@ var ts; members.set(symbol.escapedName, symbol); }); var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 33554432 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; } - if (hasComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } return result; } // Return the type implied by an array binding pattern @@ -30722,6 +31855,7 @@ var ts; if (getter && getter.body) { type = getReturnTypeFromBody(getter); } + // Otherwise, fall back to 'any'. else { if (noImplicitAny) { if (setter) { @@ -30786,7 +31920,7 @@ var ts; // 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 */ + links.type = targetSymbol.flags & 67216319 /* Value */ ? getTypeOfSymbol(targetSymbol) : unknownType; } @@ -31166,7 +32300,7 @@ 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 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -31530,7 +32664,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 107455 /* Value */) { + if (symbolFlags & 67216319 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; @@ -31593,8 +32727,18 @@ var ts; error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } + var symbolLinks_1 = getSymbolLinks(lateSymbol); + if (!symbolLinks_1.nameType) { + // Retain link to name type so that it can be reused later + symbolLinks_1.nameType = type; + } addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); - lateSymbol.parent = parent; + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } return links.resolvedSymbol = lateSymbol; } } @@ -31796,7 +32940,7 @@ var ts; } return [signature]; } - var result = undefined; + var result; for (var i = 0; i < signatureLists.length; i++) { // 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); @@ -31813,7 +32957,7 @@ var ts; // 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; + var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; @@ -31944,7 +33088,7 @@ var ts; else { // Combinations of function, class, enum and module var members = emptySymbols; - var stringIndexInfo = undefined; + var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); } @@ -32043,13 +33187,12 @@ var ts; // 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 templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = ts.escapeLeadingUnderscores(t.value); + var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); @@ -32066,7 +33209,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } - prop.syntheticLiteralTypeOrigin = t; + prop.nameType = t; members.set(propName, prop); } else if (t.flags & (1 /* Any */ | 2 /* String */)) { @@ -32251,7 +33394,7 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getDefaultConstraintOfConditionalType(type) { - return getUnionType([type.trueType, type.falseType]); + return getUnionType([getInferredTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); } function getConstraintOfDistributiveConditionalType(type) { // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained @@ -32259,13 +33402,11 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (isDistributiveConditionalType(type)) { + if (type.root.isDistributive) { var constraint = getConstraintOfType(type.checkType); if (constraint) { - var target = type.target || type; - var mapper = createTypeMapper([target.checkType], [constraint]); - var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper; - return instantiateType(target, combinedMapper); + var mapper = createTypeMapper([type.root.checkType], [constraint]); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); } } return undefined; @@ -32273,17 +33414,27 @@ var ts; function getConstraintOfConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } - function getBaseConstraintOfType(type) { + function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { if (type.flags & (7372800 /* InstantiableNonPrimitive */ | 393216 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 524288 /* Index */) { + } + function getBaseConstraintOfType(type) { + var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); + if (!constraint && type.flags & 524288 /* Index */) { return stringType; } - return undefined; + return constraint; + } + /** + * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` + * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable) + */ + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; } function hasNonCircularBaseConstraint(type) { return getResolvedBaseConstraint(type) !== circularConstraintType; @@ -32323,8 +33474,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -32347,7 +33498,8 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 2097152 /* Conditional */) { - return getBaseConstraint(getConstraintOfConditionalType(t)); + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); } if (t.flags & 4194304 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -32458,7 +33610,7 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; + var commonType; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; if (prop.declarations) { @@ -32598,23 +33750,13 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 279 /* JSDocOptionalType */) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 279 /* JSDocOptionalType */; - } - } - } - } + return ts.isInJavaScriptFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 279 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 279 /* JSDocOptionalType */; + })); } function tryFindAmbientModule(moduleName, withAugmentations) { if (ts.isExternalModuleNameRelative(moduleName)) { @@ -32715,11 +33857,15 @@ var ts; var parameters = []; var hasLiteralTypes = false; var minArgumentCount = 0; - var thisParameter = undefined; + var thisParameter = void 0; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJavaScriptFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(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. @@ -32728,7 +33874,7 @@ var ts; var paramSymbol = param.symbol; // 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); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -32744,8 +33890,8 @@ var ts; // 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) || - isUntypedSignatureInJSFile; + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -32770,18 +33916,21 @@ var ts; } return links.resolvedSignature; } + /** + * A JS function gets a synthetic rest parameter if it references `arguments` AND: + * 1. It has no parameters but at least one `@param` with a type that starts with `...` + * OR + * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` + */ function maybeAddJsSyntheticRestParameter(declaration, parameters) { - // JS functions get a free rest parameter if: - // a) The last parameter has `...` preceding its type - // b) It references `arguments` somewhere + if (!containsArgumentsReference(declaration)) { + return false; + } var lastParam = ts.lastOrUndefined(declaration.parameters); - var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); var lastParamVariadicType = 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; @@ -32847,32 +33996,18 @@ var ts; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; - switch (node.kind) { - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 280 /* 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) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); + if (!ts.isFunctionLike(node)) + continue; + // 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) { + continue; + } } + result.push(getSignatureFromDeclaration(node)); } return result; } @@ -32968,7 +34103,10 @@ var ts; return instantiation; } function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); } function getErasedSignature(signature) { return signature.typeParameters ? @@ -33242,6 +34380,7 @@ var ts; if (ts.isEntityNameExpression(expr)) { return expr; } + // fall through; } return undefined; } @@ -33264,24 +34403,23 @@ var ts; var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 32768 /* TypeParameter */ ? getConstrainedTypeParameter(res, node) : res : + res.flags & 32768 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : unknownType; } - if (!(symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67216319 /* 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 assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + var referenceType = valueType.symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType || assignedType) { + return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -33297,24 +34435,33 @@ var ts; return getInferredClassType(symbol); } } - function getSubstitutionType(typeParameter, substitute) { + function getSubstitutionType(typeVariable, substitute) { var result = createType(4194304 /* Substitution */); - result.typeParameter = typeParameter; + result.typeVariable = typeVariable; result.substitute = substitute; return result; } - function getConstrainedTypeParameter(typeParameter, node) { + function isUnaryTupleTypeNode(node) { + return node.kind === 167 /* TupleType */ && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { var constraints; while (ts.isPartOfTypeNode(node)) { var parent = node.parent; if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) { - if (getTypeFromTypeNode(parent.checkType) === typeParameter) { - constraints = ts.append(constraints, getTypeFromTypeNode(parent.extendsType)); + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); } } node = parent; } - return constraints ? getSubstitutionType(typeParameter, getIntersectionType(ts.append(constraints, typeParameter))) : typeParameter; + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { return node.flags & 1048576 /* JSDoc */ && node.kind === 161 /* TypeReference */; @@ -33382,10 +34529,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 793064 /* Type */; + var meaning = 67901928 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 107455 /* Value */; + meaning |= 67216319 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -33440,10 +34587,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -33494,18 +34641,9 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67901928 /* 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 /* 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. */ @@ -33617,6 +34755,8 @@ var ts; } else if (flags & 1 /* Any */) { includes |= 1 /* Any */; + if (type === wildcardType) + includes |= 4096 /* Wildcard */; } else if (!strictNullChecks && flags & 12288 /* Nullable */) { if (flags & 4096 /* Undefined */) @@ -33737,7 +34877,7 @@ var ts; var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); if (includes & 1 /* Any */) { - return anyType; + return includes & 4096 /* Wildcard */ ? wildcardType : anyType; } switch (unionReduction) { case 1 /* Literal */: @@ -33830,6 +34970,8 @@ var ts; } else if (flags & 1 /* Any */) { includes |= 1 /* Any */; + if (type === wildcardType) + includes |= 4096 /* Wildcard */; } else if (flags & 16384 /* Never */) { includes |= 8 /* Never */; @@ -33880,7 +35022,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return anyType; + return includes & 4096 /* Wildcard */ ? wildcardType : anyType; } if (includes & 1024 /* EmptyObject */ && !(includes & 512 /* ObjectType */)) { typeSet.push(emptyObjectType); @@ -33922,19 +35064,29 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? - neverType : - getLiteralType(ts.symbolName(prop)); + var links = getSymbolLinks(getLateBoundSymbol(prop)); + if (!links.nameType) { + if (links.target && links.target !== unknownSymbol && links.target !== resolvingSymbol && links.target.escapedName === prop.escapedName) { + links.nameType = getLiteralTypeFromPropertyName(links.target); + } + else { + links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? + neverType : + getLiteralType(ts.symbolName(prop)); + } + } + return links.nameType; } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) : - ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : - type === wildcardType ? wildcardType : - type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : - getLiteralTypeFromPropertyNames(type); + return type.flags & 262144 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) : + maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : + getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); @@ -33997,6 +35149,9 @@ var ts; } return indexInfo.type; } + if (indexType.flags & 16384 /* Never */) { + return neverType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (getIndexTypeOfType(objectType, 1 /* Number */)) { @@ -34095,10 +35250,13 @@ var ts; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper; + var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } // 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 @@ -34137,7 +35295,13 @@ var ts; function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 1048576 /* IndexedAccess */ && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; } return links.resolvedType; } @@ -34155,76 +35319,74 @@ var ts; } return links.resolvedType; } - function getActualTypeParameter(type) { - return type.flags & 4194304 /* Substitution */ ? type.typeParameter : type; + function getActualTypeVariable(type) { + return type.flags & 4194304 /* Substitution */ ? type.typeVariable : type; } - function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) { - var type = createType(2097152 /* Conditional */); - type.checkType = checkType; - type.extendsType = extendsType; - type.trueType = trueType; - type.falseType = falseType; - type.inferTypeParameters = inferTypeParameters; - type.target = target; - type.mapper = mapper; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - return type; - } - function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) { - // Instantiate extends type without instantiating any 'infer T' type parameters - var extendsType = instantiateType(baseExtendsType, mapper); - // Return falseType for a definitely false extends check. We check an instantations of the two - // types with type parameters mapped to the wildcard type, the most permissive instantiations - // possible (the wildcard type is assignable to and from all types). If those are not related, - // then no instatiations will be and we can just return the false branch type. - if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) { - return instantiateType(baseFalseType, mapper); + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; } - // The check could be true for some instantiation + // If this is a distributive conditional type and the check type is generic we need to defer + // resolution of the conditional type such that a later instantiation will properly distribute + // over union types. + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */); var combinedMapper; - if (inferTypeParameters) { - var inferences = ts.map(inferTypeParameters, createInferenceInfo); - // We don't want inferences from constraints as they may cause us to eagerly resolve the - // conditional type instead of deferring resolution. Also, we always want strict function - // types rules (i.e. proper contravariance) for inferences. - inferTypes(inferences, checkType, extendsType, 8 /* NoConstraints */ | 16 /* AlwaysStrict */); - // We infer 'never' when there are no candidates for a type parameter - var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; }); - var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes); - combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + } + combinedMapper = combineTypeMappers(mapper, context); } - // Return union of trueType and falseType for any and never since they match anything - if (checkType.flags & 1 /* Any */ || (checkType.flags & 16384 /* Never */ && !(extendsType.flags & 16384 /* Never */))) { - return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]); - } - // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType; - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type - // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { - return instantiateType(baseTrueType, combinedMapper || mapper); + if (!isDeferred) { + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // Return falseType for a definitely false extends check. We check an instantations of the two + // types with type parameters mapped to the wildcard type, the most permissive instantiations + // possible (the wildcard type is assignable to and from all types). If those are not related, + // then no instatiations will be and we can just return the false branch type. + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + // Return trueType for a definitely true extends check. The definitely assignable relation excludes + // type variable constraints from consideration. Without the definitely assignable relation, the type + // type Foo = T extends { x: string } ? string : number + // would immediately resolve to 'string' instead of being deferred. + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } } // Return a deferred type for a check that is neither definitely true nor definitely false - var erasedCheckType = getActualTypeParameter(checkType); - var trueType = instantiateType(baseTrueType, mapper); - var falseType = instantiateType(baseFalseType, mapper); - // We compute the cache key from the ids of the four constituent types, plus an indicator of whether the - // type is distributive (i.e. whether the original declaration has a type parameter as the check type). - var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 /* TypeParameter */ ? 1 : 0; - var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive; - var cached = conditionalTypes.get(id); - if (cached) { - return cached; - } - var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper)); - conditionalTypes.set(id, result); + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(2097152 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); return result; } - function isDistributiveConditionalType(type) { - return !!((type.target || type).checkType.flags & 32768 /* TypeParameter */); + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferredTrueTypeFromConditionalType(type) { + return type.combinedMapper ? + type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper)) : + getTrueTypeFromConditionalType(type); } function getInferTypeParameters(node) { var result; @@ -34240,7 +35402,28 @@ var ts; function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), /*target*/ undefined, /*mapper*/ undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var checkType = getTypeFromTypeNode(node.checkType); + var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 32768 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: getAliasSymbolForTypeNode(node), + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, /*mapper*/ undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } } return links.resolvedType; } @@ -34496,9 +35679,10 @@ var ts; return getTypeFromIntersectionTypeNode(node); case 277 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); + case 279 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); case 172 /* ParenthesizedType */: case 278 /* JSDocNonNullableType */: - case 279 /* JSDocOptionalType */: case 274 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); case 281 /* JSDocVariadicType */: @@ -34585,14 +35769,18 @@ var ts; return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { - return !!mapper.signature; + return !!mapper.typeParameters; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { @@ -34718,8 +35906,8 @@ var ts; // between the node and the type parameter declaration, if the node contains actual references to the // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_1 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 211 /* Block */ ? "quit" : n === container_1; })) { + var container_2 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 211 /* Block */ ? "quit" : n === container_2; })) { return ts.forEachChild(node, containsReference); } } @@ -34774,22 +35962,35 @@ var ts; return result; } function getConditionalTypeInstantiation(type, mapper) { - var target = type.target || type; - var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + var root = type.root; + if (root.outerTypeParameters) { + // We are instantiating a conditional 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 typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { // Check if we have a conditional type where the check type is a naked type parameter. If so, // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). - if (isDistributiveConditionalType(target)) { - var checkType_1 = target.checkType; - var instantiatedType = combinedMapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072 /* Union */) { - return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); }); + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 /* Union */ | 16384 /* Never */)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } - return instantiateConditionalType(target, combinedMapper); - } - function instantiateConditionalType(type, mapper) { - return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments); + return getConditionalType(root, mapper); } function instantiateType(type, mapper) { if (type && mapper && mapper !== identityMapper) { @@ -34830,10 +36031,10 @@ var ts; return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } if (type.flags & 2097152 /* Conditional */) { - return getConditionalTypeInstantiation(type, mapper); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } if (type.flags & 4194304 /* Substitution */) { - return mapper(type.typeParameter); + return instantiateType(type.typeVariable, mapper); } } return type; @@ -34900,7 +36101,8 @@ var ts; return node.body.kind === 211 /* Block */ ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { if (type.flags & 65536 /* Object */) { @@ -35374,10 +36576,10 @@ var ts; target = target.regularType; } if (source.flags & 4194304 /* Substitution */) { - source = relation === definitelyAssignableRelation ? source.typeParameter : source.substitute; + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } if (target.flags & 4194304 /* Substitution */) { - target = target.typeParameter; + target = target.typeVariable; } // 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) @@ -35503,11 +36705,11 @@ var ts; } } if (flags & 2097152 /* Conditional */) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { - if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { return result; } } @@ -35895,20 +37097,14 @@ var ts; } } else if (source.flags & 2097152 /* Conditional */) { - if (relation !== definitelyAssignableRelation) { - var constraint = getConstraintOfDistributiveConditionalType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } if (target.flags & 2097152 /* Conditional */) { - if (isTypeIdenticalTo(source.checkType, target.checkType) && - isTypeIdenticalTo(source.extendsType, target.extendsType)) { - if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { - result &= isRelatedTo(source.falseType, target.falseType, reportErrors); + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -35916,9 +37112,21 @@ var ts; } } } - else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } } else { @@ -36264,6 +37472,11 @@ var ts; if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { continue; } + // Skip over symbol-named members + var nameType = getLiteralTypeFromPropertyName(prop); + if (nameType !== undefined && !(isRelatedTo(nameType, stringType) || isRelatedTo(nameType, numberType))) { + continue; + } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -36783,8 +37996,18 @@ var ts; ts.Debug.assert(strictNullChecks); return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]); } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; + } + // Use NonNullable global type alias if available to improve quick info/declaration emit + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior + } function getNonNullableType(type) { - return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; } /** * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module @@ -36886,6 +38109,10 @@ var ts; } var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name); result.type = undefinedType; + var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name)); + if (associatedKeyType.flags & 32 /* StringLiteral */) { + result.nameType = associatedKeyType; + } undefinedProperties.set(name, result); return result; } @@ -36988,6 +38215,7 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 198 /* BinaryExpression */: case 151 /* PropertyDeclaration */: case 150 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; @@ -37049,9 +38277,10 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, compareTypes, baseInferences) { - var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); var context = mapper; + context.typeParameters = typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -37170,7 +38399,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return getTypeFromInference(inference) || emptyObjectType; + return getTypeFromInference(inference); } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -37185,21 +38414,38 @@ var ts; } return undefined; } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with different arity are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && getTypeReferenceArity(source) !== getTypeReferenceArity(target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : - undefined; + emptyObjectType; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; var contravariant = false; + var propagationType; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; } + if (source === wildcardType) { + // We are inferring from an 'any' type. We want to infer this type for every type parameter + // referenced in the target type, so we record it as the propagation type and infer from the + // target to itself. Then, as we find candidates we substitute the propagation type. + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + 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. @@ -37269,14 +38515,15 @@ var ts; inference.priority = priority; } if (priority === inference.priority) { + var candidate = propagationType || source; if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, source); + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, source); + inference.candidates = ts.append(inference.candidates, candidate); } } - if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -37306,7 +38553,10 @@ var ts; else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; + var savePriority = priority; + priority |= 16 /* LiteralKeyof */; inferFromTypes(empty, target.type); + priority = savePriority; contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { @@ -37316,8 +38566,8 @@ var ts; else if (source.flags & 2097152 /* Conditional */ && target.flags & 2097152 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(source.trueType, target.trueType); - inferFromTypes(source.falseType, target.falseType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else if (target.flags & 393216 /* UnionOrIntersection */) { var targetTypes = target.types; @@ -37353,7 +38603,7 @@ var ts; } } else { - if (!(priority && 8 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) { + if (!(priority & 32 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) { source = getApparentType(source); } if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) { @@ -37384,7 +38634,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 16 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -37423,7 +38673,7 @@ var ts; var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 2 /* MappedType */; + priority |= 2 /* HomomorphicMappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -37433,14 +38683,16 @@ var ts; 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. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); return; } } - // 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)) { + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0 /* Call */); inferFromSignatures(source, target, 1 /* Construct */); @@ -37538,62 +38790,73 @@ var ts; } return candidates; } + function getContravariantInference(inference) { + return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, context, signature) { + // 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 occurrences 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 widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + 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 = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } 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(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 = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? - getUnionType(baseCandidates, 2 /* Subtype */) : - getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unwidenedType); - // If we have inferred 'never' but have contravariant candidates. To get a more specific type we - // infer from the contravariant candidates instead. - if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { - inferredType = getCommonSubtype(inference.contraCandidates); + var signature = context.signature; + if (signature) { + if (inference.candidates) { + inferredType = getCovariantInference(inference, context, signature); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getContravariantInference(inference); + } } - } - else if (inference.contraCandidates) { - // We only have contravariant inferences, infer the best common subtype of those - inferredType = getCommonSubtype(inference.contraCandidates); - } - else if (context.flags & 2 /* NoDefault */) { - // We use silentNeverType as the wildcard that signals no inferences. - 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 if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getContravariantInference(inference); + } + else if (context.flags & 2 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + // 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 /* AnyDefault */)); + } } } + else { + inferredType = getTypeFromInference(inference); + } inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -37618,7 +38881,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -37638,7 +38901,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -37857,8 +39120,8 @@ var ts; } if (flags & 65536 /* Object */) { return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : - strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (2048 /* Void */ | 4096 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -37870,7 +39133,7 @@ var ts; return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } if (flags & 134217728 /* NonPrimitive */) { - return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & 7897088 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); @@ -37878,7 +39141,7 @@ var ts; if (flags & 393216 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 8388607 /* All */; + return 4194303 /* All */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -37892,7 +39155,7 @@ var ts; } function getTypeOfDestructuredProperty(type, name) { var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType; @@ -38076,6 +39339,9 @@ 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, noReductions) { + if (type.flags & 16384 /* Never */) { + return type; + } if (!(type.flags & 131072 /* Union */)) { return mapper(type); } @@ -38914,29 +40180,28 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } - function isApparentTypePosition(node) { + function isConstraintPosition(node) { var parent = node.parent; return parent.kind === 183 /* PropertyAccessExpression */ || parent.kind === 185 /* CallExpression */ && parent.expression === node || parent.kind === 184 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 207 /* NonNullExpression */ || parent.kind === 180 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 7372800 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getApparentTypeForLocation(type, node) { + function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getApparentType); + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); } return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -39008,7 +40273,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -39572,47 +40837,47 @@ var ts; // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter) { var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = func.parameters.indexOf(parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(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)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = func.parameters.indexOf(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)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } - 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. @@ -39658,7 +40923,7 @@ var ts; var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { + if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function return undefined; } var contextualReturnType = getContextualReturnType(func); @@ -39736,9 +41001,11 @@ var ts; 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. + // expression has no contextual type, the right operand is contextually typed by the type of the left operand, + // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right ? getTypeOfExpression(left, /*cache*/ true) : type; + return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? + getTypeOfExpression(left, /*cache*/ true) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; @@ -39761,6 +41028,7 @@ var ts; case 2 /* ModuleExports */: case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: + case 6 /* Prototype */: return false; default: ts.Debug.assertNever(kind); @@ -39826,7 +41094,7 @@ var ts; function getContextualTypeForChildJsxExpression(node) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // 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(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; } function getContextualTypeForJsxExpression(node) { @@ -39978,15 +41246,9 @@ var ts; return anyType; } var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } - function getJsxSignaturesParameterTypes(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false); - } - function getJsxSignaturesParameterTypesJs(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true); - } - function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + function getJsxSignaturesParameterTypes(valueType, isJs, context) { // 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 (valueType.flags & 2 /* String */) { return anyType; @@ -39996,7 +41258,7 @@ var ts; // For example: // var CustomTag: "h1" = "h1"; // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = valueType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -40022,21 +41284,24 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */); + if (context.typeArguments) { + signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + } + return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); } - function getJsxPropsTypeFromCallSignature(sig) { + function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignature(sig); - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { propsType = intersectTypes(intrinsicAttribs, propsType); } return propsType; } - function getJsxPropsTypeFromClassType(hostClassType, isJs) { + function getJsxPropsTypeFromClassType(hostClassType, isJs, context) { if (isTypeAny(hostClassType)) { return hostClassType; } - var propsName = getJsxElementPropertiesName(); + var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context)); if (propsName === undefined) { // There is no type ElementAttributesProperty, return 'any' return anyType; @@ -40058,14 +41323,14 @@ var ts; else { // Normal case -- add in IntrinsicClassElements and IntrinsicElements var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); if (intrinsicClassAttribs !== unknownType) { var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); apparentAttributesType = intersectTypes(typeParams ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) : intrinsicClassAttribs, apparentAttributesType); } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); } @@ -40073,18 +41338,12 @@ var ts; } } } - function getJsxPropsTypeFromConstructSignatureJs(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true); - } - function getJsxPropsTypeFromConstructSignature(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false); - } - function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + function getJsxPropsTypeFromConstructSignature(sig, isJs, context) { var hostClassType = getReturnTypeOfSignature(sig); if (hostClassType) { - return getJsxPropsTypeFromClassType(hostClassType, isJs); + return getJsxPropsTypeFromClassType(hostClassType, isJs, context); } - return getJsxPropsTypeFromCallSignature(sig); + return getJsxPropsTypeFromCallSignature(sig, context); } // 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. @@ -40133,7 +41392,16 @@ var ts; // union type of return types from these signatures function getContextualSignature(node) { ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); + var type; + if (ts.isInJavaScriptFile(node)) { + var jsdoc = ts.getJSDocType(node); + if (jsdoc) { + type = getTypeFromTypeNode(jsdoc); + } + } + if (!type) { + type = getContextualTypeForFunctionLikeDeclaration(node); + } if (!type) { return undefined; } @@ -40326,19 +41594,29 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createSymbolTable(); + var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; var propagatedFlags = 8388608 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 178 /* ObjectBindingPattern */ || contextualType.pattern.kind === 182 /* ObjectLiteralExpression */); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node); + var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - var isInJSFile = ts.isInJavaScriptFile(node); + if (isInJSFile && node.properties.length === 0) { + // an empty JS object literal that nonetheless has members is a JS namespace + var symbol = getSymbolOfNode(node); + if (symbol.exports) { + propertiesTable = symbol.exports; + symbol.exports.forEach(function (symbol) { return propertiesArray.push(getMergedSymbol(symbol)); }); + return createObjectLiteralType(); + } + } + propertiesTable = ts.createSymbolTable(); var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; @@ -40374,9 +41652,13 @@ var ts; } typeFlags |= type.flags; var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; - var prop = nameType && isTypeUsableAsLateBoundName(nameType) + var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType); + var prop = hasLateBoundName ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); + if (hasLateBoundName) { + prop.nameType = nameType; + } 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. @@ -40500,7 +41782,7 @@ var ts; } function checkJsxSelfClosingElement(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxElement(node, checkMode) { // Check attributes @@ -40512,14 +41794,16 @@ var ts; else { checkExpression(node.closingElement.tagName); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxFragment(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); - if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { - error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } /** * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers @@ -40564,7 +41848,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -40631,7 +41915,10 @@ var ts; if (hasSpreadAnyType) { return anyType; } - return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + if (typeToIntersect && spread !== emptyObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -40669,12 +41956,11 @@ var ts; function checkJsxAttributes(node, checkMode) { return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType; } /** * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic @@ -40685,11 +41971,11 @@ var ts; function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); if (intrinsicElementsType !== unknownType) { // Property case if (!ts.isIdentifier(node.tagName)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); if (intrinsicProp) { links.jsxFlags |= 1 /* IntrinsicNamedElement */; @@ -40738,20 +42024,66 @@ var ts; } // Instantiate in context of source type var instantiatedSignatures = []; + var candidateForTypeArgumentError; + var hasTypeArgumentError = !!node.typeArguments; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); + if (typeArgumentInstantiated) { + hasTypeArgumentError = false; + instantiatedSignatures.push(typeArgumentInstantiated); + } + else { + if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + candidateForTypeArgumentError = signature; + } + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } } else { instantiatedSignatures.push(signature); } } + if (node.typeArguments && hasTypeArgumentError) { + if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); + } + // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine + else if (node.typeArguments.length !== 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); + } + } return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } + function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (!node.typeArguments) { + return; + } + if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + return; + } + var args = checkTypeArguments(signature, node.typeArguments, reportErrors); + if (!args) { + return; + } + return getSignatureInstantiation(signature, args, isJavascript); + } + function getJsxNamespaceAt(location) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + return candidate; + } + } + // JSX global fallback + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + } /** * 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. @@ -40759,11 +42091,9 @@ var ts; * @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) { - // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -40773,6 +42103,8 @@ var ts; if (propertiesOfJsxElementAttribPropInterface.length === 0) { return ""; } + // Element Attributes has one property, so the element attributes type will be the type of the corresponding + // property of the class instance type else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } @@ -40788,19 +42120,11 @@ var ts; /// 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; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } - function getJsxElementChildrenPropertyName() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - return _jsxElementChildrenPropertyName; + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } function getApparentTypeOfJsxPropsType(propsType) { if (!propsType) { @@ -40829,7 +42153,7 @@ var ts; function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); @@ -40839,7 +42163,7 @@ var ts; paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { paramType = intersectTypes(intrinsicAttributes, paramType); } @@ -40864,7 +42188,7 @@ var ts; 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(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; @@ -40898,7 +42222,7 @@ var ts; result = allMatchingAttributesType; } // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { result = intersectTypes(intrinsicAttributes, result); } @@ -40941,7 +42265,7 @@ var ts; // For example: // var CustomTag: "h1" = "h1"; // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -40971,7 +42295,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -41002,7 +42326,7 @@ var ts; * @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) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -41042,32 +42366,26 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.escapedText); return prop || unknownSymbol; } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === unknownType) + return undefined; + return type; } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); } - return deferredJsxStatelessElementType; } /** * Returns all the properties of the Jsx.IntrinsicElements interface */ - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; } function checkJsxPreconditions(errorNode) { @@ -41075,7 +42393,7 @@ var ts; if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); } - if (getJsxGlobalElementType() === undefined) { + if (getJsxElementTypeAt(errorNode) === undefined) { if (noImplicitAny) { error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); } @@ -41090,9 +42408,9 @@ var ts; // 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 reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* 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 @@ -41166,7 +42484,7 @@ var ts; // 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) || getPropertiesOfType(sourceAttributesType).length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement)))); } else { // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties @@ -41211,7 +42529,9 @@ var ts; return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || + ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */ || + ts.isInJavaScriptFile(symbol.valueDeclaration) && ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(symbol.valueDeclaration))); } /** * Check whether the requested property access is valid. @@ -41373,7 +42693,7 @@ var ts; return unknownType; } } - propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -41484,7 +42804,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455 /* Value */); + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 67216319 /* Value */); return suggestion && ts.symbolName(suggestion); } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { @@ -41499,6 +42819,10 @@ var ts; }); return result && ts.symbolName(result); } + function getSuggestionForNonexistentModule(name, targetModule) { + var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + return suggestion && ts.symbolName(suggestion); + } /** * 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. @@ -41523,7 +42847,8 @@ var ts; for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; var candidateName = ts.symbolName(candidate); - if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + if (candidateName.charCodeAt(0) === 34 /* doubleQuote */ + || !(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { continue; } var candidateNameLowerCase = candidateName.toLowerCase(); @@ -41617,15 +42942,23 @@ var ts; return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } - function isValidMethodAccess(method, type) { + function isValidMethodAccess(method, actualThisType) { var propType = getTypeOfFuncClassEnumModule(method); var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { - var thisType = getThisTypeOfSignature(sig); - return !thisType || isTypeAssignableTo(type, thisType); + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); }); } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type === unknownType || isTypeAny(type)) { return true; @@ -41876,13 +43209,7 @@ var ts; typeArguments = node.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 || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { + if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { 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. @@ -41898,6 +43225,14 @@ var ts; var hasEnoughArguments = argCount >= signature.minArgumentCount; return callIsIncomplete || hasEnoughArguments; } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + // 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); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { if (type.flags & 65536 /* Object */) { @@ -41911,13 +43246,13 @@ var ts; } // 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 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, 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 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -41968,7 +43303,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); @@ -42399,6 +43734,17 @@ var ts; return arg; } } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 187 /* TaggedTemplateExpression */; var isDecorator = node.kind === 149 /* Decorator */; @@ -42515,21 +43861,13 @@ var ts; 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; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); - } - var paramCount = min < max ? min + "-" + max : min; - diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { - var sig = signatures_6[_a]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -42601,7 +43939,7 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : + createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : undefined; while (true) { candidate = originalCandidate; @@ -43025,19 +44363,49 @@ var ts; return false; } function getJavaScriptClassType(symbol) { - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + var initializer = ts.getDeclaredJavascriptInitializer(symbol.valueDeclaration); + if (initializer) { + symbol = getSymbolOfNode(initializer); } + var inferred; if (isJavaScriptConstructor(symbol.valueDeclaration)) { - return getInferredClassType(symbol); + inferred = getInferredClassType(symbol); } - if (symbol.flags & 3 /* Variable */) { - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { - return getInferredClassType(valueType.symbol); + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + if (assignmentSymbol) { + var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); + if (prototype) { + return checkExpression(prototype); } } } + function getAssignedJavascriptPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 183 /* PropertyAccessExpression */) { + parent = parent.parent; + } + return parent && ts.isBinaryExpression(parent) && + ts.isPrototypeAccess(parent.left) && + parent.operatorToken.kind === 58 /* EqualsToken */ && + ts.isObjectLiteralExpression(parent.right) && + parent.right; + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -43115,7 +44483,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -43168,13 +44536,13 @@ var ts; return type; } function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ 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 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (!resolvedRequire) { // project does not contain symbol named 'require' - assume commonjs require return true; @@ -43365,7 +44733,7 @@ var ts; } else { var types = checkAndAggregateReturnExpressionTypes(func, checkMode); - if (functionFlags & 1 /* Generator */) { + if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { var iterableIteratorAny = functionFlags & 2 /* Async */ @@ -43434,25 +44802,21 @@ var ts; } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); + var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0; ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - // A yield* expression effectively yields everything that its operand yields - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); - } - 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); - } - ts.pushIfUnique(aggregatedTypes, type); - } + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); }); return aggregatedTypes; } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpressionCached(node.expression, checkMode) : undefinedWideningType; + // A `yield*` expression effectively yields everything that its operand yields + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.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); + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; @@ -43476,7 +44840,7 @@ var ts; } return true; } - /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ function checkAndAggregateReturnExpressionTypes(func, checkMode) { var functionFlags = ts.getFunctionFlags(func); var aggregatedTypes = []; @@ -43505,7 +44869,9 @@ var ts; if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -43576,7 +44942,6 @@ var ts; ts.Debug.assert(node.kind !== 153 /* 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 @@ -43631,7 +44996,7 @@ var ts; ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : // Async function getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function - if ((functionFlags & 1 /* Generator */) === 0) { + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } @@ -43655,11 +45020,11 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function 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); } - else { + else { // Normal function checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } @@ -44115,6 +45480,9 @@ var ts; return (target.flags & 12288 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + return checkExpression(node.right, checkMode); + } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { @@ -44324,52 +45692,35 @@ var ts; error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); } } - 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) { - // 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 */); - } - // Generator functions prior to ES2015 require the __values helper - if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && - languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256 /* Values */); - } + var func = ts.getContainingFunction(node); + var functionFlags = func ? ts.getFunctionFlags(func) : 0 /* Normal */; + if (!(functionFlags & 1 /* Generator */)) { + // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. + return anyType; + } + if (node.asteriskToken) { + // 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 & 1 /* Generator */) { - var expressionType = checkExpressionCached(node.expression); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - 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 /* Async */) !== 0) || anyType; - if (nodeIsYieldStar) { - 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, - /*headMessage*/ undefined); - } - else { - 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, - /*headMessage*/ undefined); - } - } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); } } + var isAsync = (functionFlags & 2 /* Async */) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + // 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), isAsync) || anyType; + checkTypeAssignableTo(yieldedType, signatureElementType, node.expression || node, /*headMessage*/ undefined); + } // Both yield and yield* expressions have type 'any' return anyType; } @@ -44430,10 +45781,27 @@ var ts; return node.kind === 188 /* TypeAssertionExpression */ || node.kind === 206 /* AsExpression */; } function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); - return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + var inJs = ts.isInJavaScriptFile(declaration); + var initializer = inJs && ts.getDeclaredJavascriptInitializer(declaration) || declaration.initializer; + var type = getTypeOfExpression(initializer, /*cache*/ true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (inJs) { + if (widened.flags & 12288 /* Nullable */) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyType); + } + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyArrayType); + } + return anyArrayType; + } + } + return widened; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { @@ -44514,7 +45882,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 === 185 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true) && !isSymbolOrSymbolForCall(node)) { + if (node.kind === 185 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -44816,6 +46184,7 @@ var ts; if (node.kind === 159 /* IndexSignature */) { checkGrammarIndexSignature(node); } + // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled else if (node.kind === 162 /* FunctionType */ || node.kind === 232 /* FunctionDeclaration */ || node.kind === 163 /* ConstructorType */ || node.kind === 157 /* CallSignature */ || node.kind === 154 /* Constructor */ || node.kind === 158 /* ConstructSignature */) { @@ -45634,7 +47003,7 @@ var ts; case 230 /* VariableDeclaration */: case 180 /* BindingElement */: case 232 /* FunctionDeclaration */: - case 246 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 + case 246 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -45861,7 +47230,7 @@ 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 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; if (promiseConstructorType === unknownType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -45884,7 +47253,7 @@ var ts; } // 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 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; @@ -45938,7 +47307,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -46086,7 +47455,20 @@ var ts; 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 === 145 /* QualifiedName */ ? node.name.right : node.name)); + var decl = ts.getHostSignatureFromJSDoc(node); + // don't issue an error for invalid hosts -- just functions -- + // and give a better error message when the host function mentions `arguments` + // but the tag doesn't have an array type + if (decl) { + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + } + } } } function checkJSDocAugmentsTag(node) { @@ -46095,7 +47477,7 @@ var ts; error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } - var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 285 /* JSDocAugmentsTag */); + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); 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); @@ -46158,7 +47540,7 @@ var ts; var body = node.kind === 152 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - if ((functionFlags & 1 /* Generator */) === 0) { + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ ? checkAsyncFunctionReturnType(node) // Async function : getTypeFromTypeNode(returnTypeNode)); // normal function @@ -46181,6 +47563,8 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { if (deferredUnusedIdentifierNodes) { + // TODO: GH#22580 + // Debug.assert(addToSeen(seenDeferredUnusedIdentifiers, getNodeId(node)), "Deferring unused identifier check twice"); deferredUnusedIdentifierNodes.push(node); } } @@ -46274,14 +47658,14 @@ var ts; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); + diagnostics.add(ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 /* Identifier */ && ts.idText(node).charCodeAt(0) === 95 /* _ */; + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { @@ -46340,18 +47724,60 @@ var ts; } function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports_1 = ts.createMap(); node.locals.forEach(function (local) { - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration, ts.symbolName(local)); + if (local.isReferenced || local.exportSymbol) + return; + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + var importClause = importClauseFromImported(declaration); + var key = String(getNodeId(importClause)); + var group_1 = unusedImports_1.get(key); + if (group_1) { + group_1[1].push(declaration); } + else { + unusedImports_1.set(key, [importClause, [declaration]]); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local)); } } }); + unusedImports_1.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name)); + } + } + else if (unuseds.length === 1) { + error(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)); + } + else { + error(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)); + } + }); } } + function isImportedDeclaration(node) { + return node.kind === 243 /* ImportClause */ || node.kind === 246 /* ImportSpecifier */ || node.kind === 244 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 243 /* ImportClause */ ? decl : decl.kind === 244 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function forEachImportedDeclaration(importClause, cb) { + var defaultName = importClause.name, namedBindings = importClause.namedBindings; + return (defaultName && cb(importClause)) || + namedBindings && (namedBindings.kind === 244 /* NamespaceImport */ ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); + } function checkBlock(node) { // Grammar checking for SyntaxKind.Block if (node.kind === 211 /* Block */) { @@ -46371,7 +47797,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -46405,12 +47831,12 @@ var ts; return true; } function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { + if (languageVersion <= 1 /* ES5 */ && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_this")) { potentialThisCollisions.push(node); } } function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + if (languageVersion <= 1 /* ES5 */ && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_newTarget")) { potentialNewTargetCollisions.push(node); } } @@ -46444,6 +47870,9 @@ var ts; }); } function checkCollisionWithCapturedSuperVariable(node, name) { + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } @@ -46465,7 +47894,7 @@ var ts; } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { // No need to check for require or exports for ES6 modules and later - if (modulekind >= ts.ModuleKind.ES2015) { + if (modulekind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { return; } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { @@ -46483,7 +47912,7 @@ var ts; } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } // Uninstantiated modules shouldnt do this check @@ -46533,7 +47962,7 @@ var ts; var symbol = getSymbolOfNode(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!ts.isIdentifier(node.name)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && @@ -46582,7 +48011,7 @@ var ts; 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); + var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -46701,7 +48130,8 @@ var ts; // 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 !== 219 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); + var initializer = ts.isInJavaScriptFile(node) && ts.getDeclaredJavascriptInitializer(node) || node.initializer; + checkTypeAssignableTo(checkExpressionCached(initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } } @@ -47236,7 +48666,7 @@ var ts; var isGenerator = functionFlags & 1 /* Generator */; if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (isGenerator) { + 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 types of generators when return type tracking is added @@ -47254,7 +48684,7 @@ var ts; } } else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2 /* Async */) { + if (functionFlags & 2 /* Async */) { // Async function 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) { @@ -47340,8 +48770,7 @@ var ts; return "quit"; } if (current.kind === 226 /* 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)); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } }); @@ -47696,7 +49125,7 @@ var ts; var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && baseProp) { var rootChain = function () { return ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { issuedMemberError = true; } @@ -48211,7 +49640,6 @@ var ts; // - 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); @@ -48316,7 +49744,11 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { + if (ts.nodeIsMissing(moduleName)) { + // Should be a parse error. + return false; + } + if (!ts.isStringLiteral(moduleName)) { error(moduleName, ts.Diagnostics.String_literal_expected); return false; } @@ -48327,7 +49759,7 @@ var ts; ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { // 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)) { @@ -48351,8 +49783,8 @@ var ts; // 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) | + var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | + (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 250 /* ExportSpecifier */ ? @@ -48363,7 +49795,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 250 /* ExportSpecifier */ - && !(target.flags & 107455 /* Value */) + && !(target.flags & 67216319 /* Value */) && !(node.flags & 2097152 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -48414,14 +49846,14 @@ var ts; if (node.moduleReference.kind !== 252 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 107455 /* Value */) { + if (target.flags & 67216319 /* 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 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67216319 /* 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 /* Type */) { + if (target.flags & 67901928 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -48481,7 +49913,7 @@ var ts; 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 */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* 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.idText(exportedName)); @@ -48757,8 +50189,14 @@ var ts; function checkJSDocVariadicType(node) { checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); - // Only legal location is in the *last* parameter tag. + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } @@ -48783,22 +50221,26 @@ var ts; 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); + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { /* - Only return an array type if the corresponding parameter is marked as a rest parameter. + Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: /** @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)) { + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { return createArrayType(type); } } } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } return addOptionality(type); } // Function and class expression bodies are checked after all statements in the enclosing body. This is @@ -48867,6 +50309,7 @@ var ts; checkUnusedIdentifiers(); } deferredNodes = undefined; + seenDeferredUnusedIdentifiers.clear(); deferredUnusedIdentifierNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); @@ -48969,7 +50412,7 @@ var ts; // (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(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); } break; case 190 /* FunctionExpression */: @@ -49110,7 +50553,7 @@ var ts; } if (entityName.parent.kind === 247 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } if (entityName.kind !== 183 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import @@ -49125,10 +50568,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 205 /* ExpressionWithTypeArguments */) { - meaning = 793064 /* Type */; + meaning = 67901928 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455 /* Value */; + meaning |= 67216319 /* Value */; } } else { @@ -49158,7 +50601,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 183 /* PropertyAccessExpression */ || entityName.kind === 145 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -49175,7 +50618,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 161 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 161 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 260 /* JsxAttribute */) { @@ -49251,7 +50694,7 @@ var ts; // 3). Dynamic import call or require in javascript if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 242 /* ImportDeclaration */ || node.parent.kind === 248 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } // falls through @@ -49276,7 +50719,7 @@ var ts; // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. if (location && location.kind === 269 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 107455 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -49284,7 +50727,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 4194304 /* InWithStatement */) { @@ -49469,13 +50912,13 @@ var ts; // 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 /* Value */) + ? !!(moduleSymbol.flags & 67216319 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 107455 /* Value */); + return s && !!(s.flags & 67216319 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -49525,7 +50968,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // 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 */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -49538,7 +50981,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -49634,7 +51077,7 @@ var ts; } // 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 */ && + return target.flags & 67216319 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -49647,7 +51090,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 107455 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -49659,6 +51102,8 @@ var ts; } function isImplementationOfOverload(node) { if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload @@ -49732,9 +51177,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // 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); + var valueSymbol = resolveEntityName(typeName, 67216319 /* 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); + var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -49784,7 +51229,11 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { + declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(119 /* AnyKeyword */); + } // 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 /* TypeLiteral */ | 131072 /* Signature */)) @@ -49794,18 +51243,26 @@ var ts; type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 131072 /* AddUndefined */) { + if (addUndefined) { type = getOptionalType(type); } - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { + signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(119 /* AnyKeyword */); + } var signature = getSignatureFromDeclaration(signatureDeclaration); - typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { + expr = ts.getParseTreeNode(expr, ts.isExpression); + if (!expr) { + return ts.createToken(119 /* AnyKeyword */); + } var type = getWidenedType(getRegularTypeOfExpression(expr)); - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -49824,7 +51281,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -49845,9 +51302,12 @@ var ts; } return false; } - function writeLiteralConstValue(node, writer) { + function literalTypeToNode(type) { + return ts.createLiteral(type.value); + } + function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); + return literalTypeToNode(type); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -49890,9 +51350,10 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -49914,8 +51375,7 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } }; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -49927,8 +51387,8 @@ var ts; // 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 === 183 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) - ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793064 /* Type */ | 1920 /* Namespace */; + ? 67216319 /* Value */ | 1048576 /* ExportValue */ + : 67901928 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -49992,7 +51452,7 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 237 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); if (!moduleSymbol) { return undefined; @@ -50093,7 +51553,7 @@ var ts; 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 */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -50732,6 +52192,7 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; @@ -51124,8 +52585,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } } @@ -51277,8 +52738,8 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { 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), /*length*/ 0, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } } @@ -51328,7 +52789,7 @@ var ts; case 243 /* ImportClause */: // For default import case 241 /* ImportEqualsDeclaration */: case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */:// For rename import `x as y` + case 246 /* ImportSpecifier */: // For rename import `x as y` return true; case 71 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. @@ -51374,14 +52835,14 @@ var ts; * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. */ function createNodeArray(elements, hasTrailingComma) { - if (elements) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else { if (ts.isNodeArray(elements)) { return elements; } } - else { - elements = []; - } var array = elements; array.pos = -1; array.end = -1; @@ -51412,7 +52873,7 @@ var ts; return clone; } ts.getSynthesizedClone = getSynthesizedClone; - function createLiteral(value) { + function createLiteral(value, isSingleQuote) { if (typeof value === "number") { return createNumericLiteral(value + ""); } @@ -51420,7 +52881,10 @@ var ts; return value ? createTrue() : createFalse(); } if (ts.isString(value)) { - return createStringLiteral(value); + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; } return createLiteralFromNode(value); } @@ -51493,6 +52957,15 @@ var ts; return name; } ts.createUniqueName = createUniqueName; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 5 /* OptimisticUnique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateFlags = 4 /* Node */; @@ -51531,6 +53004,49 @@ var ts; return createSynthesizedNode(86 /* FalseKeyword */); } ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(84 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(124 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(79 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(76 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(114 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(112 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(113 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(117 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(115 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(132 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(120 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { var node = createSynthesizedNode(145 /* QualifiedName */); @@ -51546,9 +53062,15 @@ var ts; : node; } ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || + expression.kind === 296 /* CommaListExpression */ ? + createParen(expression) : + expression; + } function createComputedPropertyName(expression) { var node = createSynthesizedNode(146 /* ComputedPropertyName */); - node.expression = expression; + node.expression = parenthesizeForComputedName(expression); return node; } ts.createComputedPropertyName = createComputedPropertyName; @@ -53179,31 +54701,35 @@ var ts; : node; } ts.updateJsxElement = updateJsxElement; - function createJsxSelfClosingElement(tagName, attributes) { + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(254 /* JsxSelfClosingElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxSelfClosingElement = createJsxSelfClosingElement; - function updateJsxSelfClosingElement(node, tagName, attributes) { + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxSelfClosingElement(tagName, attributes), node) + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; - function createJsxOpeningElement(tagName, attributes) { + function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(255 /* JsxOpeningElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxOpeningElement = createJsxOpeningElement; - function updateJsxOpeningElement(node, tagName, attributes) { + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxOpeningElement(tagName, attributes), node) + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxOpeningElement = updateJsxOpeningElement; @@ -53345,7 +54871,7 @@ var ts; var node = createSynthesizedNode(268 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); return node; } ts.createPropertyAssignment = createPropertyAssignment; @@ -53398,8 +54924,11 @@ var ts; } ts.updateEnumMember = updateEnumMember; // Top-level nodes - function updateSourceFileNode(node, statements) { - if (node.statements !== statements) { + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences)) { var updated = createSynthesizedNode(272 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); @@ -53407,18 +54936,15 @@ var ts; updated.fileName = node.fileName; updated.path = node.path; updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; - if (node.referencedFiles !== undefined) - updated.referencedFiles = node.referencedFiles; - if (node.typeReferenceDirectives !== undefined) - updated.typeReferenceDirectives = node.typeReferenceDirectives; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; - if (node.isDeclarationFile !== undefined) - updated.isDeclarationFile = node.isDeclarationFile; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; if (node.hasNoDefaultLib !== undefined) @@ -53455,6 +54981,12 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; return updateNode(updated, node); } return node; @@ -53998,7 +55530,8 @@ var ts; requestEmitHelper: ts.noop, resumeLexicalEnvironment: ts.noop, startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, }; function createTypeCheck(value, tag) { return tag === "undefined" @@ -54131,7 +55664,7 @@ var ts; var valuesHelper = { name: "typescript:values", scoped: false, - text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };\n " + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" }; function createValuesHelper(context, expression, location) { context.requestEmitHelper(valuesHelper); @@ -54142,7 +55675,7 @@ var ts; var readHelper = { name: "typescript:read", scoped: false, - text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };\n " + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" }; function createReadHelper(context, iteratorRecord, count, location) { context.requestEmitHelper(readHelper); @@ -54203,7 +55736,7 @@ var ts; } ts.restoreEnclosingLabel = restoreEnclosingLabel; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { - var target = skipParentheses(node); + var target = ts.skipParentheses(node); switch (target.kind) { case 71 /* Identifier */: return cacheIdentifiers; @@ -55032,7 +56565,7 @@ var ts; do { previousNode = node; if (kinds & 1 /* Parentheses */) { - node = skipParentheses(node); + node = ts.skipParentheses(node); } if (kinds & 2 /* Assertions */) { node = skipAssertions(node); @@ -55044,13 +56577,6 @@ var ts; return node; } ts.skipOuterExpressions = skipOuterExpressions; - function skipParentheses(node) { - while (node.kind === 189 /* ParenthesizedExpression */) { - node = node.expression; - } - return node; - } - ts.skipParentheses = skipParentheses; function skipAssertions(node) { while (ts.isAssertionExpression(node) || node.kind === 207 /* NonNullExpression */) { node = node.expression; @@ -55812,9 +57338,9 @@ var ts; case 253 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 254 /* JsxSelfClosingElement */: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 255 /* JsxOpeningElement */: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 256 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 257 /* JsxFragment */: @@ -56382,9 +57908,10 @@ var ts; var Debug; (function (Debug) { var isDebugInfoEnabled = false; - 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; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; 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; @@ -56489,7 +58016,7 @@ var ts; var uniqueExports = ts.createMap(); var exportedNames; var hasExportDefault = false; - var exportEquals = undefined; + var exportEquals; var hasExportStarsToExportValues = false; var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -57406,8 +58933,7 @@ var ts; case 210 /* SemicolonClassElement */: return node; default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { @@ -57578,8 +59104,7 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitSourceFile(node) { @@ -58093,7 +59618,7 @@ var ts; ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); 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))); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); } /** * Gets all property declarations with initializers on either the static or instance side of a class. @@ -58707,10 +60232,8 @@ var ts; case 86 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: - ts.Debug.failBadSyntaxKind(node.literal); - break; + return ts.Debug.failBadSyntaxKind(node.literal); } - break; case 134 /* NumberKeyword */: return ts.createIdentifier("Number"); case 138 /* SymbolKeyword */: @@ -58731,8 +60254,7 @@ var ts; case 173 /* ThisType */: break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } @@ -58756,6 +60278,8 @@ var ts; // One of the individual is global object, return immediately return serializedIndividual; } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || @@ -58919,7 +60443,7 @@ var ts; function visitPropertyNameOfClassElement(member) { var name = member.name; var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); - if (expr) { + if (expr) { // expr only exists if `name` is a computed property name // 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])); @@ -60541,12 +62065,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: "\n const _super = name => super[name];\n " + text: "\n const _super = name => super[name];" }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - 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 " + 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);" }; })(ts || (ts = {})); /// @@ -61127,7 +62651,7 @@ var ts; var awaitHelper = { name: "typescript:await", scoped: false, - text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" }; function createAwaitHelper(context, expression) { context.requestEmitHelper(awaitHelper); @@ -61136,7 +62660,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -61153,7 +62677,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -61164,7 +62688,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -61231,8 +62755,7 @@ var ts; case 257 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxElement(node, isChild) { @@ -61270,14 +62793,14 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } return element; } function visitJsxOpeningFragment(node, children, isChild, location) { - var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -61309,7 +62832,7 @@ var ts; return visitJsxExpression(node); } else { - ts.Debug.failBadSyntaxKind(node); + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxText(node) { @@ -62469,6 +63992,7 @@ var ts; if (statement.kind === 223 /* ReturnStatement */) { return true; } + // An if-statement with two covered branches is covered. else if (statement.kind === 215 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { @@ -62476,6 +64000,7 @@ var ts; isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } + // A block is covered if it has a last statement which is covered. else if (statement.kind === 211 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { @@ -62674,11 +64199,11 @@ var ts; 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 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter)) - ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */)); + ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); statements.push(statement); } /** @@ -62783,8 +64308,7 @@ var ts; 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; + return ts.Debug.failBadSyntaxKind(node); } var captureNewTargetStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -63427,26 +64951,23 @@ var ts; statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); } } - var bodyLocation; - var statementsLocation; if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); } else { var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); } else { statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); } } - // 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 createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { // The following ES6 code: @@ -64025,18 +65546,15 @@ var ts; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { - var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = transformFunctionBody(node); - if (node.kind === 155 /* GetAccessor */) { - updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); - } - else { - updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); - } + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 155 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { - updated = ts.visitEachChild(node, visitor, context); + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; @@ -64502,14 +66020,14 @@ var ts; */ 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)); + var span = _a[_i]; + expressions.push(ts.visitNode(span.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)); + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); } } } @@ -65110,8 +66628,7 @@ var ts; case 190 /* FunctionExpression */: return visitFunctionExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } /** @@ -67155,6 +68672,7 @@ var ts; withBlockStack.pop(); } break; + // default: do nothing } } } @@ -68783,7 +70301,7 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" }; function createExportStarHelper(context, module) { var compilerOptions = context.getCompilerOptions(); @@ -68801,13 +70319,13 @@ var ts; var importStarHelper = { name: "typescript:commonjsimportstar", scoped: false, - text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" }; // emit helper for `import Name from "foo"` var importDefaultHelper = { name: "typescript:commonjsimportdefault", scoped: false, - text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" }; })(ts || (ts = {})); /// @@ -69145,12 +70663,12 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_1 = dependencyGroups_1[_i]; + var group_2 = dependencyGroups_1[_i]; // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -70362,6 +71880,1435 @@ var ts; } ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + 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 === 233 /* 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 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 === 233 /* 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; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */) { + 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; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || + (node.kind === 148 /* 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 /* 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 === 233 /* ClassDeclaration */ || node.kind === 148 /* 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 : + 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; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 156 /* 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(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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_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; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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 /* 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: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: + case 152 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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 === 233 /* 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 : + 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 232 /* 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 : + 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; + break; + default: + ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 154 /* 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 158 /* ConstructSignature */: + case 163 /* ConstructorType */: + // 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: + case 152 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + 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 === 233 /* 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 : + 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 232 /* FunctionDeclaration */: + case 162 /* FunctionType */: + 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 : + 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; + default: + ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + 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 233 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 234 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 158 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 157 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 153 /* MethodDeclaration */: + case 152 /* 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 === 233 /* 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 232 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 235 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 233 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + 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 { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJavaScript(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var enclosingDeclaration; + var necessaryTypeRefernces; + var possibleImports; + var importDeclarationMap; + var suppressNewDiagnosticContexts; + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + }; + var errorNameNode; + var currentSourceFile; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + var host = context.getEmitHost(); + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeRefernces.set(ref, true); + } + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!possibleImports) { + possibleImports = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(possibleImports, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(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) { + context.addDiagnostic(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 transformRoot(node) { + if (node.kind === 272 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + return node; + } + if (node.kind === 273 /* Bundle */) { + isBundledEmit = true; + var refs_1 = ts.createMap(); + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + return; // Omit declaration files from bundle results, too + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + possibleImports = undefined; + suppressNewDiagnosticContexts = false; + importDeclarationMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + collectReferences(sourceFile, refs_1); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, updated, /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs_1.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + possibleImports = undefined; + importDeclarationMap = ts.createMap(); + necessaryTypeRefernces = undefined; + var refs = collectReferences(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + refs.forEach(referenceVisitor); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + if (ts.isExternalModule(node) && !resultHasExternalModuleIndicator) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences()); + return updated; + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeRefernces ? ts.map(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getNodeId(elem), elem); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 71 /* Identifier */) { + return name; + } + else { + if (name.kind === 179 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 204 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 148 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + if (node.kind === 156 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 148 /* Parameter */ + || node.kind === 151 /* PropertyDeclaration */ + || node.kind === 150 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 237 /* ModuleDeclaration */: + case 234 /* InterfaceDeclaration */: + case 233 /* ClassDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 236 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 230 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 241 /* ImportEqualsDeclaration */: + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + case 247 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.forEach(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237 /* ModuleDeclaration */; + if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 252 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 244 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function filterCandidateImports(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + var unconsideredImports = []; + while (ts.length(possibleImports)) { + var i = possibleImports.shift(); + if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope + unconsideredImports.push(i); + continue; + } + // Eagerly transform import equals - if they're not visible, we'll get nothing, if they are, we'll immediately add them since it's complete + if (i.kind === 241 /* ImportEqualsDeclaration */) { + var result_3 = transformImportEqualsDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result_3); + continue; + } + // Import declarations, on the other hand, can be partially painted by multiple aliases; so we can see many indeterminate states + // until we've marked all possible visibility + var result = transformImportDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result); + } + // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not + // be considered in the child scope + possibleImports = unconsideredImports; + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.mapDefined(statements, function (statement) { + if (ts.isImportDeclaration(statement) || ts.isImportEqualsDeclaration(statement)) { + var key = "" + ts.getNodeId(statement); + if (importDeclarationMap.has(key)) { + var result = importDeclarationMap.get(key); + importDeclarationMap.delete(key); + return result; + } + else { + return undefined; + } + } + else { + return statement; + } + }); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, input.modifiers, input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 165 /* TypeLiteral */ || input.kind === 176 /* MappedType */) && input.parent.kind !== 235 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 205 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 161 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 158 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 154 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 153 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(152 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 155 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 156 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 151 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 150 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 152 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 157 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 159 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + } + case 230 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 147 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 170 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 162 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 163 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 153 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 247 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + if (input.expression.kind === 71 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + case 241 /* ImportEqualsDeclaration */: + case 242 /* ImportDeclaration */: { + // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later + // to reduce the likelihood we need to rewrite it + possibleImports = possibleImports || []; + ts.pushIfUnique(possibleImports, input); + return input; + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var previousNeedsDeclare; + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var oldPossibleImports; + switch (input.kind) { + case 235 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 234 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 232 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + return cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + } + case 237 /* ModuleDeclaration */: { + previousNeedsDeclare = needsDeclare; + needsDeclare = false; + oldPossibleImports = possibleImports; + possibleImports = undefined; + var inner = input.body; + if (inner && inner.kind === 238 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + needsDeclare = false; + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + } + } + case 233 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 71 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 85 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 212 /* VariableStatement */: { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return cleanup(ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes))); + } + case 236 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(returnValue) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (input.kind === 237 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + possibleImports = ts.concatenate(oldPossibleImports, possibleImports); + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (returnValue) { + if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) { + // Exported top-level member indicates moduleness + resultHasExternalModuleIndicator = true; + } + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 204 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function ensureModifiers(node) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 272 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((isBundledEmit && parentIsFile ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_7 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_7(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 234 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 155 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 230 /* VariableDeclaration */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: + case 148 /* Parameter */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 237 /* ModuleDeclaration */: + case 241 /* ImportEqualsDeclaration */: + case 234 /* InterfaceDeclaration */: + case 233 /* ClassDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 236 /* EnumDeclaration */: + case 212 /* VariableStatement */: + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + case 247 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 158 /* ConstructSignature */: + case 154 /* Constructor */: + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: + case 152 /* MethodSignature */: + case 157 /* CallSignature */: + case 159 /* IndexSignature */: + case 230 /* VariableDeclaration */: + case 147 /* TypeParameter */: + case 205 /* ExpressionWithTypeArguments */: + case 161 /* TypeReference */: + case 170 /* ConditionalType */: + case 162 /* FunctionType */: + case 163 /* ConstructorType */: + return true; + } + return false; + } +})(ts || (ts = {})); /// /// /// @@ -70375,6 +73322,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -70456,6 +73404,7 @@ var ts; var onSubstituteNode = function (_, node) { return node; }; var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; var state = 0 /* Uninitialized */; + var diagnostics = []; // The transformation context is provided to each transformer as part of transformer // initialization. var context = { @@ -70485,6 +73434,9 @@ var ts; 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; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); } }; // Ensure the parse tree is clean before applying transformations @@ -70507,7 +73459,8 @@ var ts; transformed: transformed, substituteNode: substituteNode, emitNodeWithNotification: emitNodeWithNotification, - dispose: dispose + dispose: dispose, + diagnostics: diagnostics }; function transformRoot(node) { return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; @@ -70701,1825 +73654,6 @@ var ts; /// /* @internal */ var ts; -(function (ts) { - function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var declarationDiagnostics = ts.createDiagnosticCollection(); - ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); - return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); - function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) { - var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false); - } - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 273 /* Bundle */; - var newLine = host.getNewLine(); - var compilerOptions = host.getCompilerOptions(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer; - createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var resultHasExternalModuleIndicator; - var currentText; - var currentLineMap; - var currentIdentifiers; - var isCurrentFileExternalModule; - var reportedDeclarationError = false; - var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; - var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - 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; - } - emittedReferencedFiles.push(referencedFile); - } - }); - } - resultHasExternalModuleIndicator = false; - if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - needsDeclare = true; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - needsDeclare = false; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - 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 === 242 /* ImportDeclaration */); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - increaseIndent(); - } - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - decreaseIndent(); - } - } - }); - setWriter(oldWriter); - allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - if (!isBundledEmit && ts.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 {};"); - writeLine(); - } - }); - if (usedTypeDirectiveReferences) { - ts.forEachKey(usedTypeDirectiveReferences, function (directive) { - referencesOutput += "/// " + newLine; - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput, - }; - function hasInternalAnnotation(range) { - var comment = currentText.substring(range.pos, range.end); - return ts.stringContains(comment, "@internal"); - } - function stripInternal(node) { - if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); - if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { - return; - } - emitNode(node); - } - } - function createAndSetNewTextWriterWithSymbolWriter() { - 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; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeProperty = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsynchronousModuleElements(nodes) { - var oldWriter = writer; - ts.forEach(nodes, function (declaration) { - var nodeToCheck; - if (declaration.kind === 230 /* VariableDeclaration */) { - nodeToCheck = declaration.parent.parent; - } - else if (declaration.kind === 245 /* NamedImports */ || declaration.kind === 246 /* ImportSpecifier */ || declaration.kind === 243 /* ImportClause */) { - ts.Debug.fail("We should be getting ImportDeclaration instead to write"); - } - else { - nodeToCheck = declaration; - } - var moduleElementEmitInfo = ts.forEach(moduleElementDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - 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 === 242 /* 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 { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); - asynchronousSubModuleDeclarationEmitInfo = []; - } - writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; - asynchronousSubModuleDeclarationEmitInfo = undefined; - } - moduleElementEmitInfo.asynchronousOutput = writer.getText(); - } - } - }); - setWriter(oldWriter); - } - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { - if (!typeReferenceDirectives) { - return; - } - if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); - } - for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { - var directive = typeReferenceDirectives_1[_i]; - if (!usedTypeDirectiveReferences.has(directive)) { - usedTypeDirectiveReferences.set(directive, directive); - } - } - } - function handleSymbolAccessibilityError(symbolAccessibilityResult) { - 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) { - if (errorInfo.typeName) { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - else { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); - } - function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - reportedDeclarationError = true; - 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_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); - } - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - // 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 === 148 /* Parameter */ && - (resolver.isRequiredInitializedParameter(declaration) || - resolver.isOptionalUninitializedParameterProperty(declaration)); - if (type && !shouldUseResolverType) { - // Write the type - emitType(type); - } - else { - errorNameNode = declaration.name; - var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | - 2048 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); - errorNameNode = undefined; - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - // Write the type - emitType(signature.type); - } - else { - errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - errorNameNode = undefined; - } - } - function emitLines(nodes) { - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var node = nodes_6[_i]; - emit(node); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; - if (!canEmitFn || canEmitFn(node)) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(node); - } - } - } - function emitCommaList(nodes, eachNodeEmitFn, canEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); - } - function writeJsDocComments(declaration) { - if (declaration) { - var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - // 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) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 135 /* ObjectKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 173 /* ThisType */: - case 177 /* LiteralType */: - return writeTextOfNode(currentText, type); - case 205 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(type); - case 161 /* TypeReference */: - return emitTypeReference(type); - case 164 /* TypeQuery */: - return emitTypeQuery(type); - case 166 /* ArrayType */: - return emitArrayType(type); - case 167 /* TupleType */: - return emitTupleType(type); - case 168 /* UnionType */: - return emitUnionType(type); - case 169 /* IntersectionType */: - return emitIntersectionType(type); - case 170 /* ConditionalType */: - return emitConditionalType(type); - case 171 /* InferType */: - return emitInferType(type); - case 172 /* ParenthesizedType */: - return emitParenType(type); - case 174 /* TypeOperator */: - return emitTypeOperator(type); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(type); - case 176 /* MappedType */: - return emitMappedType(type); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - return emitSignatureDeclarationWithJsDocComments(type); - case 165 /* TypeLiteral */: - return emitTypeLiteral(type); - case 71 /* Identifier */: - return emitEntityName(type); - case 145 /* QualifiedName */: - return emitEntityName(type); - case 160 /* TypePredicate */: - return emitTypePredicate(type); - } - function writeEntityName(entityName) { - if (entityName.kind === 71 /* Identifier */) { - writeTextOfNode(currentText, entityName); - } - else { - var left = entityName.kind === 145 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 145 /* QualifiedName */ ? entityName.right : entityName.name; - writeEntityName(left); - write("."); - writeTextOfNode(currentText, right); - } - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, - // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 241 /* 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 === 183 /* PropertyAccessExpression */); - emitEntityName(node.expression); - if (node.typeArguments) { - write("<"); - emitCommaList(node.typeArguments, emitType); - write(">"); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypePredicate(type) { - writeTextOfNode(currentText, type.parameterName); - write(" is "); - emitType(type.type); - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitIntersectionType(type) { - emitSeparatedList(type.types, " & ", emitType); - } - function emitConditionalType(node) { - emitType(node.checkType); - write(" extends "); - emitType(node.extendsType); - write(" ? "); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node.trueType; - emitType(node.trueType); - enclosingDeclaration = prevEnclosingDeclaration; - write(" : "); - emitType(node.falseType); - } - function emitInferType(node) { - write("infer "); - writeTextOfNode(currentText, node.typeParameter.name); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeOperator(type) { - write(ts.tokenToString(type.operator)); - write(" "); - emitType(type.type); - } - function emitIndexedAccessType(node) { - emitType(node.objectType); - write("["); - emitType(node.indexType); - write("]"); - } - function emitMappedType(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write("{"); - writeLine(); - increaseIndent(); - if (node.readonlyToken) { - write(node.readonlyToken.kind === 37 /* PlusToken */ ? "+readonly " : - node.readonlyToken.kind === 38 /* MinusToken */ ? "-readonly " : - "readonly "); - } - write("["); - writeEntityName(node.typeParameter.name); - write(" in "); - emitType(node.typeParameter.constraint); - write("]"); - if (node.questionToken) { - write(node.questionToken.kind === 37 /* PlusToken */ ? "+?" : - node.questionToken.kind === 38 /* MinusToken */ ? "-?" : - "?"); - } - write(": "); - emitType(node.type); - write(";"); - writeLine(); - decreaseIndent(); - write("}"); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - // write members - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentText = node.text; - currentLineMap = ts.getLineStarts(node); - currentIdentifiers = node.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(node); - enclosingDeclaration = node; - 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; - } - var count = 0; - while (true) { - count++; - var name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; - } - } - } - function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { - var tempVarName = getExportTempVariableName(baseName); - if (needsDeclare) { - write("declare "); - } - write("const "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - write(";"); - writeLine(); - return tempVarName; - } - function emitExportAssignment(node) { - if (ts.isSourceFile(node.parent)) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - } - if (node.expression.kind === 71 /* Identifier */) { - write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentText, node.expression); - } - else { - var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }, needsDeclare); - write(node.isExportEquals ? "export = " : "export default "); - write(tempVarName); - } - write(";"); - writeLine(); - // 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); - } - } - function isModuleElementVisible(node) { - return resolver.isDeclarationVisible(node); - } - function emitModuleElement(node, isModuleElementVisible) { - if (isModuleElementVisible) { - writeModuleElement(node); - } - else if (node.kind === 241 /* ImportEqualsDeclaration */ || - (node.parent.kind === 272 /* SourceFile */ && isCurrentFileExternalModule)) { - var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 272 /* SourceFile */) { - // Import declaration of another module that is visited async so lets put it in right spot - asynchronousSubModuleDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - else { - if (node.kind === 242 /* ImportDeclaration */) { - var importDeclaration = node; - if (importDeclaration.importClause) { - isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || - isVisibleNamedBinding(importDeclaration.importClause.namedBindings); - } - } - moduleElementDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - } - } - function writeModuleElement(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - return writeFunctionDeclaration(node); - case 212 /* VariableStatement */: - return writeVariableStatement(node); - case 234 /* InterfaceDeclaration */: - return writeInterfaceDeclaration(node); - case 233 /* ClassDeclaration */: - return writeClassDeclaration(node); - case 235 /* TypeAliasDeclaration */: - return writeTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: - return writeEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return writeModuleDeclaration(node); - case 241 /* ImportEqualsDeclaration */: - return writeImportEqualsDeclaration(node); - case 242 /* ImportDeclaration */: - return writeImportDeclaration(node); - default: - ts.Debug.fail("Unknown symbol kind"); - } - } - 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 === 272 /* SourceFile */) { - var modifiers = ts.getModifierFlags(node); - // If the node is exported - if (modifiers & 1 /* Export */) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - write("export "); - } - if (modifiers & 512 /* Default */) { - write("default "); - } - else if (node.kind !== 234 /* InterfaceDeclaration */ && needsDeclare) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(flags) { - if (flags & 8 /* Private */) { - write("private "); - } - else if (flags & 16 /* Protected */) { - write("protected "); - } - if (flags & 32 /* Static */) { - write("static "); - } - if (flags & 64 /* Readonly */) { - write("readonly "); - } - 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 /* Export */)) { - write("export "); - } - write("import "); - writeTextOfNode(currentText, node.name); - write(" = "); - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - emitExternalModuleSpecifier(node); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function isVisibleNamedBinding(namedBindings) { - if (namedBindings) { - if (namedBindings.kind === 244 /* NamespaceImport */) { - return resolver.isDeclarationVisible(namedBindings); - } - else { - return namedBindings.elements.some(function (namedImport) { return resolver.isDeclarationVisible(namedImport); }); - } - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1 /* Export */)) { - write("export "); - } - write("import "); - if (node.importClause) { - var currentWriterPos = writer.getTextPos(); - if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentText, node.importClause.name); - } - 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 === 244 /* NamespaceImport */) { - write("* as "); - writeTextOfNode(currentText, node.importClause.namedBindings.name); - } - else { - write("{ "); - emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); - write(" }"); - } - } - write(" from "); - } - emitExternalModuleSpecifier(node); - write(";"); - writer.writeLine(); - } - function emitExternalModuleSpecifier(parent) { - // 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 !== 237 /* ModuleDeclaration */; - var moduleSpecifier = parent.kind === 241 /* ImportEqualsDeclaration */ ? ts.getExternalModuleImportEqualsDeclarationExpression(parent) : - parent.kind === 237 /* ModuleDeclaration */ ? parent.name : parent.moduleSpecifier; - if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); - if (moduleName) { - write('"'); - write(moduleName); - write('"'); - return; - } - } - writeTextOfNode(currentText, moduleSpecifier); - } - function emitImportOrExportSpecifier(node) { - if (node.propertyName) { - writeTextOfNode(currentText, node.propertyName); - write(" as "); - } - writeTextOfNode(currentText, node.name); - } - 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) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - emitJsDocComments(node); - write("export "); - if (node.exportClause) { - write("{ "); - emitCommaList(node.exportClause.elements, emitExportSpecifier); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitExternalModuleSpecifier(node); - } - write(";"); - writer.writeLine(); - } - function writeModuleDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isGlobalScopeAugmentation(node)) { - write("global "); - } - else { - if (node.flags & 16 /* Namespace */) { - write("namespace "); - } - else { - write("module "); - } - if (ts.isExternalModuleAugmentation(node)) { - emitExternalModuleSpecifier(node); - } - else { - writeTextOfNode(currentText, node.name); - } - } - while (node.body && node.body.kind !== 238 /* ModuleBlock */) { - node = node.body; - write("."); - writeTextOfNode(currentText, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - if (node.body) { - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - else { - write(";"); - } - } - function writeTypeAliasDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function writeEnumDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentText, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentText, node.name); - var enumMemberValue = resolver.getConstantValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(ts.getTextOfConstantValue(enumMemberValue)); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 153 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - 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 === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - if (node.default && !isPrivateMethodTypeParameter(node)) { - write(" = "); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.default); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError); - } - } - 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 233 /* ClassDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 234 /* InterfaceDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 158 /* ConstructSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 157 /* CallSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 153 /* MethodDeclaration */: - case 152 /* 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 === 233 /* 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 232 /* FunctionDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - case 235 /* TypeAliasDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - } - else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { - write("null"); - } - function getHeritageClauseVisibilityError() { - var diagnosticMessage; - // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 233 /* 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 { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: ts.getNameOfDeclaration(node.parent.parent) - }; - } - } - } - function writeClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) { - emitPropertyDeclaration(param); - } - }); - } - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - var tempVarName; - if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { - 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 === 237 /* ModuleDeclaration */; })); - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.hasModifier(node, 128 /* Abstract */)) { - write("abstract "); - } - write("class "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - if (baseTypeNode) { - if (!ts.isEntityNameExpression(baseTypeNode.expression)) { - write(" extends "); - write(tempVarName); - if (baseTypeNode.typeArguments) { - write("<"); - emitCommaList(baseTypeNode.typeArguments, emitType); - write(">"); - } - } - else { - emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); - } - } - emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(ts.getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function writeInterfaceDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); - if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); - } - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - emitJsDocComments(node); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - emitVariableDeclaration(node); - 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 !== 230 /* VariableDeclaration */ || isVariableDeclarationVisible(node)) { - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */) && node.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (resolver.isLiteralConstDeclaration(node)) { - write(" = "); - resolver.writeLiteralConstValue(node, writer); - } - else if (!ts.hasModifier(node, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 230 /* 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* 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 /* 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 === 233 /* ClassDeclaration */ || node.kind === 148 /* 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 : - 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; - } - } - } - function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : 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 !== 204 /* OmittedExpression */ && isVariableDeclarationVisible(element)) { - elements.push(element); - } - } - emitCommaList(elements, emitBindingElement); - } - function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - writeTextOfNode(currentText, bindingElement.name); - 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 (ts.hasType(node)) { - write(": "); - emitType(node.type); - } - } - function isVariableStatementVisible(node) { - 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; - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isLet(node.declarationList)) { - write("let "); - } - else if (ts.isConst(node.declarationList)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); - write(";"); - writeLine(); - } - function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - var accessorWithTypeAnnotation; - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - 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) { - // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 155 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 155 /* 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 === 233 /* 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 === 156 /* 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_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_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; - } - } - else { - if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - 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 /* 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: accessorWithTypeAnnotation.name - }; - } - } - function writeFunctionDeclaration(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 === 232 /* FunctionDeclaration */) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 153 /* MethodDeclaration */ || node.kind === 154 /* Constructor */) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - } - if (node.kind === 232 /* FunctionDeclaration */) { - write("function "); - writeTextOfNode(currentText, node.name); - } - else if (node.kind === 154 /* Constructor */) { - write("constructor"); - } - else { - 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 === 233 /* 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); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var closeParenthesizedFunctionType = false; - if (node.kind === 159 /* IndexSignature */) { - // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - write("["); - } - else { - if (node.kind === 154 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { - write("();"); - writeLine(); - return; - } - // Construct signature or constructor type write new Signature - if (node.kind === 158 /* ConstructSignature */ || node.kind === 163 /* ConstructorType */) { - write("new "); - } - else if (node.kind === 162 /* 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("("); - } - } - emitTypeParameters(node.typeParameters); - write("("); - } - // Parameters - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 159 /* IndexSignature */) { - write("]"); - } - else { - write(")"); - } - // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 162 /* FunctionType */ || node.kind === 163 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 165 /* TypeLiteral */) { - // Emit type literal signature return type only if specified - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 154 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - else if (closeParenthesizedFunctionType) { - write(")"); - } - function getReturnTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - 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 === 233 /* 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 : - 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 232 /* 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 : - 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; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - 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 { - writeTextOfNode(currentText, node.name); - } - if (resolver.isOptionalParameter(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!ts.hasModifier(node.parent, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - switch (node.parent.kind) { - case 154 /* 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 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node.parent, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - 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 === 233 /* 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 : - 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 232 /* 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 : - 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; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - } - function emitBindingPattern(bindingPattern) { - // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 178 /* ObjectBindingPattern */) { - write("{"); - emitCommaList(bindingPattern.elements, emitBindingElement); - write("}"); - } - else if (bindingPattern.kind === 179 /* ArrayBindingPattern */) { - write("["); - var elements = bindingPattern.elements; - emitCommaList(elements, emitBindingElement); - if (elements && elements.hasTrailingComma) { - write(", "); - } - write("]"); - } - } - function emitBindingElement(bindingElement) { - if (bindingElement.kind === 204 /* 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, ,]) {} - // tslint:disable-next-line no-double-space - // emit : function foo([ , x, , ]) {} - write(" "); - } - else if (bindingElement.kind === 180 /* 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 /* 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("..."); - } - writeTextOfNode(currentText, bindingElement.name); - } - } - } - } - } - function emitNode(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 237 /* ModuleDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 234 /* InterfaceDeclaration */: - case 233 /* ClassDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: - return emitModuleElement(node, isModuleElementVisible(node)); - case 212 /* VariableStatement */: - return emitModuleElement(node, isVariableStatementVisible(node)); - case 242 /* ImportDeclaration */: - // Import declaration without import clause is visible, otherwise it is not visible - return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 248 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return writeFunctionDeclaration(node); - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 159 /* IndexSignature */: - return emitSignatureDeclarationWithJsDocComments(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return emitPropertyDeclaration(node); - case 271 /* EnumMember */: - return emitEnumMemberDeclaration(node); - case 247 /* ExportAssignment */: - return emitExportAssignment(node); - case 272 /* 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, - /*isAbsolutePathAnUrl*/ false); - referencesOutput += "/// " + newLine; - } - 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 === 273 /* Bundle */; - if (isBundledEmit && !addBundledFileReference) { - return; - } - ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); - declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; - addedBundledEmitReference = isBundledEmit; - } - } - } - /* @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 || emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var declarationOutput = emitDeclarationResult.referencesOutput - + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); - } - return emitSkipped; - 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); - declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); - return declarationOutput; - } - } - ts.writeDeclarationFile = writeDeclarationFile; -})(ts || (ts = {})); -/// -/* @internal */ -var ts; (function (ts) { // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { @@ -72529,8 +73663,8 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); + function createSourceMapWriter(host, writer, compilerOptions) { + if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSource; var currentSourceText; @@ -72543,11 +73677,11 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; + var sourceMapDataList; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, - getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitNodeWithSourceMap: emitNodeWithSourceMap, @@ -72568,13 +73702,14 @@ var ts; * @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) { + function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { if (disabled) { return; } if (sourceMapData) { reset(); } + sourceMapDataList = outputSourceMapDataList; currentSource = undefined; currentSourceText = undefined; // Current source map file and its index in the sources list @@ -72604,7 +73739,7 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 272 /* SourceFile */) { + if (sourceFileOrBundle.kind === 272 /* SourceFile */) { // emitting single module file // 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)); @@ -72632,6 +73767,10 @@ var ts; if (disabled) { return; } + // Record source map data for the test harness. + if (sourceMapDataList) { + sourceMapDataList.push(sourceMapData); + } currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -72639,6 +73778,7 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + sourceMapDataList = undefined; } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -72857,7 +73997,7 @@ var ts; } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(getText()); + var base64SourceMapText = ts.base64encode(ts.sys, getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; } else { @@ -73111,7 +74251,15 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -73139,6 +74287,8 @@ var ts; forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -73236,6 +74386,8 @@ var ts; } } function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (emitPos) emitPos(commentPos); ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); @@ -73255,7 +74407,6 @@ var ts; })(ts || (ts = {})); /// /// -/// /// /// var ts; @@ -73276,10 +74427,8 @@ var ts; var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var bundle = ts.createBundle(sourceFiles); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; } @@ -73288,10 +74437,7 @@ var ts; else { for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { var sourceFile = sourceFiles_1[_a]; - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); if (result) { return result; } @@ -73299,8 +74445,29 @@ var ts; } } ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 273 /* Bundle */) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + else { + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJavaScript(sourceFile); + var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; + return (options.sourceMap && !options.inlineSourceMap) ? 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. @@ -73319,51 +74486,31 @@ var ts; } return ".js" /* Js */; } - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 273 /* 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); - var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); var writer = ts.createTextWriter(newLine); var sourceMap = ts.createSourceMapWriter(host, writer); + var declarationSourceMap = ts.createSourceMapWriter(host, writer, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); var currentSourceFile; var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; - var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); - // 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); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); - // Clean up emit nodes on parse tree - transform.dispose(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -73371,19 +74518,9 @@ var ts; sourceMaps: sourceMapDataList }; 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 && !compilerOptions.emitDeclarationOnly) { - if (!emitOnlyDtsFiles) { - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); - } - } - else { - emitSkipped = true; - } - if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; - } + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { emittedFilesList.push(jsFilePath); @@ -73396,11 +74533,76 @@ var ts; } } } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Make sure not to write js file and source map file if any of them cannot be written + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + emitSkipped = true; + return; + } + if (emitOnlyDtsFiles) { + return; + } + // 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, + }); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true }), { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // sourcemap hooks + onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: declarationSourceMap.emitPos, + onSetSourceFile: setSourceFileForDeclarationSourceMaps, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + } + declarationTransform.dispose(); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 272 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); + mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { bundledHelpers = ts.createMap(); isOwnFileEmit = false; @@ -73411,22 +74613,18 @@ var ts; printer.writeFile(sourceFile, writer); } writer.writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); + var sourceMappingURL = mapRecorder.getSourceMappingURL(); if (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(), /*writeByteOrderMark*/ false, sourceFiles); - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); + if (sourceMapFilePath) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state - sourceMap.reset(); + mapRecorder.reset(); writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; @@ -73436,6 +74634,10 @@ var ts; currentSourceFile = node; sourceMap.setSourceFile(node); } + function setSourceFileForDeclarationSourceMaps(node) { + currentSourceFile = node; + declarationSourceMap.setSourceFile(node); + } function emitHelpers(node, writeLines) { var helpersEmitted = false; var bundle = node.kind === 273 /* Bundle */ ? node : undefined; @@ -73573,6 +74775,7 @@ var ts; emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpersIndirect(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { var sourceFile = _b[_a]; print(0 /* SourceFile */, sourceFile, sourceFile); @@ -73930,6 +75133,8 @@ var ts; // Enum case 271 /* EnumMember */: return emitEnumMember(node); + // JSDoc nodes (ignored) + // Transformation nodes (ignored) } // If the node is an expression, try to emit it as an expression with // substitution. @@ -74125,7 +75330,8 @@ var ts; else { emitTypeAnnotation(node.type); } - emitInitializer(node.initializer); + // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); } function emitDecorator(decorator) { writePunctuation("@"); @@ -74147,8 +75353,9 @@ var ts; emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); + emitIfPresent(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { @@ -74267,7 +75474,7 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); writePunctuation("}"); } @@ -74282,7 +75489,7 @@ var ts; } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 336 /* TupleTypeElements */); + emitList(node, node.elementTypes, 272 /* TupleTypeElements */); writePunctuation("]"); } function emitUnionType(node) { @@ -74393,7 +75600,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } // // Expressions @@ -74430,7 +75637,10 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - writePunctuation(shouldEmitDotDot ? ".." : "."); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -74456,9 +75666,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - writePunctuation("["); + var openPos = emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - writePunctuation("]"); + emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); @@ -74466,7 +75676,7 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - writeKeyword("new"); + emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); @@ -74484,9 +75694,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - writePunctuation("("); + var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -74504,22 +75714,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - writeKeyword("delete"); + emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - writeKeyword("typeof"); + emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - writeKeyword("void"); + emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - writeKeyword("await"); + emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -74587,7 +75797,7 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - writeKeyword("yield"); + emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } @@ -74631,17 +75841,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); - // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; emitList(node, node.statements, format); + emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -74656,15 +75862,15 @@ var ts; writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 215 /* IfStatement */) { writeSpace(); emit(node.elseStatement); @@ -74674,8 +75880,15 @@ var ts; } } } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } function emitDoStatement(node) { - writeKeyword("do"); + emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -74683,55 +75896,48 @@ var ts; else { writeLineOrSpace(node); } - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(");"); + emitWhileClause(node, node.statement.end); + writePunctuation(";"); } function emitWhileStatement(node) { - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(")"); + emitWhileClause(node, node.pos); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - writeSemicolon(); + pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.condition); - writeSemicolon(); + pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.incrementor); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("in"); + emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("of"); + emitTokenWithComment(144 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -74745,22 +75951,34 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } - function emitTokenWithComment(token, pos, writer, contextNode) { - var node = contextNode && ts.getParseTreeNode(contextNode); - if (node && node.kind === contextNode.kind) { + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); - if (node && node.kind === contextNode.kind) { + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; @@ -74771,35 +75989,35 @@ var ts; writeSemicolon(); } function emitWithStatement(node) { - writeKeyword("with"); + var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); - writePunctuation("("); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - writePunctuation(":"); + emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - writeKeyword("throw"); + emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); writeSemicolon(); } function emitTryStatement(node) { - writeKeyword("try"); + emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -74808,7 +76026,7 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - writeKeyword("finally"); + emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } @@ -74823,7 +76041,7 @@ var ts; function emitVariableDeclaration(node) { emit(node.name); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); @@ -74961,7 +76179,7 @@ var ts; increaseIndent(); } emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); @@ -75014,6 +76232,8 @@ var ts; } emit(node.name); var body = node.body; + if (!body) + return writeSemicolon(); while (body.kind === 237 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); @@ -75024,23 +76244,21 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); - writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); + emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); + emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - writePunctuation("="); + emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); writeSemicolon(); @@ -75055,12 +76273,12 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - writeKeyword("from"); + emitTokenWithComment(142 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -75069,15 +76287,15 @@ var ts; function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - writePunctuation(","); + emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - writePunctuation("*"); + var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -75088,41 +76306,42 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - writeOperator("="); + emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node); } else { - writeKeyword("default"); + emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); writeSemicolon(); } function emitExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - writePunctuation("*"); + nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); - writeKeyword("from"); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(142 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeKeyword("as"); + nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - writeKeyword("namespace"); + nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); writeSemicolon(); @@ -75135,14 +76354,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -75168,10 +76387,7 @@ var ts; writePunctuation("<"); emitJsxTagName(node.tagName); writeSpace(); - // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); - } + emit(node.attributes); writePunctuation("/>"); } function emitJsxFragment(node) { @@ -75183,11 +76399,10 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); - // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); - emit(node.attributes); } + emit(node.attributes); } writePunctuation(">"); } @@ -75234,44 +76449,31 @@ var ts; // Clauses // function emitCaseClause(node) { - writeKeyword("case"); + emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - writeKeyword("default"); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); } - function emitCaseOrDefaultClauseStatements(parentNode, statements) { + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { var emitAsSingleStatement = statements.length === 1 && ( // 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 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { + writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode); writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } + else { + emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + } emitList(parentNode, statements, format); } function emitHeritageClause(node) { @@ -75281,12 +76483,12 @@ var ts; emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -75332,7 +76534,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } // // Top-level nodes @@ -75353,11 +76555,31 @@ var ts; } emitSourceFileWorker(node); } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.referencedFiles, node.typeReferenceDirectives); + } + function emitTripleSlashDirectives(files, types) { + for (var _a = 0, files_1 = files; _a < files_1.length; _a++) { + var directive = files_1[_a]; + write("/// "); + writeLine(); + } + for (var _b = 0, types_18 = types; _b < types_18.length; _b++) { + var directive = types_18[_b]; + write("/// "); + writeLine(); + } + } function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -75449,10 +76671,10 @@ var ts; emit(node); } } - function emitInitializer(node) { + function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - writeOperator("="); + emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -75500,7 +76722,7 @@ var ts; emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures return emitTypeArguments(parentNode, parentNode.typeArguments); } emitList(parentNode, typeParameters, 26896 /* TypeParameters */); @@ -75577,6 +76799,9 @@ var ts; } if (format & 7680 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + } } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -75684,6 +76909,9 @@ var ts; onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { + if (isEmpty && !isUndefined) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists + } writePunctuation(getClosingBracket(format)); } } @@ -75780,9 +77008,9 @@ var ts; } function writeLines(text) { var lines = text.split(/\r\n?|\n/g); - var indentation = guessIndentation(lines); - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var lineText = lines_1[_a]; + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var lineText = lines_2[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); @@ -75791,21 +77019,6 @@ var ts; } } } - function guessIndentation(lines) { - var indentation; - 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) { - indentation = i; - break; - } - } - } - } - return indentation; - } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { increaseIndent(); @@ -76029,7 +77242,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -76074,8 +77287,15 @@ var ts; * 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. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName) { + function makeUniqueName(baseName, optimistic) { + if (optimistic) { + if (isUniqueName(baseName)) { + generatedNames.set(baseName, true); + return baseName; + } + } // Find the first unique 'name_n', where n is a positive number if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { baseName += "_"; @@ -76163,6 +77383,8 @@ var ts; return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); + case 5 /* OptimisticUnique */: + return makeUniqueName(ts.idText(name), /*optimistic*/ true); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -76264,7 +77486,7 @@ var ts; if (failed) { return ""; } - if (!commonPathComponents) { + if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } return ts.getNormalizedPathFromPathComponents(commonPathComponents); @@ -76396,8 +77618,7 @@ var ts; } 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(); + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " 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; @@ -76422,8 +77643,9 @@ var ts; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } @@ -76454,8 +77676,8 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { @@ -76496,9 +77718,7 @@ var ts; output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); output += " - "; } - var categoryColor = getCategoryFormat(diagnostic.category); - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { @@ -76809,8 +78029,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var sourceFile = files_1[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -76832,13 +78052,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_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -77464,6 +78684,8 @@ var ts; case 185 /* CallExpression */: case 186 /* NewExpression */: case 205 /* ExpressionWithTypeArguments */: + case 254 /* JsxSelfClosingElement */: + case 255 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -77471,8 +78693,8 @@ var ts; } break; } - for (var _b = 0, nodes_8 = nodes; _b < nodes_8.length; _b++) { - var node = nodes_8[_b]; + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; walk(node); } } @@ -77557,9 +78779,9 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 9 /* StringLiteral */ - ? b.kind === 9 /* StringLiteral */ && a.text === b.text - : b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText; + return a.kind === 71 /* Identifier */ + ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 9 /* StringLiteral */ && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -77578,7 +78800,7 @@ var ts; && !file.isDeclarationFile) { // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; @@ -77596,63 +78818,54 @@ var ts; file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { - switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { - break; + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // 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 (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // 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(node.name); } - 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 237 /* 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); } - 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, /*inAmbientModule*/ true); - } + // 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, /*inAmbientModule*/ true); } } } + } } } function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - (imports || (imports = [])).push(node.arguments[0]); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); } - else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) { - (imports || (imports = [])).push(node.arguments[0]); + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); } else { ts.forEachChild(node, collectDynamicImportOrRequireCalls); @@ -77751,6 +78964,7 @@ var ts; modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } + // See if we need to reprocess the imports due to prior skipped imports else if (file_1 && modulesWithElidedImports.get(file_1.path)) { if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports.set(file_1.path, false); @@ -78039,9 +79253,9 @@ var ts; if (options.out && options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } - if (options.mapRoot && !options.sourceMap) { + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { // Error to specify --mapRoot without --sourcemap - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { if (!options.declaration) { @@ -78051,6 +79265,9 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } + if (options.declarationMap && !options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } @@ -78066,14 +79283,14 @@ var ts; } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } 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)); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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) { @@ -78081,15 +79298,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - 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")); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } // 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) { + options.mapRoot) { // there is --mapRoot specified // 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 @@ -78105,7 +79322,7 @@ var ts; } if (options.emitDeclarationOnly) { if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -78204,18 +79421,18 @@ var ts; } return ts.emptyArray; } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } function getCompilerOptionsObjectLiteralSyntax() { @@ -78233,11 +79450,11 @@ var ts; } return _compilerOptionsObjectLiteralSyntax; } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { var props = ts.getPropertyAssignment(objectLiteral, key1, key2); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); } return !!props.length; } @@ -78349,6 +79566,8 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.defaultPreferences = {}; var TextChange = /** @class */ (function () { function TextChange() { } @@ -78741,16 +79960,13 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 71 /* Identifier */ && - (node.parent.kind === 222 /* BreakStatement */ || node.parent.kind === 221 /* ContinueStatement */) && - node.parent.label === node; + return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 /* Identifier */ && - node.parent.kind === 226 /* LabeledStatement */ && - node.parent.label === node; + return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; } + ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } @@ -78887,6 +80103,8 @@ var ts; case 5 /* Property */: // static method / property return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 6 /* Prototype */: + return "local class" /* localClassElement */; default: { ts.assertTypeIsNever(kind); return "" /* unknown */; @@ -79116,12 +80334,7 @@ var ts; // 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; - } - }); + var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); }); // 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; @@ -79361,6 +80574,102 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { + var tokenKind = token.kind; + var remainingMatchingTokens = 0; + while (true) { + token = findPrecedingToken(token.getFullStart(), sourceFile); + if (!token) { + return undefined; + } + if (token.kind === matchingTokenKind) { + if (remainingMatchingTokens === 0) { + return token; + } + remainingMatchingTokens--; + } + else if (token.kind === tokenKind) { + remainingMatchingTokens++; + } + } + } + ts.findPrecedingMatchingToken = findPrecedingMatchingToken; + function isPossiblyTypeArgumentPosition(token, sourceFile) { + // This function determines if the node could be type argument position + // Since during editing, when type argument list is not complete, + // the tree could be of any shape depending on the tokens parsed before current node, + // scanning of the previous identifier followed by "<" before current node would give us better result + // Note that we also balance out the already provided type arguments, arrays, object literals while doing so + var remainingLessThanTokens = 0; + while (token) { + switch (token.kind) { + case 27 /* LessThanToken */: + // Found the beginning of the generic argument expression + token = findPrecedingToken(token.getFullStart(), sourceFile); + var tokenIsIdentifier = token && ts.isIdentifier(token); + if (!remainingLessThanTokens || !tokenIsIdentifier) { + return tokenIsIdentifier; + } + remainingLessThanTokens--; + break; + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + remainingLessThanTokens = +3; + break; + case 46 /* GreaterThanGreaterThanToken */: + remainingLessThanTokens = +2; + break; + case 29 /* GreaterThanToken */: + remainingLessThanTokens++; + break; + case 18 /* CloseBraceToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); + if (!token) + return false; + break; + case 20 /* CloseParenToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); + if (!token) + return false; + break; + case 22 /* CloseBracketToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); + if (!token) + return false; + break; + // Valid tokens in a type name. Skip. + case 26 /* CommaToken */: + case 36 /* EqualsGreaterThanToken */: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 103 /* TypeOfKeyword */: + case 85 /* ExtendsKeyword */: + case 128 /* KeyOfKeyword */: + case 23 /* DotToken */: + case 49 /* BarToken */: + case 55 /* QuestionToken */: + case 56 /* ColonToken */: + break; + default: + if (ts.isTypeNode(token)) { + break; + } + // Invalid token in type + return false; + } + token = findPrecedingToken(token.getFullStart(), sourceFile); + } + return false; + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; /** * Returns true if the cursor at position in sourceFile is within a comment. * @@ -79557,16 +80866,6 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; - /** Add a value to a set, and return true if it wasn't already present. */ - function addToSeen(seen, key) { - key = String(key); - if (seen.has(key)) { - return false; - } - seen.set(key, true); - return true; - } - ts.addToSeen = addToSeen; function getSnapshotText(snap) { return snap.getText(0, snap.getLength()); } @@ -79864,32 +81163,35 @@ var ts; */ /* @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); - } - } + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); } ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + /* @internal */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + /* @internal */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } + function getFirstChild(node) { + return node.forEachChild(function (child) { return child; }); + } })(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. @@ -80111,24 +81413,23 @@ var ts; return textSpan(node); } if (node.kind === 198 /* BinaryExpression */) { - var binaryExpression = node; + var _a = node, left = _a.left, operatorToken = _a.operatorToken; // 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 (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } - if (binaryExpression.operatorToken.kind === 58 /* EqualsToken */ && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.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 /* CommaToken */) { - return spanInNode(binaryExpression.left); + if (operatorToken.kind === 26 /* CommaToken */) { + return spanInNode(left); } } if (ts.isExpressionNode(node)) { @@ -80156,46 +81457,49 @@ var ts; break; } } - // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 268 /* 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 === 188 /* 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); - } - // initializer of variable/parameter declaration go to previous node - if ((node.parent.kind === 230 /* VariableDeclaration */ || - node.parent.kind === 148 /* Parameter */)) { - var paramOrVarDecl = node.parent; - if (paramOrVarDecl.initializer === node || - paramOrVarDecl.type === node || - ts.isAssignmentOperator(node.kind)) { - return spanInPreviousNode(node); + switch (node.parent.kind) { + case 268 /* PropertyAssignment */: + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + return spanInNode(node.parent.initializer); + } + break; + case 188 /* TypeAssertionExpression */: + // Breakpoint in type assertion goes to its operand + if (node.parent.type === node) { + return spanInNextNode(node.parent.type); + } + break; + case 230 /* VariableDeclaration */: + case 148 /* Parameter */: { + // initializer of variable/parameter declaration go to previous node + var _b = node.parent, initializer = _b.initializer, type = _b.type; + if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; } - } - if (node.parent.kind === 198 /* 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); + case 198 /* BinaryExpression */: { + var left = node.parent.left; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + break; } + default: + // return type of function go to previous token + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } } // Default go to parent to set the breakpoint return spanInNode(node.parent); } } function textSpanFromVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ && - variableDeclaration.parent.declarations[0] === variableDeclaration) { + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) { // First declaration - include let keyword return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); } @@ -80220,7 +81524,7 @@ var ts; variableDeclaration.parent.parent.kind === 220 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ && + if (ts.isVariableDeclarationList(variableDeclaration.parent) && 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 @@ -80706,7 +82010,7 @@ var ts; case 13 /* NoSubstitutionTemplateLiteral */: return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; default: - throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; @@ -80813,7 +82117,7 @@ var ts; case 0 /* None */: return { prefix: "" }; default: - throw ts.Debug.assertNever(lexState); + return ts.Debug.assertNever(lexState); } } function isBinaryExpressionOperatorToken(token) { @@ -81372,29 +82676,38 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function createPathCompletion(name, kind, span) { - return { name: name, kind: kind, span: span }; + function nameAndKind(name, kind) { + return { name: name, kind: kind }; + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind; + return ({ name: name, kind: kind, span: span }); + }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker)); + } + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + function getStringLiteralCompletionsFromModuleNamesWorker(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(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); } } else { // Check for node modules - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } - 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 @@ -81409,21 +82722,21 @@ var ts; // 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) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); var result = []; for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, host, exclude, result); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); } 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) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -81452,8 +82765,8 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var filePath = files_2[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; @@ -81464,7 +82777,7 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createPathCompletion(foundFile, "script" /* scriptElement */, span)); + result.push(nameAndKind(foundFile, "script" /* scriptElement */)); }); } // If possible, get folder completion as well @@ -81473,7 +82786,7 @@ var ts; 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(createPathCompletion(directoryName, "directory" /* directory */, span)); + result.push(nameAndKind(directoryName, "directory" /* directory */)); } } } @@ -81486,26 +82799,26 @@ var ts; * 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) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; var fileExtensions = ts.getSupportedExtensions(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (name, kind) { + var _loop_8 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { - result.push(createPathCompletion(name, kind, span)); + result.push(nameAndKind(name, kind)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_7(name, kind); + _loop_8(name, kind); } } } @@ -81514,14 +82827,14 @@ var ts; 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); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); } }); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { var moduleName = _d[_c]; - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } return result; } @@ -81628,23 +82941,13 @@ var ts; } 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); - return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); - } - 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; - } + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) + : undefined; + return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); @@ -81660,7 +82963,7 @@ var ts; try { typeRoots = ts.getEffectiveTypeRoots(options, host); } - catch (_b) { } + catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; @@ -81692,7 +82995,7 @@ var ts; } function pushResult(moduleName) { if (!seen.has(moduleName)) { - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); seen.set(moduleName, true); } } @@ -81756,9 +83059,11 @@ var ts; } // Replace everything after the last directory seperator that appears function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); } // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) function isPathRelativeToScript(path) { @@ -81808,7 +83113,7 @@ var ts; try { return ts.directoryProbablyExists(path, host); } - catch (_a) { } + catch ( /*ignore*/_a) { /*ignore*/ } return undefined; } function tryIOAndConsumeErrors(host, toApply) { @@ -81819,7 +83124,7 @@ var ts; try { return toApply && toApply.apply(host, args); } - catch (_a) { } + catch ( /*ignore*/_a) { /*ignore*/ } return undefined; } })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); @@ -81835,11 +83140,18 @@ var ts; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { + var GlobalsSearch; + (function (GlobalsSearch) { + GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue"; + GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; + GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; + })(GlobalsSearch || (GlobalsSearch = {})); + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && convertPathCompletions(entries); @@ -81848,19 +83160,19 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log); + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, preferences, compilerOptions.target); if (!completionData) { return undefined; } switch (completionData.kind) { case 0 /* Data */: - return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); case 1 /* JsDocTagName */: // If the current position is a jsDoc tag name, only tag names should be provided for completion return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); @@ -81870,11 +83182,11 @@ var ts; case 3 /* JsDocParameterName */: return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); default: - throw ts.Debug.assertNever(completionData); + return ts.Debug.assertNever(completionData); } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log) { + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -81883,12 +83195,12 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "var" /* variableElement */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } default: return ts.Debug.assertNever(completion); @@ -81906,8 +83218,8 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.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. @@ -81925,14 +83237,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, 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, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -81942,7 +83254,7 @@ var ts; if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isMemberCompletionKind(kind) { switch (kind) { @@ -81971,7 +83283,7 @@ var ts; } }); } - function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); if (!info) { return undefined; @@ -81979,12 +83291,12 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (includeInsertTextCompletions) { + if (preferences.includeCompletionsWithInsertText) { if (origin && origin.type === "this-type") { - insertText = needsConvertPropertyAccess ? "this[" + quote(name) + "]" : "this." + name; + insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; } else if (needsConvertPropertyAccess) { - insertText = "[" + quote(name) + "]"; + insertText = "[" + quote(name, preferences) + "]"; var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; @@ -81999,7 +83311,7 @@ var ts; } } } - if (insertText !== undefined && !includeInsertTextCompletions) { + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -82021,9 +83333,17 @@ var ts; replacementSpan: replacementSpan, }; } - function quote(text) { - // TODO: GH#20619 Use configured quote style - return JSON.stringify(text); + function quote(text, preferences) { + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || @@ -82035,7 +83355,7 @@ var ts; function getSourceFromOrigin(origin) { return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. @@ -82045,7 +83365,7 @@ var ts; for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { var symbol = symbols_4[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } @@ -82111,7 +83431,7 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeFromTypeNode(node.parent.parent.objectType).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); default: return undefined; } @@ -82129,8 +83449,7 @@ var ts; // foo({ // '/*completion position*/' // }); - var type = typeChecker.getContextualType(node.parent.parent); - return { kind: 1 /* Properties */, symbols: type && type.getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); } return fromContextualType(); case 184 /* ElementAccessExpression */: { @@ -82142,13 +83461,13 @@ var ts; // } // let a: A; // a['/*completion position*/'] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeAtLocation(expression).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); } return undefined; } case 185 /* CallExpression */: case 186 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { var argumentInfo_1 = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -82181,6 +83500,9 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker), typeChecker) }; } } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } function getStringLiteralTypes(type, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 32768 /* TypeParameter */) { @@ -82194,7 +83516,7 @@ var ts; } 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, includeInsertTextCompletions: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } @@ -82219,9 +83541,16 @@ var ts; || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; } - function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName, preferences) { var typeChecker = program.getTypeChecker(); var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker); + } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); switch (symbolCompletion.type) { @@ -82240,40 +83569,46 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, 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 }; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, codeActions, sourceDisplay); } - case "none": { + case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. - if (allKeywordsCompletions().some(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 allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createCompletionDetails(name, "" /* none */, "keyword" /* keyword */, [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)]) : undefined; } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo && symbolOriginInfo.type === "export" - ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) - : { codeActions: undefined, sourceDisplay: undefined }; + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, codeActions, sourceDisplay) { + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || symbolOriginInfo.type !== "export") { + return { codeActions: undefined, sourceDisplay: undefined }; + } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { @@ -82291,7 +83626,6 @@ var ts; var CompletionKind; (function (CompletionKind) { CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; - /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */ CompletionKind[CompletionKind["Global"] = 1] = "Global"; CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; @@ -82368,7 +83702,7 @@ var ts; function isModuleSymbol(symbol) { return symbol.declarations.some(function (d) { return d.kind === 272 /* SourceFile */; }); } - function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, preferences, target) { var start = ts.timestamp(); 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.) @@ -82378,6 +83712,7 @@ var ts; var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); var insideJsDocTagTypeExpression = false; + var isInSnippetScope = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { @@ -82551,9 +83886,9 @@ var ts; getTypeScriptMemberSymbols(); } else if (isRightOfOpenTag) { - var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNames(), "getJsxIntrinsicTagNames() should all be defined"); + var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); })); } else { symbols = tagSymbols; @@ -82578,7 +83913,7 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, position, sourceFile, typeChecker); - return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 287 /* JSDocParameterTag */: @@ -82595,6 +83930,7 @@ var ts; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile)); if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { @@ -82604,7 +83940,7 @@ var ts; var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; - var isValidAccess = isRhsOfImportDeclaration ? + var isValidAccess = allowTypeOrValue ? // 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; @@ -82627,6 +83963,7 @@ var ts; } } function addTypeProperties(type) { + isNewIdentifierLocation = hasIndexSignature(type); 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 @@ -82645,50 +83982,42 @@ var ts; } } function tryGetGlobalSymbols() { - var objectLikeContainer; - var namedImportsOrExports; - var classLikeContainer; - var jsxContainer; - if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { - 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 - completionKind = 5 /* None */; - // Declaring new property/method/accessor - isNewIdentifierLocation = true; - // 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 === 254 /* JsxSelfClosingElement */) || (jsxContainer.kind === 255 /* 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); - completionKind = 3 /* MemberLike */; - isNewIdentifierLocation = false; - return true; - } - } - } + var result = tryGetObjectLikeCompletionSymbols() + || tryGetImportOrExportClauseCompletionSymbols() + || tryGetConstructorCompletion() + || tryGetClassLikeCompletionSymbols() + || tryGetJsxCompletionSymbols() + || (getGlobalCompletions(), 1 /* Success */); + return result === 1 /* Success */; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) + return 0 /* Continue */; + // no members, only keywords + completionKind = 5 /* None */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 3 /* ConstructorParameterKeywords */; + return 1 /* Success */; + } + function tryGetJsxCompletionSymbols() { + var jsxContainer = tryGetContainingJsxElement(contextToken); + // Cursor is inside a JSX self-closing element or opening element + var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + if (!attrsType) + return 0 /* Continue */; + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + return 1 /* Success */; + } + function getGlobalCompletions() { if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 3 /* FunctionLikeBodyKeywords */; + keywordFilters = 4 /* FunctionLikeBodyKeywords */; } // Get all entities in the current scope. - completionKind = 5 /* None */; + completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -82722,13 +84051,11 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (isGlobalCompletionScope(scopeNode)) { - completionKind = 1 /* Global */; - } - var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + isInSnippetScope = isSnippetScope(scopeNode); + var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (options.includeInsertTextCompletions && scopeNode.kind !== 272 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 272 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { @@ -82738,13 +84065,13 @@ var ts; } } } - if (options.includeExternalModuleExports) { + // Don't suggest import completions for a commonjs-only module + if (preferences.includeCompletionsForModuleExports && !(sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator)) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } filterGlobalCompletion(symbols); - return true; } - function isGlobalCompletionScope(scopeNode) { + function isSnippetScope(scopeNode) { switch (scopeNode.kind) { case 272 /* SourceFile */: case 200 /* TemplateExpression */: @@ -82756,9 +84083,10 @@ var ts; } } function filterGlobalCompletion(symbols) { - var isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - if (isTypeCompletion) - keywordFilters = 4 /* TypeKeywords */; + var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile); + if (isTypeOnlyCompletion) + keywordFilters = 5 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -82770,19 +84098,22 @@ var ts; if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); } - if (isTypeCompletion) { + if (allowTypes) { // Its a type, but you can reach it by namespace.type as well - return symbolCanBeReferencedAtTypeLocation(symbol); + var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); + if (symbolAllowedAsType || isTypeOnlyCompletion) { + return symbolAllowedAsType; + } } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); }); } function isContextTokenValueLocation(contextToken) { return contextToken && contextToken.kind === 103 /* TypeOfKeyword */ && - contextToken.parent.kind === 164 /* TypeQuery */; + (contextToken.parent.kind === 164 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { @@ -82806,7 +84137,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 793064 /* Type */) { + if (symbol.flags & 67901928 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -82920,7 +84251,7 @@ var ts; || containingNodeKind === 159 /* IndexSignature */ // [ | : string ] || containingNodeKind === 146 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 129 /* ModuleKeyword */: // module | - case 130 /* NamespaceKeyword */:// namespace | + case 130 /* NamespaceKeyword */: // namespace | return true; case 23 /* DotToken */: return containingNodeKind === 237 /* ModuleDeclaration */; // module A.| @@ -82939,10 +84270,10 @@ var ts; return containingNodeKind === 151 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": + switch (keywordForNode(previousToken)) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: return true; } } @@ -82974,18 +84305,19 @@ var ts; * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + function tryGetObjectLikeCompletionSymbols() { + var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); + if (!objectLikeContainer) + return 0 /* Continue */; // We're looking up possible property names from contextual/inferred/declared type. completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 182 /* 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; + return 2 /* Fail */; + isNewIdentifierLocation = hasIndexSignature(typeForObject); typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); existingMembers = objectLikeContainer.properties; } @@ -82995,7 +84327,7 @@ var ts; isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (!ts.isVariableLike(rootDeclaration)) - throw ts.Debug.fail("Root declaration is not variable-like."); + return ts.Debug.fail("Root declaration is not variable-like."); // 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. @@ -83013,7 +84345,7 @@ var ts; if (canGetType) { var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); if (!typeForObject) - return false; + return 2 /* Fail */; // 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; @@ -83023,7 +84355,7 @@ var ts; // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); } - return true; + return 1 /* Success */; } /** * Aggregates relevant symbols for completion in import clauses and export clauses @@ -83040,72 +84372,70 @@ var ts; * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + function tryGetImportOrExportClauseCompletionSymbols() { + var namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken); + if (!namedImportsOrExports) + return undefined; + // cursor is in an import clause + // try to show exported member for imported module var declarationKind = namedImportsOrExports.kind === 245 /* NamedImports */ ? 242 /* ImportDeclaration */ : 248 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { - return false; + return 2 /* Fail */; } completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { symbols = ts.emptyArray; - return true; + return 2 /* Fail */; } var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); - return true; + return 1 /* Success */; } /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. */ - function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + function tryGetClassLikeCompletionSymbols() { + var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location); + if (!decl) + return 0 /* Continue */; // We're looking up possible property names from parent type. completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - // 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 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 /* Private */; - break; - case "static": - classElementModifierFlags = classElementModifierFlags | 32 /* Static */; - break; - } - } - // No member list for private methods - if (!(classElementModifierFlags & 8 /* Private */)) { - var baseClassTypeToGetPropertiesFrom = void 0; - if (baseTypeNode) { - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); - if (classElementModifierFlags & 32 /* Static */) { - // Use static class to get property symbols from - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); - } - } - 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); + keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + // If you're in an interface you don't want to repeat things from super-interface. So just stop here. + if (!ts.isClassLike(decl)) + return 1 /* Success */; + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // 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 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; } } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + // List of property symbols of base type that are not private and already implemented + var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } + return 1 /* Success */; } /** * Returns the immediate owning object literal or binding pattern of a context token, @@ -83115,7 +84445,7 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */:// const x = { a: 0, | + case 26 /* CommaToken */: // const x = { a: 0, | var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; @@ -83133,7 +84463,7 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // import { | - case 26 /* CommaToken */:// import { a as 0, | + case 26 /* CommaToken */: // import { a as 0, | switch (contextToken.parent.kind) { case 245 /* NamedImports */: case 249 /* NamedExports */: @@ -83143,61 +84473,9 @@ var ts; } return undefined; } - function isFromClassElementDeclaration(node) { - return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); - } - function isParameterOfConstructorDeclaration(node) { - return ts.isParameter(node) && ts.isConstructorDeclaration(node.parent); - } function isConstructorParameterCompletion(node) { - return node.parent && - 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 /* OpenBraceToken */:// class c { | - if (ts.isClassLike(contextToken.parent)) { - return contextToken.parent; - } - break; - // class c {getValue(): number, | } - case 26 /* CommaToken */: - if (ts.isClassLike(contextToken.parent)) { - return contextToken.parent; - } - break; - // 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) && - (isClassMemberCompletionKeyword(contextToken.kind) || - isClassMemberCompletionKeywordText(contextToken.getText()))) { - return contextToken.parent.parent; - } - } - } - // class c { method() { } | method2() { } } - if (location && location.kind === 293 /* SyntaxList */ && ts.isClassLike(location.parent)) { - return location.parent; - } - return undefined; + return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent) + && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node)); } /** * Returns the immediate owning class declaration of a context token, @@ -83319,14 +84597,7 @@ var ts; return containingNodeKind === 267 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: - return containingNodeKind === 236 /* EnumDeclaration */ || // enum a { | - containingNodeKind === 234 /* InterfaceDeclaration */ || // interface a { | - containingNodeKind === 165 /* TypeLiteral */; // const x : { | - case 25 /* SemicolonToken */: - return containingNodeKind === 150 /* PropertySignature */ && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 234 /* InterfaceDeclaration */ || // interface a { f; | - contextToken.parent.parent.kind === 165 /* TypeLiteral */); // const x : { a; | + return containingNodeKind === 236 /* EnumDeclaration */; // enum a { | case 27 /* LessThanToken */: return containingNodeKind === 233 /* ClassDeclaration */ || // class A< | containingNodeKind === 203 /* ClassExpression */ || // var C = class D< | @@ -83349,7 +84620,7 @@ var ts; containingNodeKind === 244 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromClassElementDeclaration(contextToken)) { + if (isFromObjectTypeDeclaration(contextToken)) { return false; } // falls through @@ -83362,13 +84633,12 @@ var ts; case 110 /* LetKeyword */: case 76 /* ConstKeyword */: case 116 /* YieldKeyword */: - case 139 /* TypeKeyword */:// type htm| + case 139 /* 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)) { + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; } if (isConstructorParameterCompletion(contextToken)) { @@ -83377,28 +84647,28 @@ var ts; // - its name of the parameter and not being edited // eg. constructor(a |<- this shouldnt show completion if (!ts.isIdentifier(contextToken) || - isConstructorParameterCompletionKeywordText(contextToken.getText()) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || isCurrentlyEditingNode(contextToken)) { return false; } } // Previous token may have been a keyword that was converted to an identifier. - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": + switch (keywordForNode(contextToken)) { + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 75 /* ClassKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 83 /* EnumKeyword */: + case 89 /* FunctionKeyword */: + case 109 /* InterfaceKeyword */: + case 110 /* LetKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 115 /* StaticKeyword */: + case 104 /* VarKeyword */: + case 116 /* YieldKeyword */: return true; } return ts.isDeclarationName(contextToken) @@ -83477,7 +84747,7 @@ var ts; // 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); + existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } existingMemberNames.set(existingName, true); } @@ -83488,7 +84758,7 @@ var ts; * * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags */ - function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; @@ -83508,10 +84778,7 @@ var ts; continue; } // 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)) { + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { continue; } var existingName = ts.getPropertyNameForPropertyNameNode(m.name); @@ -83519,23 +84786,11 @@ var ts; existingMemberNames.set(existingName, true); } } - var result = []; - 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++) { - var property = properties_12[_i]; - if (isValidProperty(property, inValidModifierFlags)) { - result.push(property); - } - } - } - function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.escapedName) && - propertySymbol.getDeclarations() && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); - } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. @@ -83558,7 +84813,7 @@ var ts; return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { - return node.getStart() <= position && position <= node.getEnd(); + return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { @@ -83581,10 +84836,10 @@ var ts; // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2 /* PropertyAccess */: - case 5 /* None */: case 1 /* Global */: // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 5 /* None */: case 4 /* String */: return validIdentiferResult; default: @@ -83614,62 +84869,36 @@ var ts; return kind !== 140 /* UndefinedKeyword */; case 1 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* ConstructorParameterKeywords */: - return isConstructorParameterCompletionKeyword(kind); - case 3 /* FunctionLikeBodyKeywords */: - return isFunctionLikeBodyCompletionKeyword(kind); - case 4 /* TypeKeywords */: + case 2 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 3 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 4 /* FunctionLikeBodyKeywords */: + return !isClassMemberCompletionKeyword(kind); + case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); } })); } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 132 /* ReadonlyKeyword */; + } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: case 123 /* ConstructorKeyword */: - case 132 /* ReadonlyKeyword */: case 125 /* GetKeyword */: case 136 /* SetKeyword */: case 120 /* AsyncKeyword */: return true; + default: + return ts.isClassMemberModifier(kind); } } - function isClassMemberCompletionKeywordText(text) { - return isClassMemberCompletionKeyword(ts.stringToToken(text)); - } - function isConstructorParameterCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - } - } - function isConstructorParameterCompletionKeywordText(text) { - return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); - } - function isFunctionLikeBodyCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: - case 117 /* AbstractKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 140 /* UndefinedKeyword */: - return false; - } - return true; + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } function isEqualityOperatorKind(kind) { switch (kind) { @@ -83727,6 +84956,48 @@ var ts; }); return ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined"); } + /** + * 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 tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 293 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 25 /* SemicolonToken */: // class c {getValue(): number; | } + case 18 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 17 /* OpenBraceToken */: // class c { | + case 26 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && (ts.isClassElement(node.parent) || ts.isTypeElement(node.parent)) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -83757,30 +85028,17 @@ var ts; } function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); - return referenceEntries && convertReferencedSymbols(referenceEntries); - } - function convertReferencedSymbols(referenceEntries) { - var fileNameToDocumentHighlights = ts.createMap(); - for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { - var entry = referenceEntries_1[_i]; - var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span; - var highlightSpans = fileNameToDocumentHighlights.get(fileName); - if (!highlightSpans) { - fileNameToDocumentHighlights.set(fileName, highlightSpans = []); - } - highlightSpans.push(span_12); - } - return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) { + if (!referenceEntries) + return undefined; + var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); + return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; return ({ fileName: fileName, highlightSpans: highlightSpans }); }); } function getSyntacticDocumentHighlights(node, sourceFile) { var highlightSpans = getHighlightSpans(node, sourceFile); - if (!highlightSpans || highlightSpans.length === 0) { - return undefined; - } - return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { @@ -84321,7 +85579,9 @@ var ts; } else if (ts.isDefaultImport(direct)) { var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); - addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + if (!isAvailableThroughGlobal) { + addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + } directImports.push(direct); } else { @@ -84473,7 +85733,7 @@ var ts; 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) { + if (!isForRename) { // If renaming `foo`, don't touch `bar`, just `foo`. // Search locally for `bar`. addSearch(name, checker.getSymbolAtLocation(name)); } @@ -84569,8 +85829,8 @@ var ts; function forEachImport(sourceFile, action) { if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); } } else { @@ -84597,19 +85857,6 @@ var ts; }); } } - function importerFromModuleSpecifier(moduleSpecifier) { - var decl = moduleSpecifier.parent; - switch (decl.kind) { - case 185 /* CallExpression */: - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - return decl; - case 252 /* 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. @@ -84648,12 +85895,15 @@ var ts; return exportInfo(symbol, getExportKindForDeclaration(exportNode)); } } + // If we are in `export = a;` or `export default a;`, `parent` is the export assignment. else if (ts.isExportAssignment(parent)) { return getExportAssignmentExport(parent); } + // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. else if (ts.isExportAssignment(parent.parent)) { return getExportAssignmentExport(parent.parent); } + // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } @@ -84724,10 +85974,10 @@ var ts; return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } var decl = importedSymbol.valueDeclaration; - if (ts.isExportAssignment(decl)) { + if (ts.isExportAssignment(decl)) { // `export = class {}` return ts.Debug.assertDefined(decl.expression.symbol); } - else if (ts.isBinaryExpression(decl)) { + else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } return ts.Debug.fail(); @@ -84804,8 +86054,8 @@ var ts; if (parent.kind === 272 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 238 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent)); - return parent.parent; + ts.Debug.assert(parent.kind === 238 /* ModuleBlock */); + return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { return node.kind === 237 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; @@ -84827,12 +86077,13 @@ var ts; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {}); var checker = program.getTypeChecker(); return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { var definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. - return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }; + return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) }; }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; @@ -84852,9 +86103,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 269 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -84868,8 +86119,8 @@ var ts; } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); - return ts.map(x, toReferenceEntry); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { @@ -84877,60 +86128,50 @@ var ts; return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); - } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); } - function definitionToReferencedSymbolDefinitionInfo(def, checker) { + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { case "symbol": { - var symbol = def.symbol, node_3 = def.node; - var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var symbol = def.symbol; + var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - 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)] }; + 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)] }; } case "keyword": { - var node_5 = def.node; - var name_5 = ts.tokenToString(node_5.kind); - return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* 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 */ }] }; } case "this": { - 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 }; + 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 }; } case "string": { - 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)] }; + 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)] }; } + default: + return ts.Debug.assertNever(def); } })(); - if (!info) { - return undefined; - } var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); - return { - containerKind: "" /* unknown */, - containerName: "", - fileName: sourceFile.fileName, - kind: kind, - name: name, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: displayParts - }; + var textSpan = getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile); + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: textSpan, displayParts: displayParts }; } - function getDefinitionKindAndDisplayParts(symbol, node, checker) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind; + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); + var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } function toReferenceEntry(entry) { @@ -84961,7 +86202,7 @@ var ts; function implementationKindDisplayParts(node, checker) { var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node); if (symbol) { - return getDefinitionKindAndDisplayParts(symbol, node, checker); + return getDefinitionKindAndDisplayParts(symbol, checker, node); } else if (node.kind === 182 /* ObjectLiteralExpression */) { return { @@ -84995,8 +86236,8 @@ var ts; return { fileName: fileName, span: span }; } FindAllReferences.toHighlightSpan = toHighlightSpan; - function getTextSpan(node) { - var start = node.getStart(); + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); var end = node.getEnd(); if (node.kind === 9 /* StringLiteral */) { start += 1; @@ -85054,7 +86295,7 @@ var ts; case 248 /* ExportDeclaration */: return true; case 185 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); default: return false; } @@ -85086,10 +86327,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ - definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, - references: references - }]; + return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -85097,17 +86335,15 @@ var ts; 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.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 if (ts.isLabelOfLabeledStatement(node)) { + // 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); @@ -85121,11 +86357,11 @@ var ts; function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); + var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); var result = []; var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === 79 /* DefaultKeyword */) { - addReference(node, symbol, node, state); + addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { @@ -85134,7 +86370,7 @@ var ts; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); } else { // Global search @@ -85229,7 +86465,11 @@ var ts; this.symbolIdToReferences = []; // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. this.sourceFileToSeenSymbols = []; + this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; }); } + State.prototype.includesSourceFile = function (sourceFile) { + return this.includedSourceFiles.has(sourceFile.fileName); + }; /** 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) @@ -85243,11 +86483,11 @@ var ts; // 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). - 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 _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { - location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, + symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, }; }; @@ -85255,12 +86495,12 @@ var ts; * 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) { + State.prototype.referenceAdder = function (searchSymbol) { var symbolId = ts.getSymbolId(searchSymbol); var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references }); + this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; @@ -85285,7 +86525,7 @@ var ts; 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); + var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; addRef(singleRef); @@ -85321,7 +86561,9 @@ var ts; 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 /* Import */), state); + var exportingFile = declaration.getSourceFile(); + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); } } /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ @@ -85421,6 +86663,17 @@ var ts; // 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; } + /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ + function isSymbolReferencedInFile(definition, checker, sourceFile) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return true; // Be lenient with invalid code. + return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) { + var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), ts.isIdentifier); + return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol; + }); + } + Core.isSymbolReferencedInFile = isSymbolReferencedInFile; function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } var positions = []; @@ -85451,18 +86704,13 @@ var ts; return positions; } function getLabelReferencesInNode(container, targetLabel) { - var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); - for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { - var position = possiblePositions_1[_i]; + var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) { 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)); - } - } + return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined; + }); return [{ definition: { type: "label", node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { @@ -85470,9 +86718,11 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.text.length === searchSymbolName.length; + case 9 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + str.text.length === searchSymbolName.length; + } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; case 79 /* DefaultKeyword */: @@ -85482,43 +86732,35 @@ var ts; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { - var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); - } + return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; + }); + }); return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } - function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - 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, /*includeJsDocComment*/ true); - if (referenceLocation.kind === kind) { - references.push(FindAllReferences.nodeEntry(referenceLocation)); - } - } - } - function getReferencesInSourceFile(sourceFile, search, state) { + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } state.cancellationToken.throwIfCancellationRequested(); - return getReferencesInContainer(sourceFile, sourceFile, search, state); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); } /** * 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) { + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; - getReferencesAtLocation(sourceFile, position, search, state); + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } - function getReferencesAtLocation(sourceFile, position, search, state) { + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { 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 @@ -85547,7 +86789,7 @@ var ts; } if (ts.isExportSpecifier(parent)) { ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); - getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); @@ -85557,7 +86799,8 @@ var ts; } switch (state.specialSearchKind) { case 0 /* None */: - addReference(referenceLocation, relatedSymbol, search.location, state); + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); break; case 1 /* Constructor */: addConstructorReferences(referenceLocation, sourceFile, search, state); @@ -85570,7 +86813,7 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -85586,8 +86829,8 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, name, state); + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { + addReference(name, referenceSymbol, state); } } else { @@ -85609,7 +86852,8 @@ var ts; searchForImportedSymbol(imported, state); } function addRef() { - addReference(referenceLocation, localSymbol, search.location, state); + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); } } function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { @@ -85654,11 +86898,11 @@ var ts; * 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); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state); } } - function addReference(referenceLocation, relatedSymbol, searchLocation, state) { - var addRef = state.referenceAdder(relatedSymbol, searchLocation); + function addReference(referenceLocation, relatedSymbol, state) { + var addRef = state.referenceAdder(relatedSymbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } @@ -85669,9 +86913,9 @@ var ts; /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ function addConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { - addReference(referenceLocation, search.symbol, search.location, state); + addReference(referenceLocation, search.symbol, state); } - var pusher = function () { return state.referenceAdder(search.symbol, search.location); }; + var pusher = function () { return state.referenceAdder(search.symbol); }; if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. @@ -85686,11 +86930,11 @@ var ts; } } function addClassStaticThisReferences(referenceLocation, search, state) { - addReference(referenceLocation, search.symbol, search.location, state); - if (ts.isClassLike(referenceLocation.parent)) { + addReference(referenceLocation, search.symbol, state); + if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); // This is the class declaration. - addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol)); } } function addStaticThisReferences(classLike, pusher) { @@ -85815,7 +87059,7 @@ var ts; return result; } function getContainingTypeReference(node) { - var topLevelTypeReference = undefined; + var topLevelTypeReference; while (node) { if (ts.isTypeNode(node)) { topLevelTypeReference = node; @@ -85869,58 +87113,29 @@ var ts; * distinction between structurally compatible implementations and explicit implementations, so we * must use the AST. * - * @param child A class or interface Symbol + * @param symbol 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 /* Interface */; - return searchHierarchy(child); - function searchHierarchy(symbol) { - if (symbol === parent) { - return true; - } - var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); - var cached = cachedResults.get(key); - 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)) { - if (parentIsInterface) { - var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); - if (interfaceReferences) { - for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { - var typeReference = interfaceReferences_1[_i]; - if (searchTypeReference(typeReference)) { - return true; - } - } - } - } - return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - } - else if (declaration.kind === 234 /* InterfaceDeclaration */) { - if (parentIsInterface) { - return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); - } - } - return false; - }); - cachedResults.set(key, inherits); - return inherits; + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; } - function searchTypeReference(typeReference) { - if (typeReference) { + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { var type = checker.getTypeAtLocation(typeReference); - if (type && type.symbol) { - return searchHierarchy(type.symbol); - } - } - return false; - } + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; } function getReferencesForSuperKeyword(superKeyword) { var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); @@ -85943,24 +87158,19 @@ var ts; default: return undefined; } - var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== 97 /* SuperKeyword */) { - continue; + return; } 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 }]; + return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -85995,18 +87205,11 @@ var ts; return undefined; } var references = []; - var possiblePositions; - if (searchSpaceNode.kind === 272 /* SourceFile */) { - ts.forEach(sourceFiles, function (sourceFile) { - cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); - getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, staticFlag, references); - }); - } - else { - var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); - getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, references); + for (var _i = 0, _a = searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + cancellationToken.throwIfCancellationRequested(); + var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode); + getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFile : searchSpaceNode, positions, staticFlag, references); } return [{ definition: { type: "this", node: thisOrSuperKeyword }, @@ -86050,26 +87253,17 @@ var ts; }); } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { - var references = []; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); - getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); - } + return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) { + var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false), ts.isStringLiteral); + return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + }); + }); return [{ definition: { type: "string", node: node }, references: references }]; - 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_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. @@ -86151,9 +87345,6 @@ var ts; * 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: @@ -86165,25 +87356,17 @@ var ts; // 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)) { + if (!symbol || previousIterationSymbolsCache.has(symbol.escapedName)) { return; } 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 === 234 /* InterfaceDeclaration */) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = checker.getTypeAtLocation(typeReference); - if (type) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + for (var _b = 0, _c = ts.getAllSuperTypeNodes(declaration); _b < _c.length; _b++) { + var typeReference = _c[_b]; + var type = checker.getTypeAtLocation(typeReference); + if (!type) + continue; var propertySymbol = checker.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push.apply(result, checker.getRootSymbols(propertySymbol)); @@ -86241,7 +87424,10 @@ var ts; return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { // if it is in the list, then we are done if (search.includes(rootSymbol)) { - return rootSymbol; + // For a root symbol that is a component of a union or intersection, use the original (union/intersection) symbol. + // That we when a symbol references the whole union we avoid claiming it references some particular member of the union. + // For a transient symbol we want to use the root symbol instead. + return ts.getCheckFlags(sym) & 6 /* Synthetic */ ? sym : rootSymbol; } // 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 @@ -86253,7 +87439,7 @@ var ts; } var result = []; getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); - return ts.find(result, search.includes); + return result.some(search.includes) ? rootSymbol : undefined; } return undefined; }); @@ -86286,7 +87472,9 @@ var ts; * 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) { + function getIntersectingMeaningFromDeclarations(node, symbol) { + var meaning = ts.getMeaningFromLocation(node); + var declarations = symbol.declarations; if (declarations) { var lastIterationMeaning = void 0; do { @@ -86307,36 +87495,12 @@ var ts; } return meaning; } + Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; function isImplementation(node) { - if (!node) { - return false; - } - else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { - return true; - } - else if (node.kind === 230 /* VariableDeclaration */) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); - } - else if (ts.isFunctionLike(node)) { - return !!node.body || ts.hasModifier(node, 2 /* Ambient */); - } - else { - switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: - return true; - } - } - return false; - } - function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 212 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 231 /* VariableDeclarationList */); - return node.parent.parent; - } + return !!(node.flags & 2097152 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); } function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { var refSymbol = checker.getSymbolAtLocation(node); @@ -86363,12 +87527,6 @@ var ts; function tryGetClassByExtendingIdentifier(node) { return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); } - function isNameOfExternalModuleImportOrDeclaration(node) { - 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 @@ -86410,9 +87568,8 @@ var ts; } // Labels if (ts.isJumpStatementTarget(node)) { - var labelName = node.text; - var label = ts.getTargetLabel(node.parent, labelName); - return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined; + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -86625,8 +87782,8 @@ var ts; return createDefinitionInfo(decl, symbolKind, symbolName, containerName); } function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; + for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { + var ref = refs_2[_i]; if (ref.pos <= pos && pos <= ref.end) { return ref; } @@ -87268,8 +88425,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -87351,7 +88508,7 @@ var ts; case 6 /* NameContainsNonURISafeCharacters */: return "Package name '" + typing + "' contains non URI safe characters"; case 0 /* Ok */: - throw ts.Debug.fail(); // Shouldn't have called this. + return ts.Debug.fail(); // Shouldn't have called this. default: ts.Debug.assertNever(result); } @@ -87367,19 +88524,19 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_8 = function (sourceFile) { + var _loop_9 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; } - ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { + sourceFile.getNamedDeclarations().forEach(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_8(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_9(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -87438,41 +88595,35 @@ var ts; return true; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - var text = ts.getTextOfIdentifierOrLiteral(name); - if (text !== undefined) { - containers.unshift(text); - } - else if (name.kind === 146 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } - } + var name = ts.getNameOfDeclaration(declaration); + if (name && ts.isPropertyNameLiteral(name)) { + containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); + return true; + } + else if (name && name.kind === 146 /* 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) { + if (ts.isPropertyNameLiteral(expression)) { + var text = ts.getTextOfIdentifierOrLiteral(expression); if (includeLastPortion) { containers.unshift(text); } return true; } - if (expression.kind === 183 /* PropertyAccessExpression */) { - var propertyAccess = expression; + if (ts.isPropertyAccessExpression(expression)) { if (includeLastPortion) { - containers.unshift(propertyAccess.name.text); + containers.unshift(expression.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); + return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true); } return false; } @@ -87775,6 +88926,7 @@ var ts; case 1 /* ExportsProperty */: case 2 /* ModuleExports */: case 3 /* PrototypeProperty */: + case 6 /* Prototype */: addNodeWithRecursiveChild(node, node.right); break; case 4 /* ThisProperty */: @@ -88111,16 +89263,20 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } + // See if it is a var initializer. If so, use the var name. else if (node.parent.kind === 230 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } + // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. else if (node.parent.kind === 198 /* BinaryExpression */ && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } + // See if it is a property assignment, and if so use the property name else if (node.parent.kind === 268 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } + // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -88145,44 +89301,111 @@ var ts; (function (ts) { var OrganizeImports; (function (OrganizeImports) { - function organizeImports(sourceFile, formatContext, host) { - // TODO (https://github.com/Microsoft/TypeScript/issues/10020): sort *within* ambient modules (find using isAmbientModule) - // All of the old ImportDeclarations in the file, in syntactic order. - var oldImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - if (oldImportDecls.length === 0) { - return []; - } - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { - return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); - }); - var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { - return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup)) - : importGroup; - }); + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); - // Delete or replace the first import. - if (newImportDecls.length === 0) { - changeTracker.deleteNode(sourceFile, oldImportDecls[0]); - } - else { - // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - useNonAdjustedStartPosition: false, - useNonAdjustedEndPosition: false, - suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + // All of the old ImportDeclarations in the file, in syntactic order. + var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(topLevelImportDecls); + for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { + var ambientModule = _a[_i]; + var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(ambientModuleImportDecls); } return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls) { + if (ts.length(oldImportDecls) === 0) { + return; + } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); + var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); + var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { + return getExternalModuleName(importGroup[0].moduleSpecifier) + ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + : importGroup; + }); + // Delete or replace the first import. + if (newImportDecls.length === 0) { + changeTracker.deleteNode(sourceFile, oldImportDecls[0], { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + }); + } + else { + // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), + }); + } + // Delete any subsequent imports. + for (var i = 1; i < oldImportDecls.length; i++) { + changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + } + } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports) { - return oldImports; // TODO (https://github.com/Microsoft/TypeScript/issues/10020) + function getModuleBlock(moduleDecl) { + var body = moduleDecl.body; + return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + } + function removeUnusedImports(oldImports, sourceFile, program) { + var typeChecker = program.getTypeChecker(); + var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var usedImports = []; + for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { + var importDecl = oldImports_1[_i]; + var importClause = importDecl.importClause; + if (!importClause) { + // Imports without import clauses are assumed to be included for their side effects and are not removed. + usedImports.push(importDecl); + continue; + } + var name = importClause.name, namedBindings = importClause.namedBindings; + // Default import + if (name && !isDeclarationUsed(name)) { + name = undefined; + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + // Namespace import + if (!isDeclarationUsed(namedBindings.name)) { + namedBindings = undefined; + } + } + else { + // List of named imports + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); + if (newElements.length < namedBindings.elements.length) { + namedBindings = newElements.length + ? ts.updateNamedImports(namedBindings, newElements) + : undefined; + } + } + } + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + // The JSX factory symbol is always used. + return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + } } function getExternalModuleName(specifier) { return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier) @@ -88197,7 +89420,7 @@ var ts; if (importGroup.length === 0) { return importGroup; } - var _a = getImportParts(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; + var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; var coalescedImports = []; if (importWithoutClause) { coalescedImports.push(importWithoutClause); @@ -88206,15 +89429,17 @@ var ts; // produce two import declarations in this special case. if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { // Add the namespace import to the existing default ImportDeclaration. - var defaultImportClause = defaultImports[0].parent; - coalescedImports.push(updateImportDeclarationAndClause(defaultImportClause, defaultImportClause.name, namespaceImports[0])); + var defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); return coalescedImports; } - var sortedNamespaceImports = ts.stableSort(namespaceImports, function (n1, n2) { return compareIdentifiers(n1.name, n2.name); }); + var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { + return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); + }); for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { var namespaceImport = sortedNamespaceImports_1[_i]; // Drop the name, if any - coalescedImports.push(updateImportDeclarationAndClause(namespaceImport.parent, /*name*/ undefined, namespaceImport)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -88222,30 +89447,37 @@ var ts; var newDefaultImport; var newImportSpecifiers = []; if (defaultImports.length === 1) { - newDefaultImport = defaultImports[0]; + newDefaultImport = defaultImports[0].importClause.name; } else { for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { var defaultImport = defaultImports_1[_b]; - newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (n) { return n.elements; })); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || compareIdentifiers(s1.name, s2.name); }); - var importClause = defaultImports.length > 0 - ? defaultImports[0].parent - : namedImports[0].parent; + var importDecl = defaultImports.length > 0 + ? defaultImports[0] + : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 ? undefined : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0], sortedImportSpecifiers); - coalescedImports.push(updateImportDeclarationAndClause(importClause, newDefaultImport, newNamedImports)); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; - function getImportParts(importGroup) { + /* + * Returns entire import declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + * + * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`. + */ + function getCategorizedImports(importGroup) { var importWithoutClause; var defaultImports = []; var namespaceImports = []; @@ -88260,14 +89492,14 @@ var ts; } var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; if (name) { - defaultImports.push(name); + defaultImports.push(importDeclaration); } if (namedBindings) { if (ts.isNamespaceImport(namedBindings)) { - namespaceImports.push(namedBindings); + namespaceImports.push(importDeclaration); } else { - namedImports.push(namedBindings); + namedImports.push(importDeclaration); } } } @@ -88281,12 +89513,11 @@ var ts; function compareIdentifiers(s1, s2) { return ts.compareStringsCaseSensitive(s1.text, s2.text); } - function updateImportDeclarationAndClause(importClause, name, namedBindings) { - var importDeclaration = importClause.parent; - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, name, namedBindings), importDeclaration.moduleSpecifier); - } } OrganizeImports.coalesceImports = coalesceImports; + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + } /* internal */ // Exported for testing function compareModuleSpecifiers(m1, m2) { var name1 = getExternalModuleName(m1); @@ -88334,13 +89565,13 @@ var ts; 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+(.*))?$/); + var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/); 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")); + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region")); } else { var region = regions.pop(); @@ -88579,10 +89810,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_14 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false)); + /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); } } } @@ -88684,7 +89915,7 @@ var ts; // // Only if all words have some sort of match is the pattern considered matched. var subWordTextChunks = segment.subWordTextChunks; - var matches = undefined; + var matches; for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { var subWordTextChunk = subWordTextChunks_1[_i]; // Try to match the candidate with this word @@ -88732,8 +89963,8 @@ var ts; // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; - var firstMatch = undefined; - var contiguous = undefined; + var firstMatch; + var contiguous; while (true) { // Let's consider our termination cases if (currentChunkSpan === chunkCharacterSpans.length) { @@ -89033,11 +90264,18 @@ var ts; function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { if (readImportFiles === void 0) { readImportFiles = true; } if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } - var referencedFiles = []; - var typeReferenceDirectives = []; + var pragmaContext = { + languageVersion: 1 /* ES5 */, + pragmas: undefined, + checkJsDirective: undefined, + referencedFiles: [], + typeReferenceDirectives: [], + amdDependencies: [], + hasNoDefaultLib: undefined, + moduleName: undefined + }; var importedFiles = []; 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 @@ -89052,23 +90290,6 @@ var ts; } return token; } - function processTripleSlashDirectives() { - var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); - ts.forEach(commentRanges, function (commentRange) { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); - if (referencePathMatchResult) { - isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; - if (fileReference) { - var collection = referencePathMatchResult.isTypeReferenceDirective - ? typeReferenceDirectives - : referencedFiles; - collection.push(fileReference); - } - } - }); - } function getFileReference() { var fileName = ts.scanner.getTokenValue(); var pos = ts.scanner.getTokenPos(); @@ -89329,7 +90550,8 @@ var ts; if (readImportFiles) { processImports(); } - processTripleSlashDirectives(); + ts.processCommentPragmas(pragmaContext, sourceText); + ts.processPragmasIntoFields(pragmaContext, ts.noop); if (externalModule) { // for external modules module all nested ambient modules are augmentations if (ambientExternalModules) { @@ -89339,7 +90561,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; } else { // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 @@ -89358,7 +90580,7 @@ var ts; } } } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -89389,22 +90611,17 @@ var ts; 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(); + var declarations = symbol.declarations; if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. - if (ts.some(declarations, isDefinedInLibraryFile)) { + if (declarations.some(isDefinedInLibraryFile)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // 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 */) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - if (!kind) { - return undefined; - } var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; @@ -89413,12 +90630,11 @@ var ts; return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } - else if (node.kind === 9 /* StringLiteral */) { + else if (ts.isStringLiteral(node)) { 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" /* variableElement */, "" /* none */, node, sourceFile); + return getRenameInfoSuccess(node.text, node.text, "var" /* variableElement */, "" /* none */, node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -89876,11 +91092,75 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program) { + program.getSemanticDiagnostics(sourceFile); + var checker = program.getDiagnosticsProducingTypeChecker(); + var diags = []; + if (sourceFile.commonJsModuleIndicator) { + diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + } + var isJsFile = ts.isSourceFileJavaScript(sourceFile); + function check(node) { + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 190 /* FunctionExpression */: + if (isJsFile) { + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + } + break; + } + if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + node.forEachChild(check); + } + check(sourceFile); + if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); + if (!name) + continue; + var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + } + } + } + return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + } + ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + function importNameForConvertToDefaultImport(node) { + switch (node.kind) { + case 242 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 241 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + if (result !== "" /* unknown */) { + return result; + } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { return ts.getDeclarationOfKind(symbol, 203 /* ClassExpression */) ? @@ -89894,17 +91174,14 @@ var ts; return "interface" /* interfaceElement */; if (flags & 262144 /* TypeParameter */) return "type parameter" /* typeParameterElement */; - var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - 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 */; - } + 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; @@ -90085,7 +91362,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) { + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) { // At constructor keyword of constructor declaration // 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 @@ -90567,7 +91844,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_10 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -90586,7 +91863,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_10(opt); } return options; } @@ -91363,7 +92640,7 @@ var ts; // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 234 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one + case 234 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -92197,8 +93474,8 @@ var ts; 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 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); + var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { @@ -93165,26 +94442,14 @@ var ts; function isControlFlowEndingStatement(kind, parent) { switch (kind) { case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: - switch (parent.kind) { - case 211 /* Block */: - var grandParent = parent.parent; - switch (grandParent && grandParent.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - // We may want to write inner functions after this. - return false; - default: - return true; - } - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 272 /* SourceFile */: - case 238 /* ModuleBlock */: - return true; - default: - throw ts.Debug.fail(); + case 227 /* ThrowStatement */: { + if (parent.kind !== 211 /* Block */) { + return true; } + var grandParent = parent.parent; + // In a function, we may want to write inner functions after this. + return !(grandParent && grandParent.kind === 190 /* FunctionExpression */ || grandParent.kind === 232 /* FunctionDeclaration */); + } case 221 /* ContinueStatement */: case 222 /* BreakStatement */: return true; @@ -93261,14 +94526,14 @@ var ts; ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; })(ChangeKind || (ChangeKind = {})); - function getSeparatorCharacter(separator) { - return ts.tokenToString(separator.kind); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - textChanges_1.getSeparatorCharacter = getSeparatorCharacter; function getAdjustedStartPosition(sourceFile, node, options, position) { if (options.useNonAdjustedStartPosition) { - return node.getStart(); + return node.getStart(sourceFile); } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); @@ -93295,7 +94560,6 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } - textChanges_1.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { return node.getEnd(); @@ -93306,7 +94570,6 @@ var ts; ? newEnd : end; } - textChanges_1.getAdjustedEndPosition = getAdjustedEndPosition; /** * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ @@ -93322,10 +94585,9 @@ var ts; } var ChangeTracker = /** @class */ (function () { /** Public for tests only. Other callers should use `ChangeTracker.with`. */ - function ChangeTracker(newLineCharacter, formatContext, validator) { + function ChangeTracker(newLineCharacter, formatContext) { this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; - this.validator = validator; this.changes = []; this.deletedNodesInLists = []; // 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 @@ -93343,6 +94605,7 @@ var ts; this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; }; + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); @@ -93402,47 +94665,39 @@ var ts; } return this; }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); }; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); - return this; + this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + }; + ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -93460,14 +94715,45 @@ var ts; var pos = before.getStart(sourceFile); this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); + var text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: { pos: pos, end: pos }, text: text }); + }; + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ + ChangeTracker.prototype.insertTypeAnnotation = function (sourceFile, node, type) { + var end = (ts.isFunctionLike(node) + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + ? ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile) || ts.first(node.parameters) + : node.kind !== 230 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name).end; + this.insertNodeAt(sourceFile, end, type, { prefix: ": " }); + }; + ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { + // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter + var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); + }; ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { if (ts.isStatement(before) || ts.isClassElement(before)) { return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; } - else if (ts.isVariableDeclaration(before)) { + else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2; return { suffix: ", " }; } - throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + else if (ts.isParameter(before)) { + return {}; + } + return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it }; ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { var firstStatement = ts.firstOrUndefined(ctr.body.statements); @@ -93488,7 +94774,7 @@ var ts; } }; ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { - this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); @@ -93522,17 +94808,11 @@ var ts; // 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 /* SemicolonToken */) - }); + this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, { pos: endPosition, end: endPosition }, newNode, this.getInsertNodeAfterOptions(after)); + return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); }; ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { @@ -93544,7 +94824,10 @@ var ts; else if (ts.isVariableDeclaration(node)) { return { prefix: ", " }; } - throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it + else if (ts.isParameter(node)) { + return {}; + } + return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, @@ -93609,17 +94892,9 @@ var ts; // let insert position be the beginning of the line that contains next element startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, - 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)) - } - }); + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -93651,13 +94926,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: ts.createToken(separator), - options: {} - }); + this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); // 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 @@ -93665,22 +94934,10 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: insertPos, end: insertPos }, - node: newNode, - options: { indentation: indentation, prefix: this.newLineCharacter } - }); + this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: newNode, - options: { prefix: ts.tokenToString(separator) + " " } - }); + this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; @@ -93692,95 +94949,86 @@ var ts; var newCls = cls.kind === 233 /* ClassDeclaration */ ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); - _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + _this.replaceNode(sourceFile, cls, newCls); }); }; - ChangeTracker.prototype.getChanges = function () { - var _this = this; + /** + * Note: after calling this, the TextChanges object must be discarded! + * @param validate only for tests + * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions, + * so we can only call this once and can't get the non-formatted text separately. + */ + ChangeTracker.prototype.getChanges = function (validate) { this.finishInsertNodeAtClassStart(); - return ts.group(this.changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { - var sourceFile = changesInFile[0].sourceFile; - var textChanges = ChangeTracker.normalize(changesInFile).map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), _this.computeNewText(c, sourceFile)); - }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; - }); - }; - ChangeTracker.prototype.computeNewText = function (change, sourceFile) { - var _this = this; - if (change.kind === ChangeKind.Remove) { - // deletion case - return ""; - } - var options = change.options || {}; - var text; - var pos = change.range.pos; - var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - if (change.kind === ChangeKind.ReplaceWithMultipleNodes) { - var lastIndex_1 = change.nodes.length - 1; - var parts = change.nodes.map(function (n, index) { - var formatted = _this.getFormattedTextOfNode(n, sourceFile, pos, options); - return index === lastIndex_1 || ts.endsWith(formatted, _this.newLineCharacter) - ? formatted - : (formatted + _this.newLineCharacter); - }); - text = parts.join(""); - } - else { - 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 || ""); - }; - ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) { - var nonformattedText = getNonformattedText(node, sourceFile, this.newLineCharacter); - if (this.validator) { - this.validator(nonformattedText); - } - var formatOptions = this.formatContext.options; - var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - var initialIndentation = options.indentation !== undefined - ? options.indentation - : (options.useIndentationFromFile !== false) - ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter)) - : 0; - var delta = options.delta !== undefined - ? options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(node) - ? (formatOptions.indentSize || 0) - : 0; - 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); - } - return normalized; + return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); }; return ChangeTracker; }()); textChanges_1.ChangeTracker = ChangeTracker; - function getNonformattedText(node, sourceFile, newLine) { - var writer = new Writer(newLine); - var printer = ts.createPrinter({ newLine: newLine === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */ }, writer); - printer.writeNode(4 /* Unspecified */, node, sourceFile, writer); - return { text: writer.getText(), node: assignPositionsToNode(node) }; - } - 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, formatContext); - return applyChanges(nonFormattedText.text, changes); - } + var changesToText; + (function (changesToText) { + function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { + return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + var sourceFile = changesInFile[0].sourceFile; + // order changes by start position + var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); + var _loop_11 = function (i) { + ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { + return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + }); + }; + // verify that change intervals do not overlap, except possibly at end points. + for (var i = 0; i < normalized.length - 1; i++) { + _loop_11(i); + } + var textChanges = normalized.map(function (c) { + return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + }); + return { fileName: sourceFile.fileName, textChanges: textChanges }; + }); + } + changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + if (change.kind === ChangeKind.Remove) { + return ""; + } + if (change.kind === ChangeKind.Text) { + return change.text; + } + var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; + var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; + var text = change.kind === ChangeKind.ReplaceWithMultipleNodes + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter) + : format(change.node); + // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line + var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + return (options.prefix || "") + noIndent + (options.suffix || ""); + } + /** Note: this may mutate `nodeIn`. */ + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; + if (validate) + validate(node, text); + var formatOptions = formatContext.options; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn) ? (formatOptions.indentSize || 0) : 0; + } + var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; + var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); + return applyChanges(text, changes); + } + /** Note: output node may be mutated input node. */ + function getNonformattedText(node, sourceFile, newLineCharacter) { + var writer = new Writer(newLineCharacter); + var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + return { text: writer.getText(), node: assignPositionsToNode(node) }; + } + })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; @@ -93950,7 +95198,7 @@ var ts; 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])) { + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { position = ranges[0].end; advancePastLineBreak(); ranges = ranges.slice(1); @@ -93978,6 +95226,10 @@ var ts; } } } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + } + textChanges_1.isValidLocationToAddComment = isValidLocationToAddComment; })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -93987,6 +95239,22 @@ var ts; (function (codefix) { var codeFixRegistrations = []; var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(changes, description) { + return createCodeFixActionWorker(diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(description, changes, fixId, fixAllDescription, command) { + return { description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } function registerCodeFix(reg) { for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { var error = _a[_i]; @@ -94050,16 +95318,9 @@ var ts; return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; - function codeFixAllWithTextChanges(context, errorCodes, use) { - var changes = []; - eachDiagnostic(context, errorCodes, function (diag) { return use(changes, diag); }); - changes.sort(function (a, b) { return b.span.start - a.span.start; }); - return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); - } - codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges; function eachDiagnostic(_a, errorCodes, cb) { var program = _a.program, sourceFile = _a.sourceFile; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) { + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) { var diag = _b[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); @@ -94109,7 +95370,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, @@ -94125,6 +95386,797 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "annotateWithTypeFromJSDoc"; + var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var decl = getDeclaration(diag.file, diag.start); + if (decl) + doChange(changes, diag.file, decl); + }); }, + }); + function getDeclaration(file, pos) { + var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false); + // For an arrow function with no name, 'name' lands on the first parameter. + return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc; + function hasUsableJSDoc(decl) { + return ts.isFunctionLikeDeclaration(decl) + ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)) + : !decl.type && !!ts.getJSDocType(decl); + } + function doChange(changes, sourceFile, decl) { + if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { + if (!decl.typeParameters) { + var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); + if (typeParameters) + changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19 /* OpenParenToken */)); + for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (!param.type) { + var paramType = ts.getJSDocType(param); + if (paramType) + changes.insertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20 /* CloseParenToken */)); + if (!decl.type) { + var returnType = ts.getJSDocReturnType(decl); + if (returnType) + changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + } + } + else { + var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix + ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. + changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + } + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 230 /* VariableDeclaration */ || + node.kind === 150 /* PropertySignature */ || + node.kind === 151 /* PropertyDeclaration */; + } + function transformJSDocType(node) { + switch (node.kind) { + case 275 /* JSDocAllType */: + case 276 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 279 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 278 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 277 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 281 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 280 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 161 /* 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) { + return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 281 /* 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 === 134 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* 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; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertFunctionToEs6Class"; + var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, + }); + function doChange(changes, sourceFile, position, checker) { + var deletedNodes = []; + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false)); + if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + // Bad input + return undefined; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 232 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 230 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return undefined; + } + copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); + for (var _i = 0, deletedNodes_1 = deletedNodes; _i < deletedNodes_1.length; _i++) { + var _a = deletedNodes_1[_i], node = _a.node, inList = _a.inList; + if (inList) { + changes.deleteNodeInList(sourceFile, node); + } + else { + changes.deleteNode(sourceFile, node); + } + } + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + // If parent node has already been deleted, do nothing + if (!deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n.node); })) { + deletedNodes.push({ node: node, inList: inList }); + } + } + 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, /*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 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + 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) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + 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 === 214 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 190 /* FunctionExpression */: { + var functionExpression = assignmentBinaryExpression.right; + 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, sourceFile); + return method; + } + case 191 /* ArrowFunction */: { + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 211 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + } + 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, sourceFile); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + return prop; + } + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 190 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + 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(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + 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 copyComments(sourceNode, targetNode, sourceFile) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + 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); + }); + } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, sourceFile, changes); + } + } + }); + // No support for fix-all since this applies to the whole file at once anyway. + return [codefix.createCodeFixActionNoFixId(changes, ts.Diagnostics.Convert_to_ES6_module)]; + }, + }); + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 241 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + break; + case 185 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); + } + break; + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 212 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 214 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 185 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + } + return false; + } + case 198 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 178 /* ObjectBindingPattern */: + case 179 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 269 /* ShorthandPropertyAssignment */: + case 270 /* SpreadAssignment */: + return undefined; + case 268 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); + case 153 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right)); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 190 /* FunctionExpression */: + case 191 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 203 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 185 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 190 /* FunctionExpression */: { + var expressionName = exported.name; + if (expressionName && expressionName.text !== name) { + // `exports.f = function g() {}` -> `export const f = function g() {}` + return exportConst(); + } + } + // falls through + case 191 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 203 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + return exportConst(); + } + function exportConst() { + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 178 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 179 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 183 /* PropertyAccessExpression */: + return parent.name !== node; + case 180 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + return makeImportDeclaration(name, namedImports, moduleSpecifier); + } + function makeImportDeclaration(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier); + } + codefix.makeImportDeclaration = makeImportDeclaration; + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -94137,8 +96189,8 @@ var ts; if (!qualifiedName) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); - return [{ description: description, changes: changes, fixId: fixId }]; + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -94175,11 +96227,8 @@ var ts; var classDeclaration = getClass(sourceFile, span.start); var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - return { description: description, changes: changes, fixId: fixId }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, fixIds: [fixId], @@ -94190,31 +96239,29 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); }, }); function getClass(sourceFile, pos) { - var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)); - ts.Debug.assert(!!classDeclaration); - return classDeclaration; + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false))); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { // 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 /* Private */); }); var classType = checker.getTypeAtLocation(classDeclaration); - if (!checker.getIndexTypeOfType(classType, 1 /* Number */)) { + if (!classType.getNumberIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } - if (!checker.getIndexTypeOfType(classType, 0 /* String */)) { + if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { @@ -94241,7 +96288,7 @@ var ts; if (!info) return undefined; var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs ? ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); @@ -94251,7 +96298,7 @@ var ts; getAllCodeActions: function (context) { var seenNames = ts.createMap(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var program = context.program; + var program = context.program, preferences = context.preferences; var info = getInfo(diag.file, diag.start, program.getTypeChecker()); if (!info) return; @@ -94261,7 +96308,7 @@ var ts; } // Always prefer to add a method declaration if possible. if (call) { - addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, preferences); } else { if (inJs) { @@ -94320,10 +96367,8 @@ var ts; } function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); - return { description: description, changes: changes, fixId: fixId }; + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { @@ -94362,9 +96407,8 @@ var ts; return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); - return { description: description, changes: changes, fixId: fixId }; + return codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( @@ -94388,15 +96432,14 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); - return { description: description, changes: changes, fixId: fixId }; + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic, preferences); changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -94420,8 +96463,7 @@ var ts; return undefined; var node = info.node, suggestion = info.suggestion; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); - return [{ description: description, changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -94458,10 +96500,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 793064 /* Type */; + flags |= 67901928 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 107455 /* Value */; + flags |= 67216319 /* Value */; } return flags; } @@ -94477,37 +96519,27 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); - return codeAction && [__assign({ fixId: fixId }, codeAction)]; + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = getTypesPackageNameToInstall(host, sourceFile, start); + return packageName === undefined ? [] + : [codefix.createCodeFixAction(/*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start); if (pkg) { commands.push(getCommand(diag.file.fileName, pkg)); } }); }, }); - function getModuleName(sourceFile, pos) { - return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; - } function getCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, moduleName) { + function getTypesPackageNameToInstall(host, sourceFile, pos) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; var packageName = ts.getPackageName(moduleName).packageName; - // If !registry, registry not available yet, can't do anything. return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; } - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { - var packageName = getTypesPackageNameToInstall(host, moduleName); - return packageName === undefined ? undefined : { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), - changes: [], - commands: [getCommand(fileName, packageName)], - }; - } - codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -94525,30 +96557,34 @@ var ts; getCodeActions: function (context) { var program = context.program, sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); }); - return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes); - }); }, + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + } + }); + }, }); function getClass(sourceFile, pos) { - // This is the identifier in the case of a class declaration + // Token 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, pos, /*includeJsDocComment*/ false); - var classDeclaration = token.parent; - ts.Debug.assert(ts.isClassLike(classDeclaration)); - return classDeclaration; + return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { 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 abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -94574,7 +96610,7 @@ var ts; return undefined; var constructor = nodes.constructor, superCall = nodes.superCall; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -94627,7 +96663,7 @@ var ts; var sourceFile = context.sourceFile, span = context.span; var ctr = getNode(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -94661,7 +96697,7 @@ var ts; return undefined; var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -94677,7 +96713,7 @@ var ts; return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && heritageClauses[0].token === 85 /* ExtendsKeyword */ && @@ -94713,7 +96749,7 @@ var ts; return undefined; } var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_this_to_unresolved_variable, fixId, ts.Diagnostics.Add_this_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -94730,7 +96766,7 @@ var ts; } // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper ts.suppressLeadingAndTrailingTrivia(token); - changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -94744,29 +96780,33 @@ var ts; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = getToken(sourceFile, context.span.start); + var errorCode = context.errorCode, sourceFile = context.sourceFile; + var importDecl = tryGetFullImport(sourceFile, context.span.start); + if (importDecl) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } + var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); if (deletion.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); - result.push({ description: description, changes: deletion, fixId: fixIdDelete }); + result.push(codefix.createCodeFixAction(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } - var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, context.errorCode, sourceFile, token); }); + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); - result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + result.push(codefix.createCodeFixAction(prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); } return result; }, fixIds: [fixIdPrefix, fixIdDelete], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var sourceFile = context.sourceFile; - var token = getToken(diag.file, diag.start); + var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); switch (context.fixId) { case fixIdPrefix: if (ts.isIdentifier(token) && canPrefix(token)) { @@ -94774,17 +96814,28 @@ var ts; } break; case fixIdDelete: - tryDeleteDeclaration(changes, sourceFile, token); + var importDecl = tryGetFullImport(diag.file, diag.start); + if (importDecl) { + changes.deleteNode(sourceFile, importDecl); + } + else { + tryDeleteDeclaration(changes, sourceFile, token); + } break; default: ts.Debug.fail(JSON.stringify(context.fixId)); } }); }, }); + // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. + function tryGetFullImport(sourceFile, pos) { + var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; + } function getToken(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.findPrecedingToken(pos, sourceFile); // this handles var ["computed"] = 12; - return token.kind === 21 /* OpenBracketToken */ ? ts.getTokenAtPosition(sourceFile, pos + 1, /*includeJsDocComment*/ false) : token; + return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. @@ -94849,6 +96900,10 @@ var ts; break; case 148 /* Parameter */: var oldFunction = parent.parent; + if (ts.isSetAccessor(oldFunction)) { + // Setter must have a parameter + break; + } if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the @@ -94859,7 +96914,7 @@ var ts; // to replace the span (vs the full span) of the old function - the old leading // and trailing trivia will remain. ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction, ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, oldFunction, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); @@ -94880,9 +96935,9 @@ var ts; changes.deleteNodeInList(sourceFile, parent); } break; - case 243 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + case 243 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *' var importClause = parent; - if (!importClause.namedBindings) { + if (!importClause.namedBindings) { // |import d from './file'| changes.deleteNode(sourceFile, ts.getAncestor(importClause, 242 /* ImportDeclaration */)); } else { @@ -94978,47 +97033,40 @@ var ts; return undefined; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); - var actions = [fix(type, fixIdPlain)]; + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; if (typeNode.kind === 277 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable)); + actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; - function fix(type, fixId) { - var newText = typeString(type, checker); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], - fixId: fixId, - }; + function fix(type, fixId, fixAllDescription) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], getAllCodeActions: function (context) { var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; var checker = program.getTypeChecker(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + return codefix.codeFixAll(context, errorCodes, function (changes, err) { var info = getInfo(err.file, err.start, checker); if (!info) return; var typeNode = info.typeNode, type = info.type; var fixedType = typeNode.kind === 277 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; - changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + doChange(changes, sourceFile, typeNode, fixedType, checker); }); } }); + function doChange(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); + } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); var typeNode = decl && decl.type; return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; } - function createChange(declaration, sourceFile, newText) { - return ts.createTextChange(ts.createTextSpanFromNode(declaration, sourceFile), newText); - } - function typeString(type, checker) { - return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); - } function isTypeContainer(node) { // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments @@ -95064,7 +97112,7 @@ var ts; if (!nodes) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -95087,6 +97135,9 @@ var ts; function getNodes(sourceFile, start) { var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } var insertBefore; switch (containingFunction.kind) { case 153 /* MethodDeclaration */: @@ -95138,9 +97189,8 @@ var ts; getAllCodeActions: ts.notImplemented, }); function createCodeAction(descriptionDiagnostic, diagnosticArgs, changes) { - var description = ts.formatMessage.apply(undefined, [undefined, descriptionDiagnostic].concat(diagnosticArgs)); // TODO: GH#20315 - return { description: description, changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(changes, [descriptionDiagnostic].concat(diagnosticArgs)); } function convertToImportCodeFixContext(context, symbolToken, symbolName) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; @@ -95156,7 +97206,8 @@ var ts; cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolName, - symbolToken: symbolToken + symbolToken: symbolToken, + preferences: context.preferences, }; } var ImportKind; @@ -95166,12 +97217,12 @@ var ts; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken) { + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken, preferences) { var exportInfos = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host)).moduleSpecifier; - var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken }; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } codefix.getImportCompletionAction = getImportCompletionAction; @@ -95233,34 +97284,20 @@ var ts; var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); var cached = cachedImportDeclarations[moduleSymbolId]; if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { - var declaration = checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; - return declaration && { declaration: declaration, importKind: importKind }; + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 242 /* ImportDeclaration */ || i.kind === 241 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } return cached; } - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 242 /* ImportDeclaration */: - return parent; - case 252 /* ExternalModuleReference */: - return parent.parent; - case 248 /* ExportDeclaration */: - case 185 /* CallExpression */:// For "require()" calls - // Ignore these, can't add imports to them. - return undefined; - default: - ts.Debug.fail(); - } - } function getCodeActionForNewImport(context, _a) { var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; - var sourceFile = context.sourceFile, symbolName = context.symbolName; + var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); + var quotedModuleSpecifier = ts.createLiteral(moduleSpecifierWithoutQuotes, shouldUseSingleQuote(sourceFile, preferences)); var importDecl = importKind !== 3 /* Equals */ ? ts.createImportDeclaration( /*decorators*/ undefined, @@ -95281,11 +97318,14 @@ var ts; // are there are already a new line seperating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } - 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 shouldUseSingleQuote(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single"; + } + else { + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + } } function usesJsExtensionOnImports(sourceFile) { return ts.firstDefined(sourceFile.imports, function (_a) { @@ -95306,35 +97346,40 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { - var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; + function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var addJsExtension = usesJsExtensionOnImports(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); if (global) { return [global]; } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); - if (!baseUrl) { + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), compilerOptions, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { return [relativePath]; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { return [relativePath]; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, compilerOptions, addJsExtension); if (paths) { var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); if (fromPaths) { return [fromPaths]; } } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); if (isPathRelativeToParent(relativeToBaseUrl)) { return [relativePath]; } @@ -95588,7 +97633,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); return newImportInfos.map(function (info) { return getCodeActionForNewImport(ctx, info); }); } function newImportInfoFromExistingSpecifier(_a) { @@ -95667,7 +97712,7 @@ var ts; var parent = token.parent; var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent); if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258 /* JsxOpeningFragment */) { - umdSymbol = checker.resolveName(checker.getJsxNamespace(), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false); + umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false); } } if (ts.isUMDExportSymbol(umdSymbol)) { @@ -95697,7 +97742,7 @@ var ts; // Fall back to the `import * as ns` style import. return 2 /* Namespace */; default: - throw ts.Debug.assertNever(moduleKind); + return ts.Debug.assertNever(moduleKind); } } function getActionsForNonUMDImport(context) { @@ -95705,13 +97750,14 @@ var ts; var sourceFile = context.sourceFile, span = context.span, program = context.program, cancellationToken = context.cancellationToken; var checker = program.getTypeChecker(); var symbolToken = ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false); - var isJsxNamespace = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken; - if (!isJsxNamespace && !ts.isIdentifier(symbolToken)) { + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; + if (!symbolName) return undefined; - } - var symbolName = isJsxNamespace ? checker.getJsxNamespace() : symbolToken.text; - var allSourceFiles = program.getSourceFiles(); - var compilerOptions = program.getCompilerOptions(); // "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 currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); @@ -95721,7 +97767,7 @@ var ts; function addSymbol(moduleSymbol, exportedSymbol, importKind) { originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); } - forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); // check the default export var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); @@ -95729,7 +97775,7 @@ var ts; var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if ((localSymbol && localSymbol.escapedName === symbolName || getEscapedNameForExportDefault(defaultExport) === symbolName || - moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { addSymbol(moduleSymbol, localSymbol || defaultExport, 1 /* Default */); } } @@ -95790,21 +97836,22 @@ var ts; return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { - return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); } codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); var res = ""; var lastCharWasValid = true; - var firstCharCode = moduleSpecifier.charCodeAt(0); + var firstCharCode = baseName.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); + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); var isValid = ts.isIdentifierPart(ch, target); if (isValid) { var char = String.fromCharCode(ch); @@ -95834,55 +97881,39 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, span = context.span; + var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } - var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter).change])], - fixId: fixId, - }, - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [ - ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), - ])], - // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - fixId: undefined, - }]; + var fixes = [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId([codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), + ]; + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); + } + return fixes; }, fixIds: [fixId], getAllCodeActions: function (context) { - var seenLines = ts.createMap(); // Only need to add `// @ts-ignore` for a line once. - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { - if (err.start !== undefined) { - var _a = getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options)), lineNumber = _a.lineNumber, change = _a.change; - if (ts.addToSeen(seenLines, lineNumber)) { - changes.push(change); - } + var seenLines = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { + makeChange(changes, diag.file, diag.start, seenLines); } }); }, }); - function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) { + function makeChange(changes, sourceFile, position, seenLines) { var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; - var lineStartPosition = ts.getStartPositionOfLine(lineNumber, 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, /*includeJsDocComment*/ false); - var tokenLeadingComments = ts.getLeadingCommentRangesOfNode(token, sourceFile); - if (!tokenLeadingComments || !tokenLeadingComments.length || tokenLeadingComments[0].pos >= startPosition) { - return { lineNumber: lineNumber, change: ts.createTextChangeFromStartLength(startPosition, 0, "// @ts-ignore" + newLineCharacter) }; - } + // Only need to add `// @ts-ignore` for a line once. + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } - // If all fails, add an extra new line immediately before the error span. - return { lineNumber: lineNumber, change: ts.createTextChangeFromStartLength(position, 0, (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter) }; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -95897,12 +97928,12 @@ var ts; * @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, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); } } } @@ -95910,7 +97941,7 @@ var ts; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -95948,7 +97979,7 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { @@ -95958,11 +97989,11 @@ var ts; } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); } else { ts.Debug.assert(declarations.length === signatures.length); - out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); } break; } @@ -95987,7 +98018,7 @@ var ts; function getSynthesizedDeepClones(nodes) { return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); } - function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { + function createMethodFromCallExpression(_a, methodName, inJs, makeStatic, preferences) { var typeArguments = _a.typeArguments, args = _a.arguments; return ts.createMethod( /*decorators*/ undefined, @@ -95998,7 +98029,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody()); + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, minArgumentCount, inJs) { @@ -96016,7 +98047,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers) { + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { /** 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. @@ -96048,16 +98079,16 @@ var ts; } return createStubbedMethod(modifiers, name, optional, /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined); + /*returnType*/ undefined, preferences); } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } - function createStubbedMethodBody() { + function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), - /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], /*multiline*/ true); } function createVisibilityModifier(flags) { @@ -96095,28 +98126,23 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (_a) { - var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; if (ts.isSourceFileJavaScript(sourceFile)) { return undefined; // TODO: GH#20113 } var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var fix = getFix(sourceFile, token, errorCode, program, cancellationToken); - if (!fix) - return undefined; - var declaration = fix.declaration, textChanges = fix.textChanges; - var name = ts.getNameOfDeclaration(declaration); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); - return [{ description: description, changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }], fixId: fixId }]; + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); + return changes.length === 0 ? undefined + : [codefix.createCodeFixAction(changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; var seenFunctions = ts.createMap(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { - var fix = getFix(sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); - if (fix) - changes.push.apply(changes, fix.textChanges); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); }); }, }); @@ -96130,18 +98156,26 @@ var ts; return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function getFix(sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { - if (!isAllowedTokenKind(token.kind)) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { return undefined; } + var parent = token.parent; 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, program, cancellationToken); + if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + return parent; + } + return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, program, cancellationToken); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + return symbol.valueDeclaration; + } } } var containingFunction = ts.getContainingFunction(token); @@ -96152,43 +98186,41 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction, program, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return !seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction)) - ? getCodeActionForParameters(ts.cast(token.parent, ts.isParameter), containingFunction, sourceFile, program, cancellationToken) - : undefined; + if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + return param; + } + return undefined; // 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, sourceFile, program, cancellationToken) : undefined; + if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + return containingFunction; + } + return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, program, cancellationToken) : undefined; + if (ts.isSetAccessor(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + return containingFunction; + } + return undefined; default: - throw ts.Debug.fail(String(errorCode)); + return ts.Debug.fail(String(errorCode)); } } - function isAllowedTokenKind(kind) { - switch (kind) { - case 71 /* Identifier */: - case 24 /* DotDotDotToken */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; + function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); } } - function getCodeActionForVariableDeclaration(declaration, program, cancellationToken) { - if (!ts.isIdentifier(declaration.name)) - return undefined; - var type = inferTypeForVariableFromUsage(declaration.name, program, cancellationToken); - return makeFix(declaration, declaration.name.getEnd(), type, program); - } function isApplicableFunctionForInference(declaration) { switch (declaration.kind) { case 232 /* FunctionDeclaration */: @@ -96200,47 +98232,47 @@ var ts; } return false; } - function getCodeActionForParameters(parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; + return; } var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - if (!types) - return undefined; // We didn't actually find a set of type inference positions matching each parameter position - if (containingFunction.parameters.length !== types.length) { - return undefined; + if (!types || containingFunction.parameters.length !== types.length) { + return; } - var textChanges = ts.arrayFrom(ts.mapDefinedIterator(ts.zipToIterator(containingFunction.parameters, types), function (_a) { - var parameter = _a[0], type = _a[1]; - return type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined; - })); - return textChanges.length ? { declaration: parameterDeclaration, textChanges: textChanges } : undefined; + ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (!parameter.type && !parameter.initializer) { + annotate(changes, sourceFile, parameter, type, program); + } + }); } - function getCodeActionForSetAccessor(setAccessorDeclaration, program, cancellationToken) { - var setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { - return undefined; + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || + inferTypeForVariableFromUsage(param.name, program, cancellationToken); + annotate(changes, sourceFile, param, type, program); } - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(setAccessorParameter.name, program, cancellationToken); - return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); } - function getCodeActionForGetAccessor(getAccessorDeclaration, sourceFile, program, cancellationToken) { - if (!ts.isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, program, cancellationToken); - var closeParenToken = ts.findChildOfKind(getAccessorDeclaration, 20 /* CloseParenToken */, sourceFile); - return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + function annotate(changes, sourceFile, declaration, type, program) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); + if (typeNode) + changes.insertTypeAnnotation(sourceFile, declaration, typeNode); } - function makeFix(declaration, start, type, program) { - return type && { declaration: declaration, textChanges: [makeChange(declaration, start, type, program)] }; - } - function makeChange(declaration, start, type, program) { - var typeString = type && typeToString(type, declaration, program.getTypeChecker()); - return typeString === undefined ? undefined : ts.createTextChangeFromStartLength(start, 0, ": " + typeString); + function getTypeNodeIfAccessible(type, enclosingScope, checker) { + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + }); + return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. @@ -96266,48 +98298,6 @@ var ts; } } } - function getTypeAccessiblityWriter(checker) { - var str = ""; - var typeIsAccessible = true; - var writeText = function (text) { return str += text; }; - return { - getText: function () { return typeIsAccessible ? str : undefined; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - write: writeText, - writeTextOfNode: writeText, - rawWrite: writeText, - writeLiteral: writeText, - getTextPos: function () { return 0; }, - getLine: function () { return 0; }, - getColumn: function () { return 0; }, - getIndent: function () { return 0; }, - isAtStartOfLine: function () { return false; }, - writeLine: function () { return writeText(" "); }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { str = ""; typeIsAccessible = true; }, - trackSymbol: function (symbol, declaration, meaning) { - if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { - typeIsAccessible = false; - } - }, - reportInaccessibleThisError: function () { typeIsAccessible = false; }, - reportPrivateInBaseOfClassExpression: function () { typeIsAccessible = false; }, - reportInaccessibleUniqueSymbolError: function () { typeIsAccessible = false; } - }; - } - function typeToString(type, enclosingDeclaration, checker) { - var writer = getTypeAccessiblityWriter(checker); - checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); - return writer.getText(); - } var InferFromReference; (function (InferFromReference) { function inferTypeFromReferences(references, checker, cancellationToken) { @@ -96337,13 +98327,13 @@ var ts; var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; - var isRestParameter = ts.isRestParameter(parameter); + var isRest = ts.isRestParameter(parameter); for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { continue; } - if (isRestParameter) { + if (isRest) { for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); } @@ -96356,7 +98346,7 @@ var ts; return undefined; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRestParameter ? checker.createArrayType(type) : type; + return isRest ? checker.createArrayType(type) : type; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -96413,6 +98403,8 @@ var ts; case 37 /* PlusToken */: usageContext.isNumberOrString = true; break; + // case SyntaxKind.ExclamationToken: + // no inferences here; } } function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { @@ -96678,9 +98670,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -96690,12 +98680,8 @@ var ts; return variations; } function createAction(context, sourceFile, node, replacement) { - // TODO: GH#21246 Should be able to use `replaceNode`, but be sure to preserve comments (see `codeFixCalledES2015Import11.ts`) - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceRange(sourceFile, { pos: node.getStart(), end: node.end }, replacement); }); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), - changes: changes, - }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -96721,15 +98707,171 @@ var ts; if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } - fixes.push({ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), - changes: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }), - }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(changes, ts.Diagnostics.Use_synthetic_default_member)); return fixes; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + var fixIdAddInitializer = "addMissingPropertyInitializer"; + var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); + if (!propertyDeclaration) + return; + var result = [ + getActionForAddMissingUndefinedType(context, propertyDeclaration), + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) + ]; + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + return result; + }, + fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); + if (!propertyDeclaration) + return; + switch (context.fixId) { + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag.file, propertyDeclaration); + break; + case fixIdAddInitializer: + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return; + addInitializer(changes, diag.file, propertyDeclaration, initializer); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function getPropertyDeclaration(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + } + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types)); + } + function getActionForAddMissingInitializer(context, propertyDeclaration) { + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 2 /* String */) { + return ts.createLiteral(""); + } + else if (type.flags & 4 /* Number */) { + return ts.createNumericLiteral("0"); + } + else if (type.flags & 8 /* Boolean */) { + return ts.createFalse(); + } + else if (type.flags & 224 /* Literal */) { + return ts.createLiteral(type.value); + } + else if (type.flags & 131072 /* Union */) { + return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); + } + else if (ts.getObjectFlags(type) & 1 /* Class */) { + var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) + return undefined; + var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; }); + if (constructorDeclaration && constructorDeclaration.parameters.length) + return undefined; + return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "useDefaultImport"; + var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var info = getInfo(sourceFile, start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); }, + }); + function getInfo(sourceFile, pos) { + var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + if (!ts.isIdentifier(name)) + return undefined; // bad input + var parent = name.parent; + if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) { + return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression }; + } + else if (ts.isNamespaceImport(parent)) { + var importNode = parent.parent.parent; + return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; + } + } + function doChange(changes, sourceFile, info) { + changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// +/// +/// +/// /// /// /// @@ -96748,960 +98890,8 @@ var ts; /// /// /// -/* @internal */ -var ts; -(function (ts) { - var refactor; - (function (refactor) { - var annotateWithTypeFromJSDoc; - (function (annotateWithTypeFromJSDoc) { - var refactorName = "Annotate with type from JSDoc"; - var actionName = "annotate"; - var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (ts.isInJavaScriptFile(context.file)) { - return undefined; - } - var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); - if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { - return [{ - name: refactorName, - description: description, - actions: [ - { - description: 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 === 148 /* 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.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions); - 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.replaceNode(sourceFile, decl, functionWithType, ts.textChanges.useNonAdjustedPositions); - return { - edits: changeTracker.getChanges(), - renameFilename: undefined, - renameLocation: undefined - }; - } - function isDeclarationWithType(node) { - return ts.isFunctionLikeDeclaration(node) || - node.kind === 230 /* VariableDeclaration */ || - node.kind === 148 /* Parameter */ || - node.kind === 150 /* PropertySignature */ || - node.kind === 151 /* 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 232 /* FunctionDeclaration */: - return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); - case 154 /* Constructor */: - return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); - case 190 /* FunctionExpression */: - return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); - case 191 /* ArrowFunction */: - return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); - case 153 /* MethodDeclaration */: - return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body); - case 155 /* GetAccessor */: - return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body); - case 156 /* 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 230 /* VariableDeclaration */: - return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer); - case 150 /* PropertySignature */: - return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); - case 151 /* 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 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: - return ts.createTypeReferenceNode("any", ts.emptyArray); - case 279 /* JSDocOptionalType */: - return transformJSDocOptionalType(node); - case 278 /* JSDocNonNullableType */: - return transformJSDocType(node.type); - case 277 /* JSDocNullableType */: - return transformJSDocNullableType(node); - case 281 /* JSDocVariadicType */: - return transformJSDocVariadicType(node); - case 280 /* JSDocFunctionType */: - return transformJSDocFunctionType(node); - case 148 /* Parameter */: - return transformJSDocParameter(node); - case 161 /* 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 === 281 /* 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 === 134 /* NumberKeyword */ ? "n" : "s", - /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* 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; - (function (refactor) { - var convertFunctionToES6Class; - (function (convertFunctionToES6Class) { - var refactorName = "Convert to ES2015 class"; - var actionName = "convert"; - var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (!ts.isInJavaScriptFile(context.file)) { - return undefined; - } - var symbol = getConstructorSymbol(context); - if (!symbol) { - return undefined; - } - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = symbol.valueDeclaration.initializer.symbol; - } - if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { - return [ - { - name: refactorName, - description: description, - actions: [ - { - description: description, - name: actionName - } - ] - } - ]; - } - } - function getEditsForAction(context, action) { - // Somehow wrong action got invoked? - if (actionName !== action) { - return undefined; - } - var sourceFile = context.file; - var ctorSymbol = getConstructorSymbol(context); - var deletedNodes = []; - var deletes = []; - if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { - return undefined; - } - var ctorDeclaration = ctorSymbol.valueDeclaration; - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var precedingNode; - var newClassDeclaration; - switch (ctorDeclaration.kind) { - case 232 /* FunctionDeclaration */: - precedingNode = ctorDeclaration; - deleteNode(ctorDeclaration); - newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); - break; - case 230 /* VariableDeclaration */: - precedingNode = ctorDeclaration.parent.parent; - if (ctorDeclaration.parent.declarations.length === 1) { - deleteNode(precedingNode); - } - else { - deleteNode(ctorDeclaration, /*inList*/ true); - } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - break; - } - if (!newClassDeclaration) { - return undefined; - } - // Because the preceding node could be touched, we need to insert nodes before delete nodes. - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); - for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { - var deleteCallback = deletes_1[_i]; - deleteCallback(); - } - return { - edits: changeTracker.getChanges(), - renameFilename: undefined, - renameLocation: undefined, - }; - 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); - if (inList) { - deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); - } - else { - deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); - } - } - 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, /*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 /* StaticKeyword */)]); - if (memberElement) { - memberElements.push(memberElement); - } - }); - } - 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) { - // both properties and methods are bound as property symbols - if (!(symbol.flags & 4 /* Property */)) { - return; - } - var memberDeclaration = symbol.valueDeclaration; - var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - 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 === 214 /* ExpressionStatement */ - ? assignmentBinaryExpression.parent : assignmentBinaryExpression; - deleteNode(nodeToDelete); - if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, - /*type*/ undefined, /*initializer*/ undefined); - } - switch (assignmentBinaryExpression.right.kind) { - case 190 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - 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 191 /* ArrowFunction */: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 211 /* Block */) { - bodyBlock = arrowFunctionBody; - } - else { - bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); - } - 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(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop); - return prop; - } - } - } - } - function copyComments(sourceNode, targetNode) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - 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); - }); - } - function createClassFromVariableDeclaration(node) { - var initializer = node.initializer; - if (!initializer || initializer.kind !== 190 /* FunctionExpression */) { - return undefined; - } - if (node.name.kind !== 71 /* Identifier */) { - return undefined; - } - var memberElements = createClassElementsFromSymbol(initializer.symbol); - if (initializer.body) { - memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); - } - 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(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); - } - 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 actionName = "Convert to ES6 module"; - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); - refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition; - if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { - return undefined; - } - var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); - return !isAtTriggerLocation(file, node) ? undefined : [ - { - name: actionName, - description: description, - actions: [ - { - description: description, - name: actionName, - }, - ], - }, - ]; - } - function isAtTriggerLocation(sourceFile, node, onSecondTry) { - if (onSecondTry === void 0) { onSecondTry = false; } - switch (node.kind) { - case 185 /* CallExpression */: - return isAtTopLevelRequire(node); - case 183 /* PropertyAccessExpression */: - return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) - || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); - case 231 /* VariableDeclarationList */: - return isVariableDeclarationTriggerLocation(ts.firstOrUndefined(node.declarations)); - case 230 /* VariableDeclaration */: - return isVariableDeclarationTriggerLocation(node); - default: - return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) - || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); - } - function isVariableDeclarationTriggerLocation(decl) { - return !!decl && !!decl.initializer && ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); - } - } - function isAtTopLevelRequire(call) { - if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { - return false; - } - var propAccess = call.parent; - var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; - if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { - return true; - } - if (!ts.isVariableDeclaration(varDecl)) { - return false; - } - var varDeclList = varDecl.parent; - if (varDeclList.kind !== 231 /* VariableDeclarationList */) { - return false; - } - var varStatement = varDeclList.parent; - return varStatement.kind === 212 /* VariableStatement */ && varStatement.parent.kind === 272 /* SourceFile */; - } - function getEditsForAction(context, _actionName) { - ts.Debug.assertEqual(actionName, _actionName); - var file = context.file, program = context.program; - ts.Debug.assert(ts.isSourceFileJavaScript(file)); - var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); - if (moduleExportsChangedToDefault) { - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, file, changes); - } - } - }); - return { edits: edits, renameFilename: undefined, renameLocation: undefined }; - } - function fixImportOfModuleExports(importingFile, exportingFile, changes) { - for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); - if (!imported || imported.resolvedFileName !== exportingFile.fileName) { - continue; - } - var parent = moduleSpecifier.parent; - switch (parent.kind) { - case 252 /* ExternalModuleReference */: { - var importEq = parent.parent; - changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); - break; - } - case 185 /* CallExpression */: { - var call = parent; - if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { - changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); - } - break; - } - } - } - } - /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { - var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; - var exports = collectExportRenames(sourceFile, checker, identifiers); - convertExportsAccesses(sourceFile, exports, changes); - var moduleExportsChangedToDefault = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); - moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; - } - return moduleExportsChangedToDefault; - } - function collectExportRenames(sourceFile, checker, identifiers) { - var res = ts.createMap(); - forEachExportReference(sourceFile, function (node) { - var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; - if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { - // Unconditionally add an underscore in case `text` is a keyword. - res.set(text, makeUniqueName("_" + text, identifiers)); - } - }); - return res; - } - function convertExportsAccesses(sourceFile, exports, changes) { - forEachExportReference(sourceFile, function (node, isAssignmentLhs) { - if (isAssignmentLhs) { - return; - } - var text = node.name.text; - changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); - }); - } - function forEachExportReference(sourceFile, cb) { - sourceFile.forEachChild(function recur(node) { - if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { - var parent = node.parent; - cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); - } - node.forEachChild(recur); - }); - } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { - switch (statement.kind) { - case 212 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); - return false; - case 214 /* ExpressionStatement */: { - var expression = statement.expression; - switch (expression.kind) { - case 185 /* CallExpression */: { - if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { - // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); - } - return false; - } - case 198 /* BinaryExpression */: { - var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); - } - } - } - // falls through - default: - return false; - } - } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { - var declarationList = statement.declarationList; - var foundImport = false; - var newNodes = ts.flatMap(declarationList.declarations, function (decl) { - var name = decl.name, initializer = decl.initializer; - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { - // `const alias = module.exports;` can be removed. - foundImport = true; - return []; - } - if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); - } - else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); - } - else { - // Move it out to its own variable statement. - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); - } - }); - if (foundImport) { - // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - } - } - /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { - switch (name.kind) { - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: { - // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` - var tmp = makeUniqueName(propertyName, identifiers); - return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), - makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), - ]; - } - case 71 /* Identifier */: - // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; - default: - ts.Debug.assertNever(name); - } - } - function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { - if (!ts.isPropertyAccessExpression(left)) { - return false; - } - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { - // `const alias = module.exports;` or `module.exports = alias;` can be removed. - changes.deleteNode(sourceFile, statement); - } - else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); - } - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - return changedToDefaultExport; - } - } - else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { - convertNamedExport(sourceFile, statement, left.name, right, changes, exports); - } - return false; - var _a; - } - /** - * Convert `module.exports = { ... }` to individual exports.. - * We can't always do this if the module has interesting members -- then it will be a default export instead. - */ - function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { - switch (prop.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 269 /* ShorthandPropertyAssignment */: - case 270 /* SpreadAssignment */: - return undefined; - case 268 /* PropertyAssignment */: - return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); - case 153 /* MethodDeclaration */: - return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); - default: - ts.Debug.assertNever(prop); - } - }); - } - function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { - // If "originalKeywordKind" was set, this is e.g. `exports. - var text = propertyName.text; - var rename = exports.get(text); - if (rename !== undefined) { - /* - const _class = 0; - export { _class as class }; - */ - var newNodes = [ - makeConst(/*modifiers*/ undefined, rename, right), - makeExportDeclaration([ts.createExportSpecifier(rename, text)]), - ]; - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - } - else { - changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); - } - } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; - switch (exported.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: { - // `module.exports = function f() {}` --> `export default function f() {}` - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 203 /* ClassExpression */: { - // `module.exports = class C {}` --> `export default class C {}` - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 185 /* CallExpression */: - if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { - return convertReExportAll(exported.arguments[0], checker); - } - // falls through - default: - // `module.exports = 0;` --> `export default 0;` - return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; - } - } - function convertReExportAll(reExported, checker) { - // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` - var moduleSpecifier = reExported.text; - var moduleSymbol = checker.getSymbolAtLocation(reExported); - var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; - return exports.has("export=") - ? [[reExportDefault(moduleSpecifier)], true] - : !exports.has("default") - ? [[reExportStar(moduleSpecifier)], false] - // If there's some non-default export, must include both `export *` and `export default`. - : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; - } - function reExportStar(moduleSpecifier) { - return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); - } - function reExportDefault(moduleSpecifier) { - return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); - } - function convertExportsDotXEquals(name, exported) { - var modifiers = [ts.createToken(84 /* ExportKeyword */)]; - switch (exported.kind) { - case 190 /* FunctionExpression */: { - var expressionName = exported.name; - if (expressionName && expressionName.text !== name) { - // `exports.f = function g() {}` -> `export const f = function g() {}` - return exportConst(); - } - } - // falls through - case 191 /* ArrowFunction */: - // `exports.f = function() {}` --> `export function f() {}` - return functionExpressionToDeclaration(name, modifiers, exported); - case 203 /* ClassExpression */: - // `exports.C = class {}` --> `export class C {}` - return classExpressionToDeclaration(name, modifiers, exported); - default: - return exportConst(); - } - function exportConst() { - // `exports.x = 0;` --> `export const x = 0;` - return makeConst(modifiers, ts.createIdentifier(name), exported); - } - } - /** - * Converts `const <> = require("x");`. - * Returns nodes that will replace the variable declaration for the commonjs import. - * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. - */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { - switch (name.kind) { - case 178 /* ObjectBindingPattern */: { - var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { - return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) - ? undefined - : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); - }); - if (importSpecifiers) { - return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; - } - } - // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 179 /* ArrayBindingPattern */: { - /* - import x from "x"; - const [a, b, c] = x; - */ - var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); - return [ - makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), - makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), - ]; - } - case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); - default: - ts.Debug.assertNever(name); - } - } - /** - * Convert `import x = require("x").` - * Also converts uses like `x.y()` to `y()` and uses a named import. - */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { - var nameSymbol = checker.getSymbolAtLocation(name); - // Maps from module property name to name actually used. (The same if there isn't shadowing.) - var namedBindingsNames = ts.createMap(); - // True if there is some non-property use like `x()` or `f(x)`. - var needDefaultImport = false; - for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { - var use = _a[_i]; - if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { - // This was a use of a different symbol with the same name, due to shadowing. Ignore. - continue; - } - var parent = use.parent; - if (ts.isPropertyAccessExpression(parent)) { - var expression = parent.expression, propertyName = parent.name.text; - ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` - var idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); - } - changes.replaceNode(file, parent, ts.createIdentifier(idName)); - } - else { - needDefaultImport = true; - } - } - var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { - var propertyName = _a[0], idName = _a[1]; - return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); - })); - if (!namedBindings) { - // If it was unused, ensure that we at least import *something*. - needDefaultImport = true; - } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; - } - // Identifiers helpers - function makeUniqueName(name, identifiers) { - while (identifiers.original.has(name) || identifiers.additional.has(name)) { - name = "_" + name; - } - identifiers.additional.set(name, true); - return name; - } - function collectFreeIdentifiers(file) { - var map = ts.createMultiMap(); - file.forEachChild(function recur(node) { - if (ts.isIdentifier(node) && isFreeIdentifier(node)) { - map.add(node.text, node); - } - node.forEachChild(recur); - }); - return map; - } - function isFreeIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 183 /* PropertyAccessExpression */: - return parent.name !== node; - case 180 /* BindingElement */: - return parent.propertyName !== node; - default: - return true; - } - } - // Node helpers - function functionExpressionToDeclaration(name, additionalModifiers, fn) { - return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); - } - function classExpressionToDeclaration(name, additionalModifiers, cls) { - return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); - } - function makeSingleImport(localName, propertyName, moduleSpecifier) { - return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); - } - function makeImport(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); - } - function makeImportSpecifier(propertyName, name) { - return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); - } - function makeConst(modifiers, name, init) { - return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); - } - function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { - return ts.createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); - } - })(refactor = ts.refactor || (ts.refactor = {})); -})(ts || (ts = {})); +/// +/// /// /// /* @internal */ @@ -97926,7 +99116,7 @@ var ts; } else if (ts.isVariableStatement(node)) { var numInitializers = 0; - var lastInitializer = undefined; + var lastInitializer = void 0; for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.initializer) { @@ -98043,7 +99233,7 @@ var ts; switch (node.kind) { case 232 /* FunctionDeclaration */: case 233 /* ClassDeclaration */: - if (node.parent.kind === 272 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { + if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } @@ -98323,12 +99513,12 @@ var ts; var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); - var returnType = undefined; + var returnType; var parameters = []; var callArguments = []; var writes; usagesInScope.forEach(function (usage, name) { - var typeNode = undefined; + var typeNode; 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) {" @@ -98563,7 +99753,7 @@ var ts; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -98578,14 +99768,14 @@ var ts; changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else if (node.parent.kind === 214 /* 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.replaceNode(context.file, node.parent, newVariableStatement, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { var newVariableStatement = ts.createVariableStatement( @@ -98605,7 +99795,7 @@ var ts; } else { var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } } } @@ -98615,7 +99805,7 @@ var ts; return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function getContainingVariableDeclarationIfInList(node, scope) { - var prevNode = undefined; + var prevNode; while (node !== undefined && node !== scope) { if (ts.isVariableDeclaration(node) && node.initializer === prevNode && @@ -98640,16 +99830,16 @@ var ts; ts.Debug.assert(fileName === renameFilename); for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) { var change = textChanges_3[_b]; - var span_15 = change.span, newText = change.newText; + var span = change.span, newText = change.newText; var index = newText.indexOf(functionNameText); if (index !== -1) { - lastPos = span_15.start + delta + index; + lastPos = span.start + delta + index; // If the reference comes first, return immediately. if (!isDeclaredBeforeUse) { return lastPos; } } - delta += newText.length - span_15.length; + delta += newText.length - span.length; } } // If the declaration comes first, return the position of the last occurrence. @@ -98658,7 +99848,7 @@ var ts; return lastPos; } function getFirstDeclaration(type) { - var firstDeclaration = undefined; + var firstDeclaration; var symbol = type.symbol; if (symbol && symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -98780,7 +99970,7 @@ var ts; 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 prevMember; var allProperties = true; for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { var member = members_6[_i]; @@ -98802,7 +99992,7 @@ var ts; } function getNodeToInsertConstantBefore(node, scope) { ts.Debug.assert(!ts.isClassLike(scope)); - var prevScope = undefined; + var prevScope; for (var curr = node; curr !== scope; curr = curr.parent) { if (isScope(curr)) { prevScope = curr; @@ -98810,7 +100000,7 @@ var ts; } for (var curr = (prevScope || node).parent;; curr = curr.parent) { if (isBlockLike(curr)) { - var prevStatement = undefined; + var prevStatement = void 0; for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement.pos > node.pos) { @@ -98875,13 +100065,13 @@ var ts; var visibleDeclarationsInExtractedRange = []; var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID var exposedVariableDeclarations = []; - var firstExposedNonVariableDeclaration = undefined; + var firstExposedNonVariableDeclaration; var expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : undefined; - var expressionDiagnostic = undefined; + var expressionDiagnostic; if (expression === undefined) { var statements = targetRange.range; var start = ts.first(statements).getStart(); @@ -98959,7 +100149,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_10 = function (i) { + var _loop_12 = 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 @@ -98969,7 +100159,7 @@ var ts; constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); } var hasWrite = false; - var readonlyClassPropertyWrite = undefined; + var readonlyClassPropertyWrite; usagesPerScope[i].usages.forEach(function (value) { if (value.usage === 2 /* Write */) { hasWrite = true; @@ -98999,7 +100189,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_10(i); + _loop_12(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { @@ -99267,165 +100457,251 @@ var ts; })(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) { - var refactorName = "Install missing types package"; - var actionName = "install"; - var description = "Install missing types package"; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { - // Then it will be available via `fixCannotFindModule`. - return undefined; - } - var action = getAction(context); - return action && [ - { - name: refactorName, - description: 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 242 /* ImportDeclaration */: - case 252 /* 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 description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); - refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition, program = context.program; - if (!ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { - return undefined; - } - var importInfo = getConvertibleImportAtPosition(file, startPosition); - if (!importInfo) { - return undefined; - } - var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); - if (!(resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) { - return undefined; - } - return [ - { - name: actionName, - description: description, - actions: [ - { - description: 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 241 /* ImportEqualsDeclaration */: - var eq = node; - var moduleReference = eq.moduleReference; - return moduleReference.kind === 252 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression) - ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression } - : undefined; - case 242 /* ImportDeclaration */: - var d = node; - var importClause = d.importClause; - return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* 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 244 /* NamespaceImport */: - case 252 /* 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 = {})); -/// -/// -/// /// -/// -/// +/* @internal */ +var ts; +(function (ts) { + var sourcemaps; + (function (sourcemaps) { + sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; + function decode(host, mapPath, map, program, fallbackCache) { + if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } + var currentDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot || currentDirectory; + var decodedMappings; + var generatedOrderedMappings; + var sourceOrderedMappings; + return { + getOriginalPosition: getOriginalPosition, + getGeneratedPosition: getGeneratedPosition + }; + function getGeneratedPosition(loc) { + var maps = getGeneratedOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { + return loc; + } + return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos + } + function getOriginalPosition(loc) { + var maps = getSourceOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos + } + function getSourceFileLike(fileName, location) { + // Lookup file in program, if provided + var file = program && program.getSourceFile(fileName); + if (!file) { + // Otherwise check the cache (which may hit disk) + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + return fallbackCache.get(path); + } + return file; + } + function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { + var file = getSourceFileLike(fileName, directory); + if (!file) { + return -1; + } + return ts.getPositionOfLineAndCharacter(file, line, character); + } + function getDecodedMappings() { + return decodedMappings || (decodedMappings = calculateDecodedMappings()); + } + function getSourceOrderedMappings() { + return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); + } + function getGeneratedOrderedMappings() { + return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); + } + function calculateDecodedMappings() { + var state = { + encodedText: map.mappings, + currentNameIndex: undefined, + sourceMapNamesLength: map.names ? map.names.length : undefined, + currentEmittedColumn: 0, + currentEmittedLine: 0, + currentSourceColumn: 0, + currentSourceLine: 0, + currentSourceIndex: 0, + positions: [], + decodingIndex: 0, + processPosition: processPosition, + }; + while (!hasCompletedDecoding(state)) { + decodeSinglePosition(state); + if (state.error) { + host.log("Encountered error while decoding sourcemap found at " + mapPath + ": " + state.error); + return []; + } + } + return state.positions; + } + function compareProcessedPositionSourcePositions(a, b) { + return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || + ts.compareValues(a.sourcePosition, b.sourcePosition); + } + function compareProcessedPositionEmittedPositions(a, b) { + return ts.compareValues(a.emittedPosition, b.emittedPosition); + } + function processPosition(position) { + var sourcePath = map.sources[position.sourceIndex]; + return { + emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), + sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), + sourcePath: sourcePath, + }; + } + } + sourcemaps.decode = decode; + function hasCompletedDecoding(state) { + return state.decodingIndex === state.encodedText.length; + } + function decodeSinglePosition(state) { + while (state.decodingIndex < state.encodedText.length) { + var char = state.encodedText.charCodeAt(state.decodingIndex); + if (char === 59 /* semicolon */) { + // New line + state.currentEmittedLine++; + state.currentEmittedColumn = 0; + state.decodingIndex++; + continue; + } + if (char === 44 /* comma */) { + // Next entry is on same line - no action needed + state.decodingIndex++; + continue; + } + // Read the current position + // 1. Column offset from prev read jsColumn + state.currentEmittedColumn += base64VLQFormatDecode(); + // Incorrect emittedColumn dont support this map + if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { + return; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { + return; + } + // 2. Relative sourceIndex + state.currentSourceIndex += base64VLQFormatDecode(); + // Incorrect sourceIndex dont support this map + if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { + return; + } + // Dont support reading mappings that dont have information about original source position + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { + return; + } + // 3. Relative sourceLine 0 based + state.currentSourceLine += base64VLQFormatDecode(); + // Incorrect sourceLine dont support this map + if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { + return; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { + return; + } + // 4. Relative sourceColumn 0 based + state.currentSourceColumn += base64VLQFormatDecode(); + // Incorrect sourceColumn dont support this map + if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { + return; + } + // 5. Check if there is name: + if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { + if (state.currentNameIndex === undefined) { + state.currentNameIndex = 0; + } + state.currentNameIndex += base64VLQFormatDecode(); + // Incorrect nameIndex dont support this map + // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap + // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { + // return; + // } + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { + return; + } + // Entry should be complete + capturePosition(); + return; + } + createErrorIfCondition(/*condition*/ true, "No encoded entry found"); + return; + function capturePosition() { + state.positions.push(state.processPosition({ + emittedColumn: state.currentEmittedColumn, + emittedLine: state.currentEmittedLine, + sourceColumn: state.currentSourceColumn, + sourceIndex: state.currentSourceIndex, + sourceLine: state.currentSourceLine, + nameIndex: state.currentNameIndex + })); + } + function createErrorIfCondition(condition, errormsg) { + if (state.error) { + // An error was already reported + return true; + } + if (condition) { + state.error = errormsg; + } + return condition; + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; state.decodingIndex++) { + if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { + return; + } + // 6 digit number + var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + function base64FormatDecode(char) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + } + function isSourceMappingSegmentEnd(encodedText, pos) { + return (pos === encodedText.length || + encodedText.charCodeAt(pos) === 44 /* comma */ || + encodedText.charCodeAt(pos) === 59 /* semicolon */); + } + })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); +})(ts || (ts = {})); /// /// /// @@ -99447,6 +100723,7 @@ var ts; /// /// /// +/// /// /// /// @@ -99456,10 +100733,11 @@ var ts; /// /// /// +/// var ts; (function (ts) { /** The version of the language service API */ - ts.servicesVersion = "0.7"; + ts.servicesVersion = "0.8"; 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) : @@ -99519,104 +100797,15 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { - ts.scanner.setTextPos(pos); - while (pos < end) { - var token = ts.scanner.scan(); - var textPos = ts.scanner.getTextPos(); - if (textPos <= end) { - if (token === 71 /* Identifier */) { - ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(this) + " to have an Identifier in its trivia"); - } - nodes.push(createNode(token, pos, textPos, this)); - } - pos = textPos; - if (token === 1 /* EndOfFileToken */) { - break; - } - } - return pos; - }; - NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, this); - list._children = []; - var pos = nodes.pos; - for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { - var node = nodes_9[_i]; - if (pos < node.pos) { - pos = this.addSyntheticNodes(list._children, pos, node.pos); - } - list._children.push(node); - pos = node.end; - } - if (pos < nodes.end) { - this.addSyntheticNodes(list._children, pos, nodes.end); - } - return list; - }; - NodeObject.prototype.createChildren = function (sourceFile) { - var _this = this; - if (!ts.isNodeKind(this.kind)) { - this._children = ts.emptyArray; - return; - } - if (ts.isJSDocCommentContainingNode(this)) { - /** 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 = []; - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - var pos = this.pos; - var processNode = function (node) { - pos = _this.addSyntheticNodes(children, pos, node.pos); - children.push(node); - pos = node.end; - }; - var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); - } - 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) { - this.addSyntheticNodes(children, pos, this.end); - } - ts.scanner.setText(undefined); - this._children = children; - }; NodeObject.prototype.getChildCount = function (sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children.length; + return this.getChildren(sourceFile).length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children[index]; + return this.getChildren(sourceFile)[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; + return this._children || (this._children = createChildren(this, sourceFile)); }; NodeObject.prototype.getFirstToken = function (sourceFile) { this.assertHasRealPosition(); @@ -99643,6 +100832,69 @@ var ts; }; return NodeObject; }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified 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 = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 71 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } var TokenOrIdentifierObject = /** @class */ (function () { function TokenOrIdentifierObject(pos, end) { // Set properties in same order as NodeObject @@ -99891,7 +101143,7 @@ var ts; */ function findInheritedJSDocComments(declaration, propertyName, typeChecker) { var foundDocs = false; - return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { + return ts.flatMap(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { if (foundDocs) { return ts.emptyArray; } @@ -99908,20 +101160,6 @@ var ts; 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) { @@ -99978,20 +101216,8 @@ var ts; } function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); - if (name) { - var result_6 = ts.getTextOfIdentifierOrLiteral(name); - if (result_6 !== undefined) { - return result_6; - } - if (name.kind === 146 /* ComputedPropertyName */) { - var expr = name.expression; - if (expr.kind === 183 /* PropertyAccessExpression */) { - return expr.name.text; - } - return ts.getTextOfIdentifierOrLiteral(expr); - } - } - return undefined; + return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) : + name.kind === 146 /* ComputedPropertyName */ && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined); } function visit(node) { switch (node.kind) { @@ -100366,6 +101592,31 @@ var ts; return ThrottledCancellationToken; }()); ts.ThrottledCancellationToken = ThrottledCancellationToken; + /* @internal */ + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } + ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -100379,6 +101630,7 @@ var ts; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } + var sourcemappedFileCache; function log(message) { if (host.log) { host.log(message); @@ -100471,6 +101723,10 @@ var ts; // 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; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourcemappedFileCache = createSourceFileLikeCache(host); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); @@ -100578,18 +101834,25 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return semanticDiagnostics.concat(declarationDiagnostics); } + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program); + } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } + if (options === void 0) { options = ts.defaultPreferences; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), fullPreferences); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName, preferences); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -100600,9 +101863,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { - return undefined; - } - if (ts.isLabelName(node)) { + // Avoid giving quickInfo for the sourceFile as a whole. return undefined; } var typeChecker = program.getTypeChecker(); @@ -100611,6 +101872,11 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 71 /* Identifier */: + if (ts.isLabelName(node)) { + // Type here will be 'any', avoid displaying this. + return undefined; + } + // falls through case 183 /* PropertyAccessExpression */: case 145 /* QualifiedName */: case 99 /* ThisKeyword */: @@ -100618,27 +101884,25 @@ var ts; case 97 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); - if (type) { - return { - 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(typeChecker) : undefined, - tags: type.symbol ? type.symbol.getJsDocTags() : undefined - }; - } + return type && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type.symbol ? type.symbol.getJsDocTags() : undefined + }; } return undefined; } - var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; return { - kind: displayPartsDocumentationsAndKind.symbolKind, + kind: symbolKind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: displayPartsDocumentationsAndKind.displayParts, - documentation: displayPartsDocumentationsAndKind.documentation, - tags: displayPartsDocumentationsAndKind.tags + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags, }; } function getSymbolAtLocationForQuickInfo(node, checker) { @@ -100646,32 +101910,156 @@ var ts; && ts.isPropertyAssignment(node.parent) && node.parent.name === node) { var type = checker.getContextualType(node.parent.parent); - if (type) { - var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); - if (property) { - return property; - } + var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); + if (property) { + return property; } } return checker.getSymbolAtLocation(node); } + var sourceMapCommentRegExp = /^\/\/[@#] sourceMappingURL=(.+)$/gm; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; + } + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + sourceMapCommentRegExp.lastIndex = starts[index]; + var comment = sourceMapCommentRegExp.exec(mappedFile.text); + if (comment) { + return comment[1]; + } + } + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, program, sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function makeGetTargetOfMappedPosition(extract, create) { + return getTargetOfMappedPosition; + function getTargetOfMappedPosition(input) { + var info = extract(input); + if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { + var file = program.getSourceFile(info.fileName); + if (!file) { + var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); + file = sourcemappedFileCache.get(path); + } + if (!file) { + return input; + } + var mapper = getSourceMapper(info.fileName, file); + var newLoc = mapper.getOriginalPosition(info); + if (newLoc === info) + return input; + return getTargetOfMappedPosition(create(newLoc, input)); + } + return input; + } + } + var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + containerKind: info.containerKind, + containerName: info.containerName, + fileName: newLoc.fileName, + kind: info.kind, + name: info.name, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + } + }); }); + function getTargetOfMappedDeclarationFiles(infos) { + return ts.map(infos, getTargetOfMappedDeclarationInfo); + } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position)); } function getDefinitionAndBoundSpan(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + var result = ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + if (!result) + return result; + var mappedDefs = getTargetOfMappedDeclarationFiles(result.definitions); + if (mappedDefs === result.definitions) { + return result; + } + return { + definitions: mappedDefs, + textSpan: result.textSpan + }; } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); + return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position)); } /// Goto implementation + var getTargetOfMappedImplementationLocation = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + fileName: newLoc.fileName, + kind: info.kind, + displayParts: info.displayParts, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + } + }); }); + function getTargetOfMappedImplementationLocations(infos) { + return ts.map(infos, getTargetOfMappedImplementationLocation); + } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return getTargetOfMappedImplementationLocations(ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position)); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -100891,29 +102279,32 @@ var ts; } return []; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); 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, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); }); } - function getCombinedCodeFix(scope, fixId, formatOptions) { + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions) { + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -100927,6 +102318,7 @@ var ts; : Promise.reject("Host does not implement `installPackage`"); default: ts.Debug.fail(); + // TODO: Debug.assertNever(action); will only work if there is more than one type. } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -101010,7 +102402,7 @@ var ts; if (!ts.isInComment(sourceFile, matchPosition)) { continue; } - var descriptor = undefined; + var descriptor = void 0; for (var i = 0; i < descriptors.length; i++) { if (matchArray[i + firstDescriptorCaptureIndex]) { descriptor = descriptors[i]; @@ -101094,7 +102486,7 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } - function getRefactorContext(file, positionOrRange, formatOptions) { + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; return { file: file, @@ -101104,23 +102496,27 @@ var ts; host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, + preferences: preferences, }; } - function getApplicableRefactors(fileName, positionOrRange) { + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); } - function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -101544,36 +102940,6 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } - function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, comparer) { - var newIndex = 0; - var oldIndex = 0; - var newLen = newItems.length; - var oldLen = oldItems.length; - while (newIndex < newLen && oldIndex < oldLen) { - var newItem = newItems[newIndex]; - var oldItem = oldItems[oldIndex]; - var compareResult = comparer(newItem, oldItem); - if (compareResult === -1 /* LessThan */) { - inserted(newItem); - newIndex++; - } - else if (compareResult === 1 /* GreaterThan */) { - deleted(oldItem); - oldIndex++; - } - else { - newIndex++; - oldIndex++; - } - } - while (newIndex < newLen) { - inserted(newItems[newIndex++]); - } - while (oldIndex < oldLen) { - deleted(oldItems[oldIndex++]); - } - } - server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; /* @internal */ function indent(str) { return "\n " + str; @@ -101587,6 +102953,7 @@ var ts; server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +// tslint:disable no-unnecessary-qualifier /** * Declaration module describing the TypeScript Server protocol */ @@ -101637,6 +103004,7 @@ var ts; CommandTypes["GeterrForProject"] = "geterrForProject"; CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; + CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync"; CommandTypes["NavBar"] = "navbar"; /* @internal */ CommandTypes["NavBarFull"] = "navbar-full"; @@ -101645,6 +103013,7 @@ var ts; CommandTypes["NavtoFull"] = "navto-full"; CommandTypes["NavTree"] = "navtree"; CommandTypes["NavTreeFull"] = "navtree-full"; + /** @deprecated */ CommandTypes["Occurrences"] = "occurrences"; CommandTypes["DocumentHighlights"] = "documentHighlights"; /* @internal */ @@ -101682,8 +103051,9 @@ var ts; CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; /* @internal */ CommandTypes["Cleanup"] = "cleanup"; + CommandTypes["GetOutliningSpans"] = "getOutliningSpans"; /* @internal */ - CommandTypes["OutliningSpans"] = "outliningSpans"; + CommandTypes["GetOutliningSpansFull"] = "outliningSpans"; CommandTypes["TodoComments"] = "todoComments"; CommandTypes["Indentation"] = "indentation"; CommandTypes["DocCommentTemplate"] = "docCommentTemplate"; @@ -101822,7 +103192,7 @@ var ts; end: scriptInfo.positionToLineOffset(diag.start + diag.length), text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), code: diag.code, - category: ts.DiagnosticCategory[diag.category].toLowerCase(), + category: ts.diagnosticCategoryName(diag), source: diag.source }; } @@ -101834,7 +103204,7 @@ var ts; var end = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length)); var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n"); var code = diag.code, source = diag.source; - var category = ts.DiagnosticCategory[diag.category].toLowerCase(); + var category = ts.diagnosticCategoryName(diag); return includeFileName ? { start: start, end: end, text: text, code: code, category: category, source: source, fileName: diag.file && diag.file.fileName } : { start: start, end: end, text: text, code: code, category: category, source: source }; } @@ -102061,8 +103431,11 @@ var ts; _a[server.CommandNames.QuickinfoFull] = function (request) { return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ false)); }, - _a[server.CommandNames.OutliningSpans] = function (request) { - return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); + _a[server.CommandNames.GetOutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.GetOutliningSpansFull] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.TodoComments] = function (request) { return _this.requiredResponse(_this.getTodoComments(request.arguments)); @@ -102140,6 +103513,9 @@ var ts; _a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments)); }, + _a[server.CommandNames.SuggestionDiagnosticsSync] = function (request) { + return _this.requiredResponse(_this.getSuggestionDiagnosticsSync(request.arguments)); + }, _a[server.CommandNames.Geterr] = function (request) { _this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); }); return _this.notRequired(); @@ -102256,6 +103632,7 @@ var ts; this.hrtime = opts.hrtime; this.logger = opts.logger; this.canUseEvents = opts.canUseEvents; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; var throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = this.canUseEvents ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); }) @@ -102278,6 +103655,7 @@ var ts; typingsInstaller: this.typingsInstaller, throttleWaitMilliseconds: throttleWaitMilliseconds, eventHandler: this.eventHandler, + suppressDiagnosticEvents: this.suppressDiagnosticEvents, globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads @@ -102326,9 +103704,11 @@ var ts; 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); }); + if (!this.suppressDiagnosticEvents) { + 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 @@ -102382,52 +103762,58 @@ var ts; this.send(res); }; Session.prototype.semanticCheck = function (file, project) { - try { - var diags = server.emptyArray; - if (!isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { - diags = project.getLanguageService().getSemanticDiagnostics(file); - } - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); - } - catch (err) { - this.logError(err, "semantic check"); - } + var diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) + ? server.emptyArray + : project.getLanguageService().getSemanticDiagnostics(file); + this.sendDiagnosticsEvent(file, project, diags, "semanticDiag"); }; Session.prototype.syntacticCheck = function (file, project) { + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag"); + }; + Session.prototype.infoCheck = function (file, project) { + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); + }; + Session.prototype.sendDiagnosticsEvent = function (file, project, diagnostics, kind) { try { - var diags = project.getLanguageService().getSyntacticDiagnostics(file); - if (diags) { - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); - } + this.event({ file: file, diagnostics: diagnostics.map(function (diag) { return formatDiag(file, project, diag); }) }, kind); } catch (err) { - this.logError(err, "syntactic check"); + this.logError(err, kind); } }; + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { var _this = this; if (requireOpen === void 0) { requireOpen = true; } + ts.Debug.assert(!this.suppressDiagnosticEvents); // Caller's responsibility var seq = this.changeSeq; var followMs = Math.min(ms, 200); var index = 0; var checkOne = function () { - if (_this.changeSeq === seq) { - var checkSpec_1 = checkList[index]; - index++; - if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { - _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - if (_this.changeSeq === seq) { - next.immediate(function () { - _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); - if (checkList.length > index) { - next.delay(followMs, checkOne); - } - }); - } - } + if (_this.changeSeq !== seq) { + return; } + var _a = checkList[index], fileName = _a.fileName, project = _a.project; + index++; + if (!project.containsFile(fileName, requireOpen)) { + return; + } + _this.syntacticCheck(fileName, project); + if (_this.changeSeq !== seq) { + return; + } + next.immediate(function () { + _this.semanticCheck(fileName, project); + if (_this.changeSeq !== seq) { + return; + } + next.immediate(function () { + _this.infoCheck(fileName, project); + if (checkList.length > index) { + next.delay(followMs, checkOne); + } + }); + }); }; if (checkList.length > index && this.changeSeq === seq) { next.delay(ms, checkOne); @@ -102481,7 +103867,7 @@ var ts; message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), start: d.start, length: d.length, - category: ts.DiagnosticCategory[d.category].toLowerCase(), + category: ts.diagnosticCategoryName(d), code: d.code, startLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start)), endLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length)) @@ -102501,7 +103887,7 @@ var ts; message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), start: d.start, length: d.length, - category: ts.DiagnosticCategory[d.category].toLowerCase(), + category: ts.diagnosticCategoryName(d), code: d.code, source: d.source, startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), @@ -102629,6 +104015,15 @@ var ts; } return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; + Session.prototype.getSuggestionDiagnosticsSync = function (args) { + var configFile = this.getConfigFileAndProject(args).configFile; + if (configFile) { + // Currently there are no info diagnostics for config files. + return server.emptyArray; + } + // isSemantic because we don't want to info diagnostics in declaration files for JS-only users + return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, args.includeLinePosition); + }; Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); @@ -102886,9 +104281,22 @@ var ts; var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, /*ensureProject*/ true); return { file: file, project: project }; }; - Session.prototype.getOutliningSpans = function (args) { + Session.prototype.getOutliningSpans = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; - return languageService.getOutliningSpans(file); + var spans = languageService.getOutliningSpans(file); + if (simplifiedResult) { + var scriptInfo_1 = this.projectService.getScriptInfoForNormalizedPath(file); + return spans.map(function (s) { return ({ + textSpan: _this.toLocationTextSpan(s.textSpan, scriptInfo_1), + hintSpan: _this.toLocationTextSpan(s.hintSpan, scriptInfo_1), + bannerText: s.bannerText, + autoCollapse: s.autoCollapse + }); }); + } + else { + return spans; + } }; Session.prototype.getTodoComments = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; @@ -102908,7 +104316,7 @@ var ts; Session.prototype.getIndentation = function (args) { 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 options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); var indentation = languageService.getIndentationAtPosition(file, position, options); return { position: position, indentation: indentation }; }; @@ -102958,7 +104366,7 @@ var ts; var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); // TODO: avoid duplicate code (with formatonkey) - var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file)); if (!edits) { return undefined; } @@ -102966,24 +104374,24 @@ var ts; }; Session.prototype.getFormattingEditsForRangeFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; - var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); }; Session.prototype.getFormattingEditsForDocumentFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; - var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsForDocument(file, options); }; Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; - var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); }; Session.prototype.getFormattingEditsAfterKeystroke = function (args) { 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 formatOptions = this.getFormatOptions(file); 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. @@ -103035,7 +104443,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, args); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { @@ -103058,7 +104466,7 @@ var ts; 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 project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file)); }); return simplifiedResult ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(project, action); }) })); }) @@ -103106,12 +104514,12 @@ var ts; return undefined; } if (simplifiedResult) { - var span_16 = helpItems.applicableSpan; + var span = helpItems.applicableSpan; return { items: helpItems.items, applicableSpan: { - start: scriptInfo.positionToLineOffset(span_16.start), - end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(span.start + span.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, @@ -103131,6 +104539,9 @@ var ts; }); }; Session.prototype.getDiagnostics = function (next, delay, fileNames) { + if (this.suppressDiagnosticEvents) { + return; + } var checkList = this.createCheckList(fileNames); if (checkList.length > 0) { this.updateErrorCheck(next, checkList, delay); @@ -103300,7 +104711,7 @@ var ts; return locationOrSpan.line !== undefined; }; Session.prototype.extractPositionAndRange = function (args, scriptInfo) { - var position = undefined; + var position; var textRange; if (this.isLocation(args)) { position = getPosition(args); @@ -103318,13 +104729,13 @@ var ts; 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); + return project.getLanguageService().getApplicableRefactors(file, position || textRange, this.getPreferences(file)); }; Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { 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, this.projectService.getFormatCodeOptions(file), position || textRange, args.refactor, args.action); + var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), position || textRange, args.refactor, args.action, this.getPreferences(file)); if (result === undefined) { return { edits: [] @@ -103347,8 +104758,7 @@ var ts; var scope = _a.scope; ts.Debug.assert(scope.type === "file"); var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; - var formatOptions = this.projectService.getFormatCodeOptions(file); - var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, formatOptions); + var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(project, changes); } @@ -103364,8 +104774,7 @@ var ts; 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); - var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions); + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); if (!codeActions) { return undefined; } @@ -103380,8 +104789,7 @@ var ts; var scope = _a.scope, fixId = _a.fixId; ts.Debug.assert(scope.type === "file"); var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; - var formatOptions = this.projectService.getFormatCodeOptions(file); - var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, formatOptions); + var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return { changes: this.mapTextChangesToCodeEdits(project, res.changes), commands: res.commands }; } @@ -103399,7 +104807,7 @@ var ts; return {}; }; Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { - var startPosition = undefined, endPosition = undefined; + var startPosition, endPosition; if (args.startPosition !== undefined) { startPosition = args.startPosition; } @@ -103419,9 +104827,9 @@ var ts; }; Session.prototype.mapCodeAction = function (project, _a) { var _this = this; - var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands, fixId = _a.fixId; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands, fixId = _a.fixId, fixAllDescription = _a.fixAllDescription; var changes = unmappedChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); - return { description: description, changes: changes, commands: commands, fixId: fixId }; + return { description: description, changes: changes, commands: commands, fixId: fixId, fixAllDescription: fixAllDescription }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; @@ -103454,6 +104862,9 @@ var ts; : spans; }; Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { + if (this.suppressDiagnosticEvents) { + return; + } var _a = this.getProjectInfoWorker(fileName, /*projectFileName*/ undefined, /*needFileNameList*/ true, /*excludeConfigFiles*/ true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; @@ -103584,6 +104995,12 @@ var ts; /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); } }; + Session.prototype.getFormatOptions = function (file) { + return this.projectService.getFormatCodeOptions(file); + }; + Session.prototype.getPreferences = function (file) { + return this.projectService.getPreferences(file); + }; return Session; }()); server.Session = Session; @@ -104498,8 +105915,12 @@ var ts; if (this.isOpen) { return this.switchToScriptVersionCache(); } - // Else if the svc is uptodate with the text, we are good - return !this.pendingReloadFromDisk && this.svc; + // If there is pending reload from the disk then, reload the text + if (this.pendingReloadFromDisk) { + this.reloadWithFileText(); + } + // At this point if svc is present its valid + return this.svc; }; TextStorage.prototype.getOrLoadText = function () { if (this.text === undefined || this.pendingReloadFromDisk) { @@ -104593,9 +106014,8 @@ var ts; ScriptInfo.prototype.getRealpathIfDifferent = function () { return this.realpath && this.realpath !== this.path ? this.realpath : undefined; }; - ScriptInfo.prototype.getFormatCodeSettings = function () { - return this.formatCodeSettings; - }; + ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatSettings; }; + ScriptInfo.prototype.getPreferences = function () { return this.preferences; }; ScriptInfo.prototype.attachToProject = function (project) { var isNew = !this.isAttached(project); if (isNew) { @@ -104684,12 +106104,18 @@ var ts; p.registerFileUpdate(this.path); } }; - ScriptInfo.prototype.setFormatOptions = function (formatSettings) { + ScriptInfo.prototype.setOptions = function (formatSettings, preferences) { if (formatSettings) { - if (!this.formatCodeSettings) { - this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); + if (!this.formatSettings) { + this.formatSettings = server.getDefaultFormatCodeSettings(this.host); } - server.mergeMapLikes(this.formatCodeSettings, formatSettings); + server.mergeMapLikes(this.formatSettings, formatSettings); + } + if (preferences) { + if (!this.preferences) { + this.preferences = ts.clone(ts.defaultPreferences); + } + server.mergeMapLikes(this.preferences, preferences); } }; ScriptInfo.prototype.getLatestVersion = function () { @@ -104955,7 +106381,7 @@ var ts; createNewValue: createMissingFileWatch, // Files that are no longer missing (e.g. because they are no longer required) // should no longer be watched. - onDeleteValue: closeFileWatcher + onDeleteValue: ts.closeFileWatcher }); } ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; @@ -104998,75 +106424,74 @@ var ts; return program.isEmittedFile(file); } ts.isEmittedFileOfProgram = isEmittedFileOfProgram; - function addFileWatcher(host, file, cb) { - return host.watchFile(file, cb); + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); } - 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); + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); } - 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); + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); return { close: function () { - if (!logOnlyTrigger) { - log(watcherCaption + "Close: " + info); - } + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); watcher.close(); } }; } - function closeFileWatcher(watcher) { - watcher.close(); + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : ""); } - ts.closeFileWatcher = closeFileWatcher; function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } @@ -105083,15 +106508,17 @@ var ts; var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // 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 nonRelaticeModuleNameCache = ts.createMap(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); - var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); - var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -105164,6 +106591,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); + nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); } function finishCachingPerDirectoryResolution() { @@ -105177,7 +106605,7 @@ var ts; clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); // 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; @@ -105223,15 +106651,8 @@ var ts; 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) { + watchFailedLookupLocationOfResolution(resolution); + if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { @@ -105311,8 +106732,9 @@ var ts; if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { return { dir: rootDir, dirPath: rootPath }; } - var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); - var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // 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); @@ -105338,78 +106760,91 @@ var ts; 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; - } + function watchFailedLookupLocationOfResolution(resolution) { + // No need to set the resolution refCount + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + 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]; + if (resolution.refCount !== undefined) { + resolution.refCount++; + return; + } + resolution.refCount = 1; + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_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; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; if (!ignore) { - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - if (dirWatcher) { - dirWatcher.refCount++; + // 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); + } + if (dirPath === rootPath) { + setAtRoot = true; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + setDirectoryWatcher(dir, dirPath); } } } + if (setAtRoot) { + setDirectoryWatcher(rootDir, rootPath); + } + } + function setDirectoryWatcher(dir, dirPath) { + 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); + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + return; } - } - function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { - var failedLookupLocations = _a.failedLookupLocations; - for (var i = startIndex; i < failedLookupLocations.length; i++) { - var failedLookupLocation = failedLookupLocations[i]; + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + if (!ignore) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - 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--; - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { @@ -105496,7 +106931,8 @@ var ts; // 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)) { + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory isChangedFailedLookupLocation = function (location) { var locationPath = resolutionHost.toPath(location); @@ -105525,7 +106961,17 @@ var ts; function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); } - function createTypeRootsWatch(_typeRootPath, typeRoot) { + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); @@ -105537,6 +106983,12 @@ var ts; // 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(); + // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered + // So handle to failed lookup locations here as well to ensure we are invalidating resolutions + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } }, 1 /* Recursive */); } /** @@ -106100,6 +107552,7 @@ var ts; /*@internal*/ function Project( /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { + var _this = this; this.projectName = projectName; this.projectKind = projectKind; this.projectService = projectService; @@ -106133,6 +107586,7 @@ var ts; this.hasChangedAutomaticTypeDirectiveNames = false; this.directoryStructureHost = directoryStructureHost; this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); + this.getCanonicalFileName = this.projectService.toCanonicalFileName; this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { this.compilerOptions = ts.getDefaultCompilerOptions(); @@ -106145,7 +107599,10 @@ var ts; } this.setInternalCompilerOptionsForEmittingJsFiles(); var host = this.projectService.host; - if (host.trace) { + if (this.projectService.logger.loggingEnabled()) { + this.trace = function (s) { return _this.writeLog(s); }; + } + else if (host.trace) { this.trace = function (s) { return host.trace(s); }; } if (host.realpath) { @@ -106297,7 +107754,7 @@ var ts; }; /*@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); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution" /* FailedLookupLocation */, this); }; /*@internal*/ Project.prototype.onInvalidatedResolution = function () { @@ -106305,7 +107762,7 @@ var ts; }; /*@internal*/ Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { - return this.projectService.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory" /* TypeRoots */, this); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory" /* TypeRoots */, this); }; /*@internal*/ Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { @@ -106741,14 +108198,14 @@ var ts; } var oldExternalFiles = this.externalFiles || server.emptyArray; this.externalFiles = this.getExternalFiles(); - server.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, + ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.compareStringsCaseSensitive, // 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) { return _this.detachScriptInfoFromProject(removed); }, ts.compareStringsCaseSensitive); + }, function (removed) { return _this.detachScriptInfoFromProject(removed); }); var elapsed = ts.timestamp() - start; this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " Version: " + this.getProjectVersion() + " structureChanged: " + hasChanges + " Elapsed: " + elapsed + "ms"); return hasChanges; @@ -106762,7 +108219,7 @@ var ts; }; Project.prototype.addMissingFileWatcher = function (missingFilePath) { var _this = this; - var fileWatcher = this.projectService.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { + var fileWatcher = this.projectService.watchFactory.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { if (_this.projectKind === ProjectKind.Configured) { _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); } @@ -106772,7 +108229,7 @@ var ts; // When a missing file is created, we should update the graph. _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this); } - }, "Missing file from program" /* MissingFilePath */, this); + }, ts.PollingInterval.Medium, "Missing file from program" /* MissingFilePath */, this); return fileWatcher; }; Project.prototype.isWatchedMissingFile = function (path) { @@ -106795,8 +108252,8 @@ var ts; 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]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var file = sourceFiles_7[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -106885,7 +108342,7 @@ var ts; // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_11 = function (globalPluginName) { + var _loop_13 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -106900,7 +108357,7 @@ var ts; // Enable global plugins with synthetic configuration entries for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_11(globalPluginName); + _loop_13(globalPluginName); } } }; @@ -107403,6 +108860,9 @@ var ts; ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + function getDetailWatchInfo(watchType, project) { + return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; + } var ProjectService = /** @class */ (function () { function ProjectService(opts) { var _this = this; @@ -107460,6 +108920,7 @@ var ts; this.typingsInstaller = opts.typingsInstaller || server.nullTypingsInstaller; this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = opts.eventHandler; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; @@ -107481,31 +108942,16 @@ var ts; this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + preferences: ts.defaultPreferences, hostInfo: "Unknown host", extraFileExtensions: [] }; 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; - } + var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose : + this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None; + var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop; + this.watchFactory = ts.getWatchFactory(watchLogLevel, log, getDetailWatchInfo); } - 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); }; @@ -107722,17 +109168,15 @@ var ts; return project.dirty && project.updateGraph(); }; ProjectService.prototype.getFormatCodeOptions = function (file) { - var formatCodeSettings; - if (file) { - var info = this.getScriptInfoForNormalizedPath(file); - if (info) { - formatCodeSettings = info.getFormatCodeSettings(); - } - } - return formatCodeSettings || this.hostConfiguration.formatCodeOptions; + var info = this.getScriptInfoForNormalizedPath(file); + return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions; }; - ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind) { - var info = this.getScriptInfoForNormalizedPath(fileName); + ProjectService.prototype.getPreferences = function (file) { + var info = this.getScriptInfoForNormalizedPath(file); + return info && info.getPreferences() || this.hostConfiguration.preferences; + }; + ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind, path) { + var info = this.getScriptInfoForPath(path); if (!info) { this.logger.msg("Error: got watch notification for unknown file: " + fileName); } @@ -107771,7 +109215,7 @@ var ts; /*@internal*/ ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { var _this = this; - return this.watchDirectory(this.host, directory, function (fileOrDirectory) { + return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) { var fileOrDirectoryPath = _this.toPath(fileOrDirectory); project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); var configFilename = project.getConfigFilePath(); @@ -108070,7 +109514,7 @@ var ts; */ 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 */); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root" /* ConfigFileForInferredRoot */); this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); }; /** @@ -108385,7 +109829,7 @@ var ts; var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, 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); + project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); if (!lastFileExceededProgramSize) { project.watchWildcards(projectOptions.wildcardDirectories); } @@ -108400,8 +109844,8 @@ var ts; 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]; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; var newRootFile = propertyReader.getFileName(f); var normalizedPath = server.toNormalizedPath(newRootFile); var isDynamic = server.isDynamicFileName(normalizedPath); @@ -108502,7 +109946,7 @@ var ts; this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { - if (!this.eventHandler) { + if (!this.eventHandler || this.suppressDiagnosticEvents) { return; } this.eventHandler({ @@ -108598,7 +110042,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_12 = function (project) { + var _loop_14 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.getCompilerOptions().preserveSymlinks && @@ -108614,7 +110058,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_12(project); + _loop_14(project); } } } @@ -108624,8 +110068,8 @@ var ts; 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 */); + var fileName = info.fileName; + info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); } }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { @@ -108697,7 +110141,7 @@ var ts; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { - info.setFormatOptions(convertFormatOptions(args.formatOptions)); + info.setOptions(convertFormatOptions(args.formatOptions), args.preferences); this.logger.info("Host configuration update for file " + args.file); } } @@ -108710,6 +110154,9 @@ var ts; server.mergeMapLikes(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); this.logger.info("Format host information updated"); } + if (args.preferences) { + server.mergeMapLikes(this.hostConfiguration.preferences, args.preferences); + } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; // We need to update the project structures again as it is possible that existing @@ -108928,13 +110375,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_13 = function (proj) { + var _loop_15 = 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_13(proj); + _loop_15(proj); } }; /* @internal */ @@ -109043,7 +110490,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_14 = function (name) { + var _loop_16 = 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]; @@ -109061,7 +110508,7 @@ var ts; } } if (rule.exclude) { - var _loop_15 = function (exclude) { + var _loop_17 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -109088,7 +110535,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_15(exclude); + _loop_17(exclude); } } else { @@ -109104,11 +110551,11 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_14(name); + _loop_16(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_16 = function (i) { + var _loop_18 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -109146,7 +110593,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_16(i); + _loop_18(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -109531,8 +110978,7 @@ 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(), + category: ts.diagnosticCategoryName(diagnostic), code: diagnostic.code }; } @@ -109582,7 +111028,7 @@ var ts; }; LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { var newLine = ts.getNewLineOrDefaultFromHost(this.host); - return ts.realizeDiagnostics(diagnostics, newLine); + return realizeDiagnostics(diagnostics, newLine); }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; @@ -109620,6 +111066,10 @@ var ts; return _this.realizeDiagnostics(diagnostics); }); }; + LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + }; LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { var _this = this; return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { @@ -109750,16 +111200,16 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = options === undefined ? undefined : JSON.parse(options); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -109916,8 +111366,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { - var ref = refs_2[_i]; + for (var _i = 0, refs_3 = refs; _i < refs_3.length; _i++) { + var ref = refs_3[_i]; result.push({ path: ts.normalizeSlashes(ref.fileName), position: ref.pos, diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 21ea143e8c5..94dcc50dc28 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -59,7 +59,8 @@ 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; + 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.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -389,7 +390,7 @@ declare namespace ts { FirstJSDocNode = 274, LastJSDocNode = 292, FirstJSDocTagNode = 284, - LastJSDocTagNode = 292, + LastJSDocTagNode = 292 } enum NodeFlags { None = 0, @@ -417,7 +418,7 @@ declare namespace ts { ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, ContextFlags = 6387712, - TypeExcludesFlags = 20480, + TypeExcludesFlags = 20480 } enum ModifierFlags { None = 0, @@ -438,6 +439,7 @@ declare namespace ts { NonPublicAccessibilityModifier = 24, TypeScriptModifier = 2270, ExportDefault = 513, + All = 3071 } enum JsxFlags { None = 0, @@ -445,7 +447,7 @@ declare namespace ts { IntrinsicNamedElement = 1, /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - IntrinsicElement = 3, + IntrinsicElement = 3 } interface Node extends TextRange { kind: SyntaxKind; @@ -643,8 +645,9 @@ declare namespace ts { questionToken?: QuestionToken; body?: Block | Expression; } - type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; + /** @deprecated Use SignatureDeclaration */ + type FunctionLike = SignatureDeclaration; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -652,7 +655,7 @@ declare namespace ts { } interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; - parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + parent?: ObjectTypeDeclaration; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { @@ -686,7 +689,7 @@ declare namespace ts { type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + parent?: ObjectTypeDeclaration; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -1078,11 +1081,13 @@ declare namespace ts { kind: SyntaxKind.JsxOpeningElement; parent?: JsxElement; tagName: JsxTagNameExpression; + typeArguments?: NodeArray; attributes: JsxAttributes; } interface JsxSelfClosingElement extends PrimaryExpression { kind: SyntaxKind.JsxSelfClosingElement; tagName: JsxTagNameExpression; + typeArguments?: NodeArray; attributes: JsxAttributes; } interface JsxFragment extends PrimaryExpression { @@ -1261,6 +1266,7 @@ declare namespace ts { variableDeclaration?: VariableDeclaration; block: Block; } + type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; @@ -1553,7 +1559,7 @@ declare namespace ts { PreFinally = 2048, AfterFinally = 4096, Label = 12, - Condition = 96, + Condition = 96 } interface FlowLock { locked?: boolean; @@ -1725,7 +1731,7 @@ declare namespace ts { enum ExitStatus { Success = 0, DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, + DiagnosticsPresent_OutputsGenerated = 2 } interface EmitResult { emitSkipped: boolean; @@ -1750,9 +1756,9 @@ declare namespace ts { /** 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 & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; - } | undefined; + }) | undefined; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ @@ -1801,7 +1807,7 @@ declare namespace ts { */ getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; - isImplementationOfOverload(node: FunctionLike): boolean | undefined; + isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; @@ -1811,7 +1817,7 @@ declare namespace ts { getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; - getJsxIntrinsicTagNames(): Symbol[]; + getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; @@ -1847,7 +1853,7 @@ declare namespace ts { InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, - InReverseMappedType = 33554432, + InReverseMappedType = 33554432 } enum TypeFormatFlags { None = 0, @@ -1870,14 +1876,14 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469291, + NodeBuilderFlagsMask = 9469291 } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8, + UseAliasDefinedOutsideCurrentScope = 8 } /** * @deprecated @@ -1914,7 +1920,7 @@ declare namespace ts { } enum TypePredicateKind { This = 0, - Identifier = 1, + Identifier = 1 } interface TypePredicateBase { kind: TypePredicateKind; @@ -1960,28 +1966,28 @@ declare namespace ts { JSContainer = 67108864, Enum = 384, Variable = 3, - Value = 107455, - Type = 793064, + Value = 67216319, + Type = 67901928, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 107454, - BlockScopedVariableExcludes = 107455, - ParameterExcludes = 107455, + FunctionScopedVariableExcludes = 67216318, + BlockScopedVariableExcludes = 67216319, + ParameterExcludes = 67216319, PropertyExcludes = 0, - EnumMemberExcludes = 900095, - FunctionExcludes = 106927, - ClassExcludes = 899519, - InterfaceExcludes = 792968, - RegularEnumExcludes = 899327, - ConstEnumExcludes = 899967, - ValueModuleExcludes = 106639, + EnumMemberExcludes = 68008959, + FunctionExcludes = 67215791, + ClassExcludes = 68008383, + InterfaceExcludes = 67901832, + RegularEnumExcludes = 68008191, + ConstEnumExcludes = 68008831, + ValueModuleExcludes = 67215503, NamespaceModuleExcludes = 0, - MethodExcludes = 99263, - GetAccessorExcludes = 41919, - SetAccessorExcludes = 74687, - TypeParameterExcludes = 530920, - TypeAliasExcludes = 793064, + MethodExcludes = 67208127, + GetAccessorExcludes = 67150783, + SetAccessorExcludes = 67183551, + TypeParameterExcludes = 67639784, + TypeAliasExcludes = 67901928, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -1989,7 +1995,7 @@ declare namespace ts { HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500, + ClassMember = 106500 } interface Symbol { flags: SymbolFlags; @@ -2016,7 +2022,7 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default", + Default = "default" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2091,7 +2097,7 @@ declare namespace ts { Instantiable = 7897088, StructuredOrInstantiable = 8355840, Narrowable = 142575359, - NotUnionOrUnit = 134283777, + NotUnionOrUnit = 134283777 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2132,7 +2138,7 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, - ClassOrInterface = 3, + ClassOrInterface = 3 } interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2189,31 +2195,46 @@ declare namespace ts { indexType: Type; constraint?: Type; } + type TypeVariable = TypeParameter | IndexedAccessType; interface IndexType extends InstantiableType { type: InstantiableType | UnionOrIntersectionType; } - interface ConditionalType extends InstantiableType { + interface ConditionalRoot { + node: ConditionalTypeNode; checkType: Type; extendsType: Type; trueType: Type; falseType: Type; + isDistributive: boolean; + inferTypeParameters: TypeParameter[]; + outerTypeParameters?: TypeParameter[]; + instantiations?: Map; + aliasSymbol: Symbol; + aliasTypeArguments: Type[]; + } + interface ConditionalType extends InstantiableType { + root: ConditionalRoot; + checkType: Type; + extendsType: Type; + resolvedTrueType?: Type; + resolvedFalseType?: Type; } interface SubstitutionType extends InstantiableType { - typeParameter: TypeParameter; + typeVariable: TypeVariable; substitute: Type; } enum SignatureKind { Call = 0, - Construct = 1, + Construct = 1 } interface Signature { - declaration: SignatureDeclaration; + declaration?: SignatureDeclaration; typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { String = 0, - Number = 1, + Number = 1 } interface IndexInfo { type: Type; @@ -2222,41 +2243,14 @@ declare namespace ts { } enum InferencePriority { NakedTypeVariable = 1, - MappedType = 2, - ReturnType = 4, - NoConstraints = 8, - AlwaysStrict = 16, + HomomorphicMappedType = 2, + MappedTypeConstraint = 4, + ReturnType = 8, + LiteralKeyof = 16, + NoConstraints = 32, + AlwaysStrict = 64, + PriorityImpliesCombination = 28 } - interface InferenceInfo { - typeParameter: TypeParameter; - candidates: Type[]; - contraCandidates: Type[]; - inferredType: Type; - priority: InferencePriority; - topLevel: boolean; - isFixed: boolean; - } - enum InferenceFlags { - None = 0, - InferUnionTypes = 1, - NoDefault = 2, - AnyDefault = 4, - } - /** - * 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, - } - type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2292,11 +2286,12 @@ declare namespace ts { enum DiagnosticCategory { Warning = 0, Error = 1, - Message = 2, + Suggestion = 2, + Message = 3 } enum ModuleResolutionKind { Classic = 1, - NodeJs = 2, + NodeJs = 2 } interface PluginImport { name: string; @@ -2312,6 +2307,7 @@ declare namespace ts { charset?: string; checkJs?: boolean; declaration?: boolean; + declarationMap?: boolean; emitDeclarationOnly?: boolean; declarationDir?: string; disableSizeLimit?: boolean; @@ -2390,17 +2386,17 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6, + ESNext = 6 } enum JsxEmit { None = 0, Preserve = 1, React = 2, - ReactNative = 3, + ReactNative = 3 } enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1, + LineFeed = 1 } interface LineAndCharacter { /** 0-based. */ @@ -2414,7 +2410,7 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, - JSON = 6, + JSON = 6 } enum ScriptTarget { ES3 = 0, @@ -2424,11 +2420,11 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, - Latest = 6, + Latest = 6 } enum LanguageVariant { Standard = 0, - JSX = 1, + JSX = 1 } /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { @@ -2442,7 +2438,7 @@ declare namespace ts { } enum WatchDirectoryFlags { None = 0, - Recursive = 1, + Recursive = 1 } interface ExpandResult { fileNames: string[]; @@ -2512,7 +2508,7 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", - Json = ".json", + Json = ".json" } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; @@ -2582,7 +2578,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216, + NoAsciiEscaping = 16777216 } interface EmitHelper { readonly name: string; @@ -2595,7 +2591,7 @@ declare namespace ts { Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4, + Unspecified = 4 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2762,6 +2758,7 @@ declare namespace ts { newLine?: NewLineKind; omitTrailingSemicolon?: boolean; } + /** @deprecated See comment on SymbolWriter */ interface SymbolTracker { trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError?(): void; @@ -2812,9 +2809,9 @@ declare namespace ts { SingleElement = 524288, Modifiers = 131328, HeritageClauses = 256, - SingleLineTypeLiteralMembers = 448, - MultiLineTypeLiteralMembers = 65, - TupleTypeElements = 336, + SingleLineTypeLiteralMembers = 384, + MultiLineTypeLiteralMembers = 16449, + TupleTypeElements = 272, UnionTypeConstituents = 260, IntersectionTypeConstituents = 264, ObjectBindingPatternElements = 262576, @@ -2830,12 +2827,12 @@ declare namespace ts { VariableDeclarationList = 272, SingleLineFunctionBodyStatements = 384, MultiLineFunctionBodyStatements = 1, - ClassHeritageClauses = 256, + ClassHeritageClauses = 0, ClassMembers = 65, InterfaceMembers = 65, EnumMembers = 81, CaseBlockClauses = 65, - NamedImportsOrExportsElements = 432, + NamedImportsOrExportsElements = 262576, JsxElementOrFragmentChildren = 131072, JsxElementAttributes = 131328, CaseOrDefaultClauseStatements = 81985, @@ -2845,11 +2842,11 @@ declare namespace ts { TypeArguments = 26896, TypeParameters = 26896, Parameters = 1296, - IndexSignatureParameters = 4432, + IndexSignatureParameters = 4432 } } declare namespace ts { - const versionMajorMinor = "2.8"; + const versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ const version: string; } @@ -2863,15 +2860,10 @@ declare namespace ts { enum FileWatcherEventKind { Created = 0, Changed = 1, - Deleted = 2, + Deleted = 2 } type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; - interface WatchedFile { - fileName: string; - callback: FileWatcherCallback; - mtime?: Date; - } interface System { args: string[]; newLine: string; @@ -2906,6 +2898,8 @@ declare namespace ts { setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; clearScreen?(): void; + base64decode?(input: string): string; + base64encode?(input: string): string; } interface FileWatcher { close(): void; @@ -2932,8 +2926,8 @@ declare namespace ts { reScanTemplateToken(): SyntaxKind; scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): SyntaxKind; - scanJsxToken(): SyntaxKind; + reScanJsxToken(): JsxTokenSyntaxKind; + scanJsxToken(): JsxTokenSyntaxKind; scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; @@ -2947,7 +2941,7 @@ declare namespace ts { tryScan(callback: () => T): T; } function tokenToString(t: SyntaxKind): string | undefined; - function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; + function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, 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. */ @@ -3066,7 +3060,7 @@ declare namespace ts { * 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; + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -3104,9 +3098,9 @@ 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; + function getJSDocTags(node: Node): ReadonlyArray; /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ - function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3260,6 +3254,7 @@ declare namespace ts { function isJSDocVariadicType(node: Node): node is JSDocVariadicType; function isJSDoc(node: Node): node is JSDoc; function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocClassTag(node: Node): node is JSDocClassTag; function isJSDocParameterTag(node: Node): node is JSDocParameterTag; function isJSDocReturnTag(node: Node): node is JSDocReturnTag; function isJSDocTypeTag(node: Node): node is JSDocTypeTag; @@ -3283,7 +3278,7 @@ declare namespace ts { function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node): node is FunctionLike; + function isFunctionLike(node: Node): node is SignatureDeclaration; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; @@ -3301,7 +3296,8 @@ declare namespace ts { function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; function isTemplateLiteral(node: Node): node is TemplateLiteral; function isAssertionExpression(node: Node): node is AssertionExpression; - function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; 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. */ @@ -3398,6 +3394,8 @@ declare namespace ts { function createLoopVariable(): Identifier; /** Create a unique name based on the supplied text. */ function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; /** Create a unique name generated for a node. */ function getGeneratedNameForNode(node: Node): Identifier; function createToken(token: TKind): Token; @@ -3406,6 +3404,8 @@ declare namespace ts { function createNull(): NullLiteral & Token; function createTrue(): BooleanLiteral & Token; function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; @@ -3606,7 +3606,7 @@ declare namespace ts { function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; @@ -3628,10 +3628,10 @@ declare namespace ts { function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; - function createJsxSelfClosingElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; - function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; - function createJsxOpeningElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; - function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; + function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; @@ -3660,7 +3660,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; 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; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ @@ -4332,10 +4332,17 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; } + interface UserPreferences { + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + } interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): Diagnostic[]; getSemanticDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): Diagnostic[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. @@ -4348,7 +4355,7 @@ declare namespace ts { getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, name: string, options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined): CompletionEntryDetails; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | 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; @@ -4378,8 +4385,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; - getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4389,9 +4396,9 @@ declare namespace ts { 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; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings): ReadonlyArray; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -4401,9 +4408,12 @@ declare namespace ts { fileName: string; } type OrganizeImportsScope = CombinedCodeFixScope; - interface GetCompletionsAtPositionOptions { - includeExternalModuleExports: boolean; - includeInsertTextCompletions: boolean; + /** @deprecated Use UserPreferences */ + interface GetCompletionsAtPositionOptions extends UserPreferences { + /** @deprecated Use includeCompletionsForModuleExports */ + includeExternalModuleExports?: boolean; + /** @deprecated Use includeCompletionsWithInsertText */ + includeInsertTextCompletions?: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4484,6 +4494,7 @@ declare namespace ts { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + fixAllDescription?: string; } interface CombinedCodeActions { changes: ReadonlyArray; @@ -4569,7 +4580,7 @@ declare namespace ts { none = "none", definition = "definition", reference = "reference", - writtenReference = "writtenReference", + writtenReference = "writtenReference" } interface HighlightSpan { fileName?: string; @@ -4591,7 +4602,7 @@ declare namespace ts { enum IndentStyle { None = 0, Block = 1, - Smart = 2, + Smart = 2 } interface EditorOptions { BaseIndentSize?: number; @@ -4686,7 +4697,7 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21, + regularExpressionLiteral = 21 } interface SymbolDisplayPart { text: string; @@ -4746,7 +4757,7 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { - /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isGlobalCompletionScope`. */ + /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */ isGlobalCompletion: boolean; isMemberCompletion: boolean; /** @@ -4797,7 +4808,7 @@ declare namespace ts { enum OutputFileType { JavaScript = 0, SourceMap = 1, - Declaration = 2, + Declaration = 2 } enum EndOfLineState { None = 0, @@ -4806,7 +4817,7 @@ declare namespace ts { InDoubleQuoteStringLiteral = 3, InTemplateHeadOrNoSubstitutionTemplate = 4, InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, + InTemplateSubstitutionPosition = 6 } enum TokenClass { Punctuation = 0, @@ -4817,7 +4828,7 @@ declare namespace ts { Identifier = 5, NumberLiteral = 6, StringLiteral = 7, - RegExpLiteral = 8, + RegExpLiteral = 8 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -4916,7 +4927,7 @@ declare namespace ts { /** * */ - jsxAttribute = "JSX attribute", + jsxAttribute = "JSX attribute" } enum ScriptElementKindModifier { none = "", @@ -4927,7 +4938,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional", + optionalModifier = "optional" } enum ClassificationTypeNames { comment = "comment", @@ -4952,7 +4963,7 @@ declare namespace ts { jsxSelfClosingTagName = "jsx self closing tag name", jsxAttribute = "jsx attribute", jsxText = "jsx text", - jsxAttributeStringLiteralValue = "jsx attribute string literal value", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" } enum ClassificationType { comment = 1, @@ -4978,7 +4989,7 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24, + jsxAttributeStringLiteralValue = 24 } } declare namespace ts { @@ -5072,7 +5083,7 @@ declare namespace ts { } declare namespace ts { /** The version of the language service API */ - const servicesVersion = "0.7"; + const servicesVersion = "0.8"; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; diff --git a/lib/typescript.js b/lib/typescript.js index 71de0f4e0b6..06d660a8873 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -41,7 +41,7 @@ var ts; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; })(Comparison = ts.Comparison || (ts.Comparison = {})); - // token > SyntaxKind.Identifer => token is a keyword + // token > SyntaxKind.Identifier => 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) { @@ -474,6 +474,7 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -500,6 +501,7 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["OptimisticUnique"] = 5] = "OptimisticUnique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; // Flags GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; @@ -729,32 +731,32 @@ var ts; SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // 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"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "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["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "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["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -949,11 +951,15 @@ var ts; var InferencePriority; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; - InferencePriority[InferencePriority["NoConstraints"] = 8] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 16] = "AlwaysStrict"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + /* @internal */ var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; @@ -970,6 +976,7 @@ var ts; * 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. */ + /* @internal */ var Ternary; (function (Ternary) { Ternary[Ternary["False"] = 0] = "False"; @@ -990,13 +997,23 @@ var ts; SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + // F.prototype = { ... } + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; - DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + /* @internal */ + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; @@ -1391,9 +1408,9 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; @@ -1409,12 +1426,12 @@ var ts; ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; @@ -1426,6 +1443,68 @@ var ts; ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + /* @internal */ + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + /** + * Triple slash comment of the form + * /// + */ + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + /** + * Single line comment of the form + * // @pragma-name argval1 argval2 + * or + * /// @pragma-name argval1 argval2 + */ + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + /** + * Multiline non-jsdoc pragma of the form + * /* @pragma-name argval1 argval2 * / + */ + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + /** + * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas` + */ + /* @internal */ + function _contextuallyTypePragmas(args) { + return args; + } + // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't + // fancy effectively defining it twice, once in value-space and once in type-space + /* @internal */ + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + }); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1526,7 +1605,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.8"; + ts.versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1546,6 +1625,10 @@ var ts; /* @internal */ (function (ts) { ts.emptyArray = []; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -2087,22 +2170,6 @@ var ts; }; } ts.singleIterator = singleIterator; - /** - * 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++) { - if (!f(array[i], i)) { - return [array.slice(0, i), array.slice(i)]; - } - } - return [array.slice(0), []]; - } - return undefined; - } - ts.span = span; /** * Maps contiguous spans of values with the same key. * @@ -2363,7 +2430,6 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2522,7 +2588,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return elementAt(array, 0); + return array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -2534,7 +2600,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return elementAt(array, -1); + return array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -2752,19 +2818,21 @@ var ts; } ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } var result = createMap(); 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); + result.set(makeKey(value), makeValue(value)); } return result; } ts.arrayToMap = arrayToMap; function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } 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; + result[makeKey(value)] = makeValue(value); } return result; } @@ -2773,6 +2841,20 @@ var ts; return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } ts.arrayToSet = arrayToSet; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -2830,15 +2912,6 @@ var ts; } } } - function group(values, getGroupId) { - var groupIdToGroup = createMultiMap(); - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - groupIdToGroup.add(getGroupId(value), value); - } - return arrayFrom(groupIdToGroup.values()); - } - ts.group = group; /** * Tests whether a value is an array. */ @@ -2958,7 +3031,6 @@ var ts; return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.formatStringFromArgs = formatStringFromArgs; - ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } @@ -3390,6 +3462,10 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAreDeclarationMapsEnabled(options) { + return !!(options.declaration && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined @@ -3809,7 +3885,6 @@ 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); }); @@ -3842,7 +3917,7 @@ var ts; } } }; - for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + for (var _i = 0, _b = sort(files, compareStringsCaseSensitive); _i < _b.length; _i++) { var current = _b[_i]; _loop_1(current); } @@ -3852,7 +3927,7 @@ var ts; return; } } - for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -3884,7 +3959,7 @@ var ts; // 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); })) { + if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -4289,7 +4364,7 @@ var ts; ts.matchedText = matchedText; /** Return the object corresponding to the best pattern to match `candidate`. */ function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; + var matchedValue; // use length of prefix as betterness criteria var longestMatchPrefixLength = -1; for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { @@ -4382,6 +4457,38 @@ var ts; return t === undefined ? undefined : [t]; } ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(ts || (ts = {})); /// var ts; @@ -4393,7 +4500,7 @@ var ts; */ /* @internal */ function setStackTraceLimit() { - if (Error.stackTraceLimit < 100) { + if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. Error.stackTraceLimit = 100; } } @@ -4404,6 +4511,314 @@ var ts; FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + /* @internal */ + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + function getPriorityValues(highPriorityValue) { + var mediumPriorityValue = highPriorityValue * 2; + var lowPriorityValue = mediumPriorityValue * 4; + return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; + } + function pollingInterval(watchPriority) { + return pollingIntervalsForPriority[watchPriority]; + } + var pollingIntervalsForPriority = getPriorityValues(250); + /* @internal */ + function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { + return host.watchFile(fileName, callback, pollingInterval(watchPriority)); + } + ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; + /* @internal */ + ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + function createPollingIntervalBasedLevels(levels) { + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + var _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + /* @internal */ + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + // Remove from watchedFiles + ts.unorderedRemoveItem(watchedFiles, file); + // Do not update polling interval queue since that will happen as part of polling + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + // Set the next polling index and timeout + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + // Always poll complete list of changedFilesInLastPoll + pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length); + // Finally do the actual polling of the queue + pollPollingIntervalQueue(queue); + // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue + // as pollPollingIntervalQueue wont schedule for next poll + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + // Max visit would be all elements of the queue + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + // Changed files go to changedFilesInLastPoll queue + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + // Restart unchangedPollCount for unchanged file and move to low polling interval queue + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from nextDefinedValueIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + /** + * Returns true if file status changed + */ + /*@internal*/ + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + var eventKind = oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + watchedFile.callback(watchedFile.fileName, eventKind); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + /** + * Watch the directory recursively using host provided method to watch child directories + * that means if this is recursive watcher, watch the children directories as well + * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) + */ + /*@internal*/ + function createRecursiveDirectoryWatcher(host) { + return createDirectoryWatcher; + /** + * Create the directory watcher for the dirPath. + */ + function createDirectoryWatcher(dirName, callback) { + var watcher = host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callback(fileName); + // Iterate through existing children and update the watches if needed + updateChildWatches(result, callback); + }); + var result = { + close: function () { + watcher.close(); + result.childWatches.forEach(ts.closeFileWatcher); + result = undefined; + }, + dirName: dirName, + childWatches: ts.emptyArray + }; + updateChildWatches(result, callback); + return result; + } + function updateChildWatches(watcher, callback) { + // Iterate through existing children and update the watches if needed + if (watcher) { + watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + } + } + /** + * Watch the directories in the parentDir + */ + function watchChildDirectories(parentDir, existingChildWatches, callback) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(ts.getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + /** + * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list + */ + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(ts.getNormalizedAbsolutePath(childName, parentDir), callback); + addChildDirectoryWatcher(result); + } + /** + * Add child directory watcher to the new ChildDirectoryWatcher list + */ + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -4436,82 +4851,110 @@ var ts; catch (_a) { _crypto = undefined; } - var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } - function createMD5HashUsingNativeCrypto(data) { - var hash = _crypto.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - } - function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - // One file can have multiple watchers - var fileWatcherCallbacks = ts.createMultiMap(); - return { addFile: addFile, removeFile: removeFile }; - function reduceDirWatcherRefCountForFile(fileName) { - var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers.get(dirName); - if (watcher) { - watcher.referenceCount -= 1; - if (watcher.referenceCount <= 0) { - watcher.close(); - dirWatchers.delete(dirName); - } - } - } - function addDirWatcher(dirPath) { - var watcher = dirWatchers.get(dirPath); - if (watcher) { - watcher.referenceCount += 1; - return; - } - watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); - watcher.referenceCount = 1; - dirWatchers.set(dirPath, watcher); - return; - } - function addFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.add(filePath, callback); - } - function addFile(fileName, callback) { - addFileWatcherCallback(fileName, callback); - addDirWatcher(ts.getDirectoryPath(fileName)); - return { fileName: fileName, callback: callback }; - } - function removeFile(watchedFile) { - removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback); - reduceDirWatcherRefCountForFile(watchedFile.fileName); - } - function removeFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.remove(filePath, callback); - } - function fileEventHandler(eventName, relativeFileName, baseDirPath) { - // 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) { - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); - } - } - } - } - } - var watchedFileSet = createWatchedFileSet(); + var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch ( /*ignore*/_a) { /*ignore*/ } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: function (path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + // Could not enable source maps. + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + base64decode: Buffer.from ? function (input) { + return Buffer.from(input, "base64").toString("utf8"); + } : function (input) { + return new Buffer(input, "base64").toString("utf8"); + }, + base64encode: Buffer.from ? function (input) { + return Buffer.from(input).toString("base64"); + } : function (input) { + return new Buffer(input).toString("base64"); + } + }; + return nodeSystem; function isFileSystemCaseSensitive() { // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { @@ -4527,46 +4970,187 @@ var ts; return ch === up ? ch.toLowerCase() : up; }); } - var platform = _os.platform(); - var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + // Use polling interval based on priority when create watch using host.watchFile + return fsWatchFile; + case "DynamicPriorityPolling": + // Use polling interval but change the interval depending on file changes and their default polling interval + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + // Use notifications from FS to watch with falling back to fs.watchFile + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + // Use notifications from FS to watch with falling back to dynamic watch file + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + // Use notifications from FS to watch with falling back to fs.watchFile + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + // Default to do not use polling interval as it is before this experiment branch + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + // 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 fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + filePathComparer: useCaseSensitiveFileNames ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive, + directoryExists: directoryExists, + getAccessileSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + // 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, dirName); + // Some applications save a working file via rename operations + var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } function fsWatchFile(fileName, callback, pollingInterval) { _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; 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) { + // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears) + // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + // Already deleted file, no need to callback again + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + // If there is no change in modified time, ignore the event + else if (+curr.mtime === +prev.mtime) { return; } + else { + // File changed + eventKind = FileWatcherEventKind.Changed; + } callback(fileName, eventKind); } } - function fsWatchDirectory(directoryName, callback, recursive) { + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + // Change + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return 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 ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { var options; - /** Watcher for the directory depending on whether it is missing or present */ - var watcher = !directoryExists(directoryName) ? - watchMissingDirectory() : - watchPresentDirectory(); + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); return { close: function () { - // Close the watcher (either existing directory watcher or missing directory watcher) + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) watcher.close(); + watcher = undefined; } }; /** - * Watch the directory that is currently present - * and when the watched directory is deleted, switch to missing directory watcher + * Invoke the callback with rename and update the watcher if not closed + * @param createWatcher */ - function watchPresentDirectory() { + function invokeCallbackAndUpdateWatcher(createWatcher) { + // Call the callback for current directory + callback("rename", ""); + // If watcher is not closed, update it + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { // 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) { @@ -4577,34 +5161,56 @@ var ts; 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; + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + return watchPresentFileSystemEntryWithFsWatchFile(); + } } /** - * Watch the directory that is missing - * and switch to existing directory when the directory is created + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point */ - function watchMissingDirectory() { - return fsWatchFile(directoryName, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { - watcher.close(); - watcher = watchPresentDirectory(); - // Call the callback for current directory + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + // Call the callback for current file or directory // For now it could be callback for the inner directory creation, // but just return current directory, better than current no-op - callback("rename", ""); + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); } - }); + }, pollingInterval); } } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -4685,11 +5291,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); @@ -4711,110 +5312,27 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } - var nodeSystem = { - clearScreen: function () { - process.stdout.write("\x1Bc"); - }, - args: process.argv.slice(2), - newLine: _os.EOL, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - write: function (s) { - process.stdout.write(s); - }, - readFile: readFile, - writeFile: writeFile, - watchFile: function (fileName, callback, pollingInterval) { - if (useNonPollingWatchers) { - var watchedFile_1 = watchedFileSet.addFile(fileName, callback); - return { - close: function () { return watchedFileSet.removeFile(watchedFile_1); } - }; - } - else { - 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) - 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, - directoryExists: directoryExists, - createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { - _fs.mkdirSync(directoryName); - } - }, - getExecutingFilePath: function () { - return __filename; - }, - getCurrentDirectory: function () { - return process.cwd(); - }, - getDirectories: getDirectories, - getEnvironmentVariable: function (name) { - return process.env[name] || ""; - }, - readDirectory: readDirectory, - getModifiedTime: function (path) { - try { - return _fs.statSync(path).mtime; - } - catch (e) { - return undefined; - } - }, - createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, - getMemoryUsage: function () { - if (global.gc) { - global.gc(); - } - return process.memoryUsage().heapUsed; - }, - getFileSize: function (path) { - try { - var stat = _fs.statSync(path); - if (stat.isFile()) { - return stat.size; - } - } - catch (_a) { } - return 0; - }, - exit: function (exitCode) { - process.exit(exitCode); - }, - realpath: function (path) { - try { - return _fs.realpathSync(path); - } - catch (_a) { - return path; - } - }, - debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), - tryEnableSourceMapsForHost: function () { - try { - require("source-map-support").install(); - } - catch (_a) { - // Could not enable source maps. - } - }, - setTimeout: setTimeout, - clearTimeout: clearTimeout - }; - return nodeSystem; + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -4883,6 +5401,7 @@ var ts; return sys; })(); if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ : 0 /* None */; @@ -5481,6 +6000,7 @@ var ts; Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), 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}'."), @@ -5552,7 +6072,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), 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."), @@ -5592,6 +6112,8 @@ var ts; 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."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), 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."), @@ -5725,7 +6247,7 @@ var ts; Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), - Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), @@ -5769,6 +6291,8 @@ var ts; Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused."), 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."), @@ -5828,6 +6352,7 @@ var ts; 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."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), 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."), @@ -5848,14 +6373,20 @@ var ts; 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"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), 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}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), 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}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{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"), @@ -5892,6 +6423,33 @@ var ts; Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_this_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_this_to_all_unresolved_variables_matching_a_member_name_95037", "Add 'this.' to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), }; })(ts || (ts = {})); /// @@ -7684,6 +8242,13 @@ var ts; return token = 26 /* CommaToken */; case 46 /* dot */: return token = 23 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 13 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { @@ -8020,9 +8585,9 @@ var ts; return false; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; - function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { @@ -8056,18 +8621,15 @@ var ts; ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } - if (nodeIsMissing(node)) { - return ""; - } - var text = sourceFile.text; - return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; - function getTextOfNodeFromSourceText(sourceText, node) { + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8162,8 +8724,7 @@ var ts; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 237 /* ModuleDeclaration */ && - (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { @@ -8194,21 +8755,22 @@ var ts; } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(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 272 /* SourceFile */: return ts.isExternalModule(node.parent); case 238 /* ModuleBlock */: - return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } - ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -8276,6 +8838,10 @@ var ts; } } ts.isAnyImportSyntax = isAnyImportSyntax; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -8339,6 +8905,11 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, startNode.pos); + return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -8686,6 +9257,10 @@ var ts; return false; } ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 231 /* VariableDeclarationList */ && node.parent.parent.kind === 212 /* VariableStatement */; @@ -9123,6 +9698,10 @@ var ts; return isInJavaScriptFile(file); } ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isSourceFileNotJavaScript(file) { + return !isInJavaScriptFile(file); + } + ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { return node && !!(node.flags & 65536 /* JavaScriptFile */); } @@ -9139,7 +9718,7 @@ var ts; (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { if (callExpression.kind !== 185 /* CallExpression */) { return false; } @@ -9151,7 +9730,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 /* StringLiteral */ || arg.kind === 13 /* NoSubstitutionTemplateLiteral */; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -9163,17 +9742,117 @@ var ts; } 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. + * Given the symbol of a declaration, find the symbol of its Javascript container-like initializer, + * if it has one. Otherwise just return the original symbol. + * + * Container-like initializer behave like namespaces, so the binder needs to add contained symbols + * to their exports. An example is a function with assignments to `this` inside. */ - function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 230 /* VariableDeclaration */) { - var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 190 /* FunctionExpression */ || declaration.initializer.kind === 203 /* ClassExpression */); + function getJSInitializerSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return symbol; + } + var declaration = symbol.valueDeclaration; + var e = getDeclaredJavascriptInitializer(declaration) || getAssignedJavascriptInitializer(declaration); + return e && e.symbol ? e.symbol : symbol; + } + ts.getJSInitializerSymbol = getJSInitializerSymbol; + /** Get the declaration initializer, when the initializer is container-like (See getJavascriptInitializer) */ + function getDeclaredJavascriptInitializer(node) { + if (node && ts.isVariableDeclaration(node) && node.initializer) { + return getJavascriptInitializer(node.initializer, /*isPrototypeAssignment*/ false) || + ts.isIdentifier(node.name) && getDefaultedJavascriptInitializer(node.name, node.initializer, /*isPrototypeAssignment*/ false); + } + } + ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + /** + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * We treat the right hand side of assignments with container-like initalizers as declarations. + */ + function getAssignedJavascriptInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + } + ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + /** + * Recognized Javascript container-like initializers are: + * 1. (function() {})() -- IIFEs + * 2. function() { } -- Function expressions + * 3. class { } -- Class expressions + * 4. {} -- Empty object literals + * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` + * + * This function returns the provided initializer, or undefined if it is not valid. + */ + function getJavascriptInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 190 /* FunctionExpression */ || e.kind === 191 /* ArrowFunction */ ? initializer : undefined; + } + if (initializer.kind === 190 /* FunctionExpression */ || initializer.kind === 203 /* ClassExpression */) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getJavascriptInitializer = getJavascriptInitializer; + /** + * A defaulted Javascript initializer matches the pattern + * `Lhs = Lhs || JavascriptInitializer` + * or `var Lhs = Lhs || JavascriptInitializer` + * + * The second Lhs is required to be the same as the first except that it may be prefixed with + * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. + */ + function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ + function getOuterNameOfJsInitializer(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + /** + * Is the 'declared' name the same as the one in the initializer? + * @return true for identical entity names, as well as ones where the initializer is prefixed with + * 'window', 'self' or 'global'. For example: + * + * var my = my || {} + * var min = window.min || {} + * my.app = self.my.app || class { } + */ + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 99 /* ThisKeyword */ || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); } return false; } - ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; function getRightMostAssignedExpression(node) { while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) { node = node.right; @@ -9192,69 +9871,78 @@ var ts; /// 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 */; - } - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || expr.left.kind !== 183 /* PropertyAccessExpression */) { + if (!isInJavaScriptFile(expr) || + expr.operatorToken.kind !== 58 /* EqualsToken */ || + !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } var lhs = expr.left; - if (lhs.expression.kind === 71 /* Identifier */) { - var lhsId = lhs.expression; - if (lhsId.escapedText === "exports") { - // exports.name = expr - return 1 /* ExportsProperty */; - } - else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { - // module.exports = expr - return 2 /* ModuleExports */; - } - else { - // F.x = expr - return 5 /* Property */; - } - } - else if (lhs.expression.kind === 99 /* ThisKeyword */) { + if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (lhs.expression.kind === 183 /* 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 */) { - // module.exports.name = expr - var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { - return 1 /* ExportsProperty */; - } - if (innerPropertyAccess.name.escapedText === "prototype") { - return 3 /* PrototypeProperty */; - } + else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + // module.exports = expr + return 2 /* ModuleExports */; + } + else if (isEntityNameExpression(lhs.expression)) { + if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(expr.right)) { + // F.prototype = { ... } + return 6 /* Prototype */; } + else if (isPrototypeAccess(lhs.expression)) { + // F.G....prototype.x = expr + return 3 /* PrototypeProperty */; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + // exports.name = expr OR module.exports.name = expr + return 1 /* ExportsProperty */; + } + // F.G...x = expr + return 5 /* Property */; } return 0 /* None */; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && expr.parent && expr.parent.kind === 214 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function importFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + return node.parent; + case 252 /* ExternalModuleReference */: + return node.parent.parent; + case 185 /* CallExpression */: + return node.parent; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(node)); + } + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; function getExternalModuleName(node) { - if (node.kind === 242 /* ImportDeclaration */) { - return node.moduleSpecifier; - } - if (node.kind === 241 /* ImportEqualsDeclaration */) { - var reference = node.moduleReference; - if (reference.kind === 252 /* ExternalModuleReference */) { - return reference.expression; - } - } - if (node.kind === 248 /* ExportDeclaration */) { - return node.moduleSpecifier; - } - if (isModuleWithStringLiteralName(node)) { - return node.name; + switch (node.kind) { + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + return node.moduleSpecifier; + case 241 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 252 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + default: + return ts.Debug.assertNever(node); } } ts.getExternalModuleName = getExternalModuleName; @@ -9304,6 +9992,14 @@ var ts; node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 54 /* BarBarToken */ && + node.expression.right.right; + } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { case 212 /* VariableStatement */: @@ -9343,7 +10039,8 @@ var ts; (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node) { + if (parent && parent.parent && parent.parent.parent && + (getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || @@ -9382,7 +10079,8 @@ var ts; ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { var host = getJSDocHost(node); - var decl = getSourceOfAssignment(host) || + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || @@ -9407,7 +10105,7 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined; + return node.dotDotDotToken !== undefined || node.type && node.type.kind === 281 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9492,6 +10190,10 @@ var ts; return false; } ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -9506,6 +10208,13 @@ var ts; return walkUp(node, 189 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 189 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 183 /* PropertyAccessExpression */ && node.kind !== 184 /* ElementAccessExpression */) { @@ -9524,16 +10233,9 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - // True if the given identifier, string literal, or number literal is the name of a declaration node + // True if `name` is the name of a declaration node function isDeclarationName(name) { - switch (name.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - return ts.isDeclaration(name.parent) && name.parent.name === name; - default: - return false; - } + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; // See GH#16030 @@ -9626,6 +10328,13 @@ var ts; return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; @@ -9660,38 +10369,6 @@ var ts; return undefined; } ts.getAncestor = getAncestor; - function getFileReferenceFromReferencePath(comment, commentRange) { - var simpleReferenceRegEx = /^\/\/\/\s*= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode) + return "\\x00"; + } + // Otherwise, keep printing a literal \0 for the null character + return "\\0"; + } return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { @@ -10468,49 +11151,38 @@ 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, checkJSDoc) { - if (ts.hasType(node)) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocType(node); - } + function getEffectiveTypeAnnotationNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; /** * 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 (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocReturnType(node); - } + function getEffectiveReturnTypeNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; /** * 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 (checkJSDoc || isInJavaScriptFile(node)) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; - } + function getEffectiveTypeParameterDeclarations(node) { + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getJSDocTypeParameterDeclarations(node) { + var templateTag = ts.getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** * 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) { + function getEffectiveSetAccessorTypeAnnotationNode(node) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); + return parameter && getEffectiveTypeAnnotationNode(parameter); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -10614,7 +11286,7 @@ var ts; } return currentDetachedCommentInfo; function isPinnedCommentLocal(comment) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } ts.emitDetachedComments = emitDetachedComments; @@ -10815,10 +11487,17 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 183 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node) || (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node); @@ -10855,7 +11534,7 @@ var ts; var length = input.length; for (var i = 0; i < length; i++) { var charCode = input.charCodeAt(i); - // handel utf8 + // handle utf8 if (charCode < 0x80) { output.push(charCode); } @@ -10912,6 +11591,78 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11231,6 +11982,7 @@ var ts; map.delete(key); onDeleteValue(existingValue, key); } + // If present notify about existing values else if (onExistingValue) { onExistingValue(existingValue, valueInNewMap, key); } @@ -11292,6 +12044,42 @@ var ts; return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + /** Add a value to a set, and return true if it wasn't already present. */ + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11327,27 +12115,20 @@ var ts; } ts.textSpanContainsTextSpan = textSpanContainsTextSpan; function textSpanOverlapsWith(span, other) { - var overlapStart = Math.max(span.start, other.start); - var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); - return overlapStart < overlapEnd; + return textSpanOverlap(span, other) !== undefined; } ts.textSpanOverlapsWith = textSpanOverlapsWith; function textSpanOverlap(span1, span2) { - var overlapStart = Math.max(span1.start, span2.start); - var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (overlapStart < overlapEnd) { - return createTextSpanFromBounds(overlapStart, overlapEnd); - } - return undefined; + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; } ts.textSpanOverlap = textSpanOverlap; function textSpanIntersectsWithTextSpan(span, other) { - return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); } ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; function textSpanIntersectsWith(span, start, length) { - var end = start + length; - return start <= textSpanEnd(span) && end >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); } ts.textSpanIntersectsWith = textSpanIntersectsWith; function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { @@ -11361,12 +12142,9 @@ var ts; } ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; function textSpanIntersection(span1, span2) { - var intersectStart = Math.max(span1.start, span2.start); - var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (intersectStart <= intersectEnd) { - return createTextSpanFromBounds(intersectStart, intersectEnd); - } - return undefined; + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; } ts.textSpanIntersection = textSpanIntersection; function createTextSpan(start, length) { @@ -11379,6 +12157,13 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; + /* @internal */ + function createTextRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos); + return { pos: pos, end: end }; + } + ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11631,6 +12416,7 @@ var ts; return false; } try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } catch (e) { @@ -11757,6 +12543,11 @@ var ts; return declaration.name || nameForNamelessJSDocTypedef(declaration); } ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + /** @internal */ + function isNamedDeclaration(node) { + return !!node.name; // A 'name' property should always be a DeclarationName. + } + ts.isNamedDeclaration = isNamedDeclaration; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -11813,7 +12604,7 @@ var ts; 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; + return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; /** @@ -11823,33 +12614,33 @@ var ts; * for example on a variable declaration whose initializer is a function expression. */ function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 287 /* JSDocParameterTag */); + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } ts.hasJSDocParameterTags = hasJSDocParameterTags; /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 286 /* JSDocClassTag */); + return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 288 /* JSDocReturnTag */); + return getFirstJSDocTag(node, ts.isJSDocReturnTag); } ts.getJSDocReturnTag = getJSDocReturnTag; /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 290 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); } 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, 289 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -11868,12 +12659,9 @@ var ts; * tag directly on the node would be returned. */ function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 289 /* JSDocTypeTag */); - if (!tag && node.kind === 148 /* Parameter */) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); } return tag && tag.typeExpression && tag.typeExpression.type; } @@ -11900,14 +12688,12 @@ var ts; } 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; }); + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); } /** 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; }); + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); @@ -12533,6 +13319,10 @@ var ts; return node.kind === 285 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 286 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { return node.kind === 287 /* JSDocParameterTag */; } @@ -12654,6 +13444,16 @@ var ts; return false; } ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { return isModifierKind(node.kind); } @@ -12958,7 +13758,7 @@ var ts; case 97 /* SuperKeyword */: case 207 /* NonNullExpression */: case 208 /* MetaProperty */: - case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression + case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: return false; @@ -13043,7 +13843,6 @@ var ts; || isPartiallyEmittedExpression(node); } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; - // Statement function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { case 218 /* ForStatement */: @@ -13317,6 +14116,45 @@ var ts; return !!node.type; } ts.hasType = hasType; + /* True if the node could have a type node a `.type` */ + /* @internal */ + function couldHaveType(node) { + switch (node.kind) { + case 148 /* Parameter */: + case 150 /* PropertySignature */: + case 151 /* PropertyDeclaration */: + case 152 /* MethodSignature */: + case 153 /* MethodDeclaration */: + case 154 /* Constructor */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + case 157 /* CallSignature */: + case 158 /* ConstructSignature */: + case 159 /* IndexSignature */: + case 160 /* TypePredicate */: + case 162 /* FunctionType */: + case 163 /* ConstructorType */: + case 172 /* ParenthesizedType */: + case 174 /* TypeOperator */: + case 176 /* MappedType */: + case 188 /* TypeAssertionExpression */: + case 190 /* FunctionExpression */: + case 191 /* ArrowFunction */: + case 206 /* AsExpression */: + case 230 /* VariableDeclaration */: + case 232 /* FunctionDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 274 /* JSDocTypeExpression */: + case 277 /* JSDocNullableType */: + case 278 /* JSDocNonNullableType */: + case 279 /* JSDocOptionalType */: + case 280 /* JSDocFunctionType */: + case 281 /* JSDocVariadicType */: + return true; + } + return false; + } + ts.couldHaveType = couldHaveType; /** True if has initializer node attached to it. */ /* @internal */ function hasInitializer(node) { @@ -13349,6 +14187,31 @@ var ts; return node.kind === 161 /* TypeReference */ || node.kind === 205 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; } @@ -13406,6 +14269,13 @@ var ts; } } } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; /** * 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, @@ -13774,6 +14644,7 @@ var ts; case 254 /* JsxSelfClosingElement */: case 255 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); case 261 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); @@ -14099,7 +14970,9 @@ var ts; sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); - processReferenceComments(sourceFile); + // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); ts.Debug.assert(token() === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); @@ -14112,6 +14985,9 @@ var ts; fixupParentReferences(sourceFile); } return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } } function addJSDocComment(node) { var comments = ts.getJSDocCommentRanges(node, sourceFile.text); @@ -14262,9 +15138,7 @@ var ts; return inContext(16384 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), 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. @@ -14276,9 +15150,14 @@ var ts; // node we finish so that it can't be reused incrementally. parseErrorBeforeNextFinishedNode = true; } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); + parseErrorAtPosition(scanner.getTextPos(), length, message); } function getNodePos() { return scanner.getStartPos(); @@ -14560,25 +15439,26 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76 /* ConstKeyword */) { - // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; + switch (token()) { + case 76 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 83 /* EnumKeyword */; + case 84 /* ExportKeyword */: + nextToken(); + if (token() === 79 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); + case 79 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 115 /* StaticKeyword */: + case 125 /* GetKeyword */: + case 136 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === 84 /* ExportKeyword */) { - nextToken(); - if (token() === 79 /* DefaultKeyword */) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - } - if (token() === 79 /* DefaultKeyword */) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === 115 /* StaticKeyword */) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); @@ -15303,9 +16183,20 @@ var ts; nextToken(); return finishNode(node); } - function parseJSDocAllType() { + function parseJSDocAllType(postFixEquals) { var result = createNode(275 /* JSDocAllType */); + if (postFixEquals) { + return createJSDocPostfixType(279 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(278 /* JSDocNonNullableType */); nextToken(); + result.type = parseNonArrayType(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { @@ -15353,14 +16244,21 @@ var ts; parameter.name = parseIdentifierName(); parseExpected(56 /* ColonToken */); } - parameter.type = parseType(); + parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocNodeWithType(kind) { - var result = createNode(kind); - nextToken(); - result.type = parseNonArrayType(); - return finishNode(result); + function parseJSDocType() { + var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + var type = parseType(); + if (dotdotdot) { + var variadic = createNode(281 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 58 /* EqualsToken */) { + return createJSDocPostfixType(279 /* JSDocOptionalType */, type); + } + return type; } function parseTypeQuery() { var node = createNode(164 /* TypeQuery */); @@ -15767,13 +16665,15 @@ var ts; // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 39 /* AsteriskToken */: - return parseJSDocAllType(); + return parseJSDocAllType(/*postfixEquals*/ false); + case 61 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); case 55 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); case 89 /* FunctionKeyword */: return parseJSDocFunctionType(); case 51 /* ExclamationToken */: - return parseJSDocNodeWithType(278 /* JSDocNonNullableType */); + return parseJSDocNonNullableType(); case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -15855,13 +16755,6 @@ var ts; var type = parseNonArrayType(); 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(279 /* JSDocOptionalType */, type); - break; case 51 /* ExclamationToken */: type = createJSDocPostfixType(278 /* JSDocNonNullableType */, type); break; @@ -15923,12 +16816,6 @@ var ts; return parseTypeOperator(operator); case 126 /* InferKeyword */: return parseInferType(); - case 24 /* DotDotDotToken */: { - var result = createNode(281 /* JSDocVariadicType */); - nextToken(); - result.type = parsePostfixTypeOrHigher(); - return finishNode(result); - } } return parsePostfixTypeOrHigher(); } @@ -16542,7 +17429,7 @@ var ts; // 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 newPrecedence = ts.getBinaryOperatorPrecedence(token()); // 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 @@ -16597,50 +17484,7 @@ var ts; if (inDisallowInContext() && token() === 92 /* InKeyword */) { return false; } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54 /* BarBarToken */: - return 1; - case 53 /* AmpersandAmpersandToken */: - return 2; - case 49 /* BarToken */: - return 3; - case 50 /* CaretToken */: - return 4; - case 48 /* AmpersandToken */: - return 5; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 6; - 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 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 8; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 9; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 10; - case 40 /* AsteriskAsteriskToken */: - return 11; - } - // -1 is lower than all other precedences. Returning it will cause binary expression - // parsing to stop. - return -1; + return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { var node = createNode(198 /* BinaryExpression */, left.pos); @@ -16716,7 +17560,7 @@ var ts; if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); return token() === 40 /* AsteriskAsteriskToken */ ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } /** @@ -16733,12 +17577,13 @@ var ts; var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40 /* AsteriskAsteriskToken */) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; if (simpleUnaryExpression.kind === 188 /* 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); + parseErrorAt(pos, end, 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 { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; @@ -16990,7 +17835,7 @@ var ts; 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)); + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } @@ -17034,8 +17879,21 @@ var ts; currentToken = scanner.scanJsxToken(); return finishNode(node); } - function parseJsxChild() { - switch (token()) { + function parseJsxChild(openingTag, token) { + switch (token) { + case 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)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 28 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; case 10 /* JsxText */: case 11 /* JsxTextAllWhiteSpaces */: return parseJsxText(); @@ -17043,8 +17901,9 @@ var ts; return parseJsxExpression(/*inExpressionContext*/ false); case 27 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); } - ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTag) { var list = []; @@ -17052,30 +17911,10 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28 /* LessThanSlashToken */) { - // Closing tag + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; - } - 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 /* ConflictMarkerTrivia */) { - break; - } - var child = parseJsxChild(); - if (child) { - list.push(child); - } + list.push(child); } parsingContext = saveParsingContext; return createNodeArray(list, listPos); @@ -17089,11 +17928,13 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(27 /* LessThanToken */); if (token() === 29 /* GreaterThanToken */) { - parseExpected(29 /* GreaterThanToken */); + // See below for explanation of scanJsxText var node_1 = createNode(258 /* JsxOpeningFragment */, fullStart); + scanJsxText(); return finishNode(node_1); } var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; if (token() === 29 /* GreaterThanToken */) { @@ -17115,6 +17956,7 @@ var ts; node = createNode(254 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; + node.typeArguments = typeArguments; node.attributes = attributes; return finishNode(node); } @@ -17137,7 +17979,9 @@ var ts; } function parseJsxExpression(inExpressionContext) { var node = createNode(263 /* JsxExpression */); - parseExpected(17 /* OpenBraceToken */); + if (!parseExpected(17 /* OpenBraceToken */)) { + return undefined; + } if (token() !== 18 /* CloseBraceToken */) { node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); @@ -17195,8 +18039,7 @@ var ts; var node = createNode(259 /* 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); + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { parseExpected(29 /* GreaterThanToken */); @@ -17332,7 +18175,7 @@ var ts; case 48 /* AmpersandToken */: // foo & case 49 /* BarToken */: // foo | case 18 /* CloseBraceToken */: // foo } - case 1 /* EndOfFileToken */:// 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. @@ -17601,7 +18444,7 @@ var ts; parseExpected(88 /* ForKeyword */); var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); parseExpected(19 /* OpenParenToken */); - var initializer = undefined; + var initializer; if (token() !== 25 /* SemicolonToken */) { if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); @@ -18244,18 +19087,6 @@ var ts; node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } function isClassMemberStart() { var idToken; if (token() === 57 /* AtToken */) { @@ -18270,7 +19101,7 @@ var ts; // 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)) { + if (ts.isClassMemberModifier(idToken)) { return true; } nextToken(); @@ -18302,7 +19133,7 @@ var ts; case 51 /* ExclamationToken */: // Non-null assertion on property name 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. + case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -18617,7 +19448,7 @@ var ts; // import ModuleSpecifier; if (identifier || // import id token() === 39 /* AsteriskToken */ || // import * - token() === 17 /* OpenBraceToken */) { + token() === 17 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); parseExpected(142 /* FromKeyword */); } @@ -18731,8 +19562,7 @@ var ts; node.name = identifierName; } if (kind === 246 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - // Report error identifier expected - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } @@ -18767,87 +19597,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function processReferenceComments(sourceFile) { - 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 /* SingleLineCommentTrivia */) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*= pos_2); pos_2 = child.end; - }); + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); ts.Debug.assert(pos_2 <= node.end); } } @@ -19806,6 +20560,12 @@ var ts; // Adjust the pos or end (or both) of the intersecting element accordingly. adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } @@ -19870,15 +20630,15 @@ var ts; var lastNodeEntirelyBeforePosition; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } } return bestResult; - function getLastChild(node) { + function getLastDescendant(node) { while (true) { - var lastChild = getLastChildWorker(node); + var lastChild = ts.getLastChild(node); if (lastChild) { node = lastChild; } @@ -19887,15 +20647,6 @@ var ts; } } } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } function visit(child) { if (ts.nodeIsMissing(child)) { // Missing nodes are effectively invisible to us. We never even consider them @@ -20060,6 +20811,209 @@ var ts; function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + /*@internal*/ + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var pragmas = []; + // 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 (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + /*@internal*/ + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to + // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { + var _b = _a.arguments, name = _b.name, path = _b.path; + return ({ name: name, path: path }); + }); + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + // TODO: It's probably fine to issue this diagnostic on all instances of the pragma + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + // _last_ of either nocheck or check in a file is the "winner" + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; // Accessed directly + default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; // Missing required argument, don't parse + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; // Split on spaces and match up positionally with definition + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; // Missing required argument, fail to parse it + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } })(ts || (ts = {})); /// /// @@ -20153,7 +21107,6 @@ var ts; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; - ContainerFlags[ContainerFlags["IsInferenceContainer"] = 256] = "IsInferenceContainer"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -20169,8 +21122,8 @@ var ts; var languageVersion; var parent; var container; + var thisParentContainer; // Container one level up var blockScopeContainer; - var inferenceContainer; var lastContainer; var seenThisKeyword; // state used by control flow analysis @@ -20225,8 +21178,8 @@ var ts; languageVersion = undefined; parent = undefined; container = undefined; + thisParentContainer = undefined; blockScopeContainer = undefined; - inferenceContainer = undefined; lastContainer = undefined; seenThisKeyword = false; currentFlow = undefined; @@ -20257,19 +21210,14 @@ var ts; function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = [node]; - } - else { - symbol.declarations.push(node); - } + symbol.declarations = ts.append(symbol.declarations, node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 107455 /* Value */) { + if (symbolFlags & 67216319 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 237 /* ModuleDeclaration */)) { @@ -20299,7 +21247,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } - return ts.getEscapedTextOfIdentifierOrLiteral(name); + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { case 154 /* Constructor */: @@ -20329,7 +21277,7 @@ var ts; case 148 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 280 /* JSDocFunctionType */); + ts.Debug.assert(node.parent.kind === 280 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -20339,7 +21287,7 @@ var ts; } } function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? 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. @@ -20402,7 +21350,7 @@ var ts; symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } else { - if (node.name) { + if (ts.isNamedDeclaration(node)) { node.name.parent = node; } // Report errors every position with duplicate declaration @@ -20440,7 +21388,12 @@ var ts; } } addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { @@ -20472,7 +21425,7 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. var isJSDocTypedefInJSDocNamespace = ts.isJSDocTypedefTag(node) && node.name && node.name.kind === 71 /* Identifier */ && node.name.isInJSDocNamespace; if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67216319 /* 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; @@ -20491,11 +21444,12 @@ var ts; // and block-container. Then after we pop out of processing the children, we restore // these saved values. var saveContainer = container; + var saveThisParentContainer = thisParentContainer; var savedBlockScopeContainer = blockScopeContainer; // 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 + // may contain locals, we eagerly 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). // @@ -20510,6 +21464,9 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 191 /* ArrowFunction */) { + thisParentContainer = container; + } container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { container.locals = ts.createSymbolTable(); @@ -20575,17 +21532,11 @@ var ts; bindChildren(node); node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; } - else if (containerFlags & 256 /* IsInferenceContainer */) { - var saveInferenceContainer = inferenceContainer; - inferenceContainer = node; - node.locals = undefined; - bindChildren(node); - inferenceContainer = saveInferenceContainer; - } else { bindChildren(node); } container = saveContainer; + thisParentContainer = saveThisParentContainer; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { @@ -20605,12 +21556,17 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } - function bindEach(nodes) { + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 232 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 232 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } if (nodes === undefined) { return; } if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); + ts.forEach(nodes, bindFunction); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -20618,7 +21574,7 @@ var ts; var nodeArrayFlags = 0 /* None */; for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { var node = nodes_2[_i]; - bind(node); + bindFunction(node); nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; } nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; @@ -20717,6 +21673,15 @@ var ts; case 291 /* JSDocTypedefTag */: bindJSDocTypedefTag(node); break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 272 /* SourceFile */: + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + case 211 /* Block */: + case 238 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; default: bindEachChild(node); break; @@ -21379,8 +22344,6 @@ var ts; case 235 /* TypeAliasDeclaration */: case 176 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 170 /* ConditionalType */: - return 256 /* IsInferenceContainer */; case 272 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; case 153 /* MethodDeclaration */: @@ -21529,7 +22492,7 @@ var ts; 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)) { + if (ts.isModuleAugmentationExternal(node)) { declareModuleSymbol(node); } else { @@ -21543,10 +22506,8 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } else { @@ -21565,7 +22526,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -21613,8 +22574,8 @@ var ts; continue; } 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)); + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -21653,7 +22614,7 @@ var ts; } } function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* 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. @@ -21699,8 +22660,8 @@ var ts; 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)); + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -21712,8 +22673,8 @@ var ts; 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.idText(identifier))); + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -21876,7 +22837,7 @@ 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); + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, 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'"; @@ -21893,7 +22854,7 @@ var ts; while (parentNode && parentNode.kind !== 291 /* JSDocTypedefTag */) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); break; } // falls through @@ -21920,13 +22881,16 @@ var ts; bindModuleExportsAssignment(node); break; case 3 /* PrototypeProperty */: - bindPrototypePropertyAssignment(node); + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); break; case 4 /* ThisProperty */: bindThisPropertyAssignment(node); break; case 5 /* Property */: - bindStaticPropertyAssignment(node); + bindSpecialPropertyAssignment(node); break; case 0 /* None */: // Nothing to do @@ -21951,7 +22915,7 @@ var ts; seenThisKeyword = true; return; case 160 /* TypePredicate */: - return checkTypePredicate(node); + break; // Binding the children will handle everything case 147 /* TypeParameter */: return bindTypeParameter(node); case 148 /* Parameter */: @@ -21968,7 +22932,7 @@ var ts; case 269 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 271 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); case 157 /* CallSignature */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: @@ -21979,15 +22943,15 @@ var ts; // 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 */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); case 232 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 154 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 155 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); case 156 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); case 162 /* FunctionType */: case 280 /* JSDocFunctionType */: case 163 /* ConstructorType */: @@ -22013,9 +22977,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 234 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); case 235 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); case 236 /* EnumDeclaration */: return bindEnumDeclaration(node); case 237 /* ModuleDeclaration */: @@ -22063,7 +23027,7 @@ var ts; case 291 /* JSDocTypedefTag */: { var fullName = node.fullName; if (!fullName || fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); } break; } @@ -22075,16 +23039,6 @@ var ts; function bindAnonymousTypeWorker(node) { return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71 /* Identifier */) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 173 /* ThisType */) { - seenThisKeyword = true; - } - bind(type); - } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -22159,7 +23113,18 @@ var ts; // 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 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, function (id, original) { + if (!original) { + return undefined; + } + var s = ts.getJSInitializerSymbol(original); + addDeclarationToSymbol(s, id, 1536 /* Module */ | 67108864 /* JSContainer */); + return s; + }); + if (symbol) { + declareSymbol(symbol.exports, symbol, lhs, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + } } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' @@ -22178,14 +23143,24 @@ var ts; } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - switch (container.kind) { + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { case 232 /* FunctionDeclaration */: case 190 /* 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 */); + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = getJSInitializerSymbolFromName(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } break; case 154 /* Constructor */: case 151 /* PropertyDeclaration */: @@ -22194,111 +23169,145 @@ var ts; case 156 /* 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 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; + case 272 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); } } 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 === 183 /* PropertyAccessExpression */) && - node.parent.parent.kind === 272 /* SourceFile */) { - bindStaticPropertyAssignment(node); + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 272 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + 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, /*isPrototypeProperty*/ true); + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); } /** - * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function or class, or not declared. + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; */ function bindStaticPropertyAssignment(node) { - // Look up the function in the local scope, since static assignments should - // follow the function declaration - var leftSideOfAssignment = node.kind === 183 /* PropertyAccessExpression */ ? node : node.left; - var target = leftSideOfAssignment.expression; - 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 === 198 /* BinaryExpression */) { - leftSideOfAssignment.parent = node; - } - if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, 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); - } - } + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function lookupSymbolForName(name) { - return lookupSymbolForNameWorker(container, name); + function getJSInitializerSymbolFromName(name, lookupContainer) { + return ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(name, lookupContainer)); } - 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 === 198 /* BinaryExpression */ || propertyAccess.parent.kind === 214 /* ExpressionStatement */); - var isLegalPosition; - if (propertyAccess.parent.kind === 198 /* BinaryExpression */) { - var initializerKind = propertyAccess.parent.right.kind; - isLegalPosition = (initializerKind === 203 /* ClassExpression */ || initializerKind === 190 /* FunctionExpression */) && - propertyAccess.parent.parent.parent.kind === 272 /* SourceFile */; + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var symbol = getJSInitializerSymbolFromName(name); + var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) + ? propertyAccess.parent.parent.parent.kind === 272 /* SourceFile */ && + !!ts.getJavascriptInitializer(propertyAccess.parent.right, ts.isPrototypeAccess(propertyAccess.parent.left)) + : propertyAccess.parent.parent.kind === 272 /* SourceFile */; + if (!isPrototypeProperty && (!symbol || !(symbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; + var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + forEachIdentifierInEntityName(propertyAccess.expression, function (id, original) { + if (original) { + // Note: add declaration to original symbol, not the special-syntax's symbol, so that namespaces work for type lookup + addDeclarationToSymbol(original, id, flags_1); + return original; + } + else { + return symbol = declareSymbol(symbol ? symbol.exports : container.locals, symbol, id, flags_1, excludeFlags_1); + } + }); } - else { - isLegalPosition = propertyAccess.parent.parent.kind === 272 /* 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 */ | 1024 /* NamespaceModule */))) { + if (!symbol || !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */ | 4096 /* ObjectLiteral */))) { 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())); + (symbol.members || (symbol.members = ts.createSymbolTable())) : + (symbol.exports || (symbol.exports = ts.createSymbolTable())); // Declare the method/property - declareSymbol(symbolTable, targetSymbol, propertyAccess, 4 /* Property */, 0 /* PropertyExcludes */); + var symbolFlags = 4 /* Property */ | (isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); + var symbolExcludes = 0 /* PropertyExcludes */ & ~(isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); + declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(node.expression)); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e)); + } + else { + var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); + ts.Debug.assert(!!s && !!s.exports); + return action(e.name, s.exports.get(e.name.escapedText)); + } } function bindCallExpression(node) { // 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)) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { setCommonJsModuleIndicator(node); } } function bindClassLikeDeclaration(node) { if (node.kind === 233 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; @@ -22331,8 +23340,8 @@ var ts; } function bindEnumDeclaration(node) { return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) - : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); } function bindVariableDeclarationOrBindingElement(node) { if (inStrictMode) { @@ -22352,10 +23361,10 @@ var ts; // 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 */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); } } } @@ -22369,7 +23378,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -22387,10 +23396,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -22417,20 +23426,31 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + function getInferTypeContainer(node) { + while (node) { + var parent_2 = node.parent; + if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) { + return parent_2; + } + node = parent_2; + } + return undefined; + } function bindTypeParameter(node) { if (node.parent.kind === 171 /* InferType */) { - if (inferenceContainer) { - if (!inferenceContainer.locals) { - inferenceContainer.locals = ts.createSymbolTable(); + var container_1 = getInferTypeContainer(node.parent); + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); } - declareSymbol(inferenceContainer.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } } // reachability checks @@ -22490,7 +23510,7 @@ var ts; } function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { return isExportsOrModuleExportsOrAlias(sourceFile, node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); } function lookupSymbolForNameWorker(container, name) { var local = container.locals && container.locals.get(name); @@ -23757,8 +24777,11 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createMap(); - var moduleNameToDirectoryMap = ts.createMap(); + return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + /*@internal*/ + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); @@ -23842,7 +24865,7 @@ var ts; } } } - ts.createModuleResolutionCache = createModuleResolutionCache; + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -23853,7 +24876,7 @@ var ts; var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } } else { @@ -24043,7 +25066,7 @@ var ts; 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; + var matchedPattern; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); @@ -24319,7 +25342,7 @@ var ts; var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = readJson(packageJsonPath, host); - if (subModuleName === "") { + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); if (typeof path === "string") { subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); @@ -24415,7 +25438,7 @@ var ts; } else { var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { + if (rest !== "") { // If "rest" is empty, we just did this search above. 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; @@ -24445,7 +25468,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -24492,6 +25515,7 @@ var ts; return "@types/" + getMangledNameForScopedPackage(packageName); } ts.getTypesPackageName = getTypesPackageName; + /* @internal */ function getMangledNameForScopedPackage(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); @@ -24501,6 +25525,7 @@ var ts; } return packageName; } + ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); @@ -24517,12 +25542,13 @@ var ts; typesPackageName; } ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { var result = cache && cache.get(containingDirectory); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } + failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } @@ -24543,7 +25569,7 @@ var ts; if (!ts.isExternalModuleNameRelative(moduleName)) { // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -24828,7 +25854,7 @@ var ts; node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (node) { node = ts.getParseTreeNode(node, ts.isParameter); return node ? isOptionalParameter(node) : false; @@ -24867,7 +25893,7 @@ var ts; resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, @@ -24879,13 +25905,13 @@ var ts; node = ts.getParseTreeNode(node, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, + getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; }, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); - var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -24954,6 +25980,7 @@ var ts; var anyArrayType; var autoArrayType; var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; // 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 @@ -24970,11 +25997,9 @@ var ts; var deferredGlobalAsyncIteratorType; var deferredGlobalAsyncIterableIteratorType; var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; var deferredNodes; var deferredUnusedIdentifierNodes; + var seenDeferredUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -24999,6 +26024,19 @@ var ts; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); + // Suggestion diagnostics must have a file. Keyed by source file name. + var suggestionDiagnostics = ts.createMultiMap(); + function addSuggestionDiagnostic(diag) { + suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + function addErrorOrSuggestionDiagnostic(isError, diag) { + if (isError) { + diagnostics.add(diag); + } + else { + addSuggestionDiagnostic(diag); + } + } var TypeFacts; (function (TypeFacts) { TypeFacts[TypeFacts["None"] = 0] = "None"; @@ -25024,8 +26062,7 @@ var ts; 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["All"] = 4194303] = "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. @@ -25055,10 +26092,10 @@ var ts; 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["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); @@ -25090,12 +26127,6 @@ var ts; var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - /** Things we lazy load from the JSX namespace */ - var jsxTypes = ts.createUnderscoreEscapedMap(); var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var definitelyAssignableRelation = ts.createMap(); @@ -25151,6 +26182,7 @@ var ts; TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType"; TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject"; TypeIncludes[TypeIncludes["Union"] = 2048] = "Union"; + TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard"; })(TypeIncludes || (TypeIncludes = {})); var MembersOrExportsResolutionKind; (function (MembersOrExportsResolutionKind) { @@ -25298,7 +26330,23 @@ var ts; }; } } - function getJsxNamespace() { + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } if (!_jsxNamespace) { _jsxNamespace = "React"; if (compilerOptions.jsxFactory) { @@ -25337,35 +26385,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 107455 /* BlockScopedVariableExcludes */; + result |= 67216319 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 107454 /* FunctionScopedVariableExcludes */; + result |= 67216318 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; + result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 106927 /* FunctionExcludes */; + result |= 67215791 /* FunctionExcludes */; if (flags & 32 /* Class */) - result |= 899519 /* ClassExcludes */; + result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 792968 /* InterfaceExcludes */; + result |= 67901832 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) - result |= 899327 /* RegularEnumExcludes */; + result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) - result |= 899967 /* ConstEnumExcludes */; + result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 106639 /* ValueModuleExcludes */; + result |= 67215503 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 99263 /* MethodExcludes */; + result |= 67208127 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 41919 /* GetAccessorExcludes */; + result |= 67150783 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 74687 /* SetAccessorExcludes */; + result |= 67183551 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 530920 /* TypeParameterExcludes */; + result |= 67639784 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 793064 /* TypeAliasExcludes */; + result |= 67901928 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -25394,7 +26442,7 @@ var ts; } function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - source.flags & 67108864 /* JSContainer */ || target.flags & 67108864 /* JSContainer */) { + (source.flags | 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 @@ -25418,6 +26466,13 @@ var ts; target.exports = ts.createSymbolTable(); mergeSymbolTable(target.exports, source.exports); } + if ((source.flags | target.flags) & 67108864 /* JSContainer */) { + var sourceInitializer = ts.getJSInitializerSymbol(source); + var targetInitializer = ts.getJSInitializerSymbol(target); + if (sourceInitializer !== source || targetInitializer !== target) { + mergeSymbol(targetInitializer, sourceInitializer); + } + } recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { @@ -25430,10 +26485,12 @@ var ts; ? 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)); + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); } } @@ -25554,8 +26611,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -25691,7 +26748,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -25700,7 +26757,7 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + if (meaning & 67216319 /* 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 @@ -25708,7 +26765,7 @@ var ts; useResult = lastLocation.kind === 148 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 148 /* Parameter */); + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } else if (location.kind === 170 /* ConditionalType */) { @@ -25780,7 +26837,7 @@ var ts; 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 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -25790,7 +26847,7 @@ var ts; case 233 /* ClassDeclaration */: case 203 /* ClassExpression */: case 234 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064 /* Type */)) { + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -25817,7 +26874,7 @@ var ts; // 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 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -25837,7 +26894,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 234 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -25959,14 +27016,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // 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 */) { + if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 240 /* 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)); @@ -25982,7 +27039,7 @@ var ts; case 234 /* InterfaceDeclaration */: case 236 /* EnumDeclaration */: case 235 /* TypeAliasDeclaration */: - case 237 /* ModuleDeclaration */:// For `namespace N { N; }` + case 237 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -26059,8 +27116,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~1920 /* Namespace */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -26079,12 +27137,12 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67216319 /* 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 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* 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; @@ -26093,15 +27151,15 @@ var ts; return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - 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 (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* 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 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* 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; @@ -26162,14 +27220,18 @@ var ts; ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */)); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { 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, "default" /* Default */, dontResolveAlias)) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); + if (defaultExportSymbol && defaultExportSymbol.valueDeclaration && isSyntacticDefault(defaultExportSymbol.valueDeclaration)) { 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 @@ -26206,7 +27268,7 @@ var ts; if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && hasSyntheticDefault) { + else if (hasSyntheticDefault) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -26239,7 +27301,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -26294,7 +27356,15 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + var moduleName = getFullyQualifiedName(moduleSymbol); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } return symbol; } @@ -26312,7 +27382,7 @@ var ts; resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(node.expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { @@ -26325,7 +27395,7 @@ var ts; case 246 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 250 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 247 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 240 /* NamespaceExportDeclaration */: @@ -26336,7 +27406,7 @@ var ts; * 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 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } return symbol && (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */; } function resolveSymbol(symbol, dontResolveAlias) { @@ -26368,7 +27438,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -26416,7 +27486,7 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 241 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -26429,39 +27499,43 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === namespaceMeaning ? 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 === 145 /* QualifiedName */ || name.kind === 183 /* PropertyAccessExpression */) { - var left = void 0; - if (name.kind === 145 /* QualifiedName */) { - left = name.left; - } - else if (name.kind === 183 /* PropertyAccessExpression */) { - 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 left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); + var namespace = resolveEntityName(left, namespaceMeaning, 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); + if (ts.isInJavaScriptFile(name)) { + var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + if (initializer) { + namespace = getSymbolOfNode(initializer); + } + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { @@ -26505,6 +27579,9 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); } @@ -26526,10 +27603,8 @@ var ts; 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.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + else { + addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); } // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. return undefined; @@ -26552,6 +27627,12 @@ var ts; } return undefined; } + function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = packageId && ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)); + return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } // 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) { @@ -26727,7 +27808,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); + return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -26827,13 +27908,21 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // 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 */; + return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { return undefined; } - var visitedSymbolTables = []; + var id = "" + getSymbolId(symbol); + var visitedSymbolTables; + if (visitedSymbolTablesMap.has(id)) { + visitedSymbolTables = visitedSymbolTablesMap.get(id); + } + else { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) @@ -26850,7 +27939,7 @@ var ts; // 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); + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && @@ -26868,7 +27957,8 @@ var ts; // Check if symbol is any of the alias return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 /* Alias */ - && symbolFromSymbolTable.escapedName !== "export=" + && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ + && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.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))) { @@ -26931,11 +28021,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } /** @@ -27044,7 +28134,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 146 /* ComputedPropertyName */) { // Typeof value - meaning = 107455 /* Value */ | 1048576 /* ExportValue */; + meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 145 /* QualifiedName */ || entityName.kind === 183 /* PropertyAccessExpression */ || entityName.parent.kind === 241 /* ImportEqualsDeclaration */) { @@ -27054,7 +28144,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 793064 /* Type */; + meaning = 67901928 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -27105,6 +28195,7 @@ var ts; } } function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; } if (writer === void 0) { writer = ts.createTextWriter(""); } var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); @@ -27187,7 +28278,8 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined + symbolStack: undefined, + inferTypeParameters: undefined }; } function typeToTypeNodeHelper(type, context) { @@ -27211,12 +28303,12 @@ var ts; } if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67901928 /* 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 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { @@ -27230,6 +28322,9 @@ var ts; } if (type.flags & 1024 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeQueryNode(symbolToName(type.symbol, context, 67216319 /* Value */, /*expectsIdentifier*/ false)); + } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } @@ -27271,7 +28366,10 @@ var ts; return typeReferenceToTypeNode(type); } if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - var name = type.symbol ? symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); + if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + } + var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -27311,13 +28409,16 @@ var ts; } if (type.flags & 2097152 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); - var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); - var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 4194304 /* Substitution */) { - return typeToTypeNodeHelper(type.typeParameter, context); + return typeToTypeNodeHelper(type.typeVariable, context); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { @@ -27336,14 +28437,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 203 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); + return createTypeQueryNodeFromSymbol(symbol, 67216319 /* 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) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 67901928 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -27420,7 +28521,7 @@ var ts; } function symbolToTypeReferenceName(symbol) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display - var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); return entityName; } function typeReferenceToTypeNode(type) { @@ -27448,7 +28549,8 @@ var ts; } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 203 /* ClassExpression */) { + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } else { @@ -27482,7 +28584,7 @@ var ts; } } } - var entityName = undefined; + var entityName = void 0; var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); @@ -27557,12 +28659,12 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } } - var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { @@ -27659,7 +28761,7 @@ var ts; if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); + var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); @@ -27893,9 +28995,6 @@ var ts; node.parent.kind === 238 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } - function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; - } function isDefaultBindingContext(location) { return location.kind === 272 /* SourceFile */ || ts.isAmbientModule(location); } @@ -27936,8 +29035,8 @@ var ts; return "(Anonymous function)"; } } - if (symbol.syntheticLiteralTypeOrigin) { - var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (symbol.nameType && symbol.nameType.flags & 32 /* StringLiteral */) { + var stringValue = symbol.nameType.value; if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; } @@ -28034,10 +29133,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 247 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 250 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -28058,7 +29157,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -28244,8 +29343,7 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var propType = getTypeOfPropertyOfType(parentType, text); - var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); + var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -28328,7 +29426,8 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); // Use type from type annotation if one is present var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); if (declaredType) { @@ -28395,12 +29494,19 @@ var ts; return undefined; } function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments + var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); + if (specialDeclaration) { + return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + } var types = []; + var constructorTypes; var definedInConstructor = false; var definedInMethod = false; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; + var declarationInConstructor = false; var expression = declaration.kind === 198 /* BinaryExpression */ ? declaration : declaration.kind === 183 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 198 /* BinaryExpression */) : undefined; @@ -28408,7 +29514,13 @@ var ts; return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 154 /* Constructor */) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + declarationInConstructor = thisContainer.kind === 154 /* Constructor */ || + thisContainer.kind === 232 /* FunctionDeclaration */ || + (thisContainer.kind === 190 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + if (declarationInConstructor) { definedInConstructor = true; } else { @@ -28430,11 +29542,34 @@ var ts; } 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_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); + var anyedType = type_2; + if (isEmptyArrayLiteralType(type_2)) { + anyedType = anyArrayType; + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + } + types.push(anyedType); + if (declarationInConstructor) { + (constructorTypes || (constructorTypes = [])).push(anyedType); + } } } - var type = jsDocType || getUnionType(types, 2 /* Subtype */); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + var type = jsDocType; + if (!type) { + // use only the constructor types unless only null | undefined (including widening variants) were assigned there + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~12288 /* Nullable */); }) === neverType) { + if (noImplicitAny) { + reportImplicitAnyError(symbol.valueDeclaration, anyType); + } + return anyType; + } + return widened; } // 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 @@ -28455,12 +29590,12 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var hasComputedProperties = false; + var objectFlags = 128 /* ObjectLiteral */; 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; + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; return; } if (e.dotDotDotToken) { @@ -28475,12 +29610,11 @@ var ts; members.set(symbol.escapedName, symbol); }); var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 33554432 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; } - if (hasComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } return result; } // Return the type implied by an array binding pattern @@ -28677,6 +29811,7 @@ var ts; if (getter && getter.body) { type = getReturnTypeFromBody(getter); } + // Otherwise, fall back to 'any'. else { if (noImplicitAny) { if (setter) { @@ -28741,7 +29876,7 @@ var ts; // 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 */ + links.type = targetSymbol.flags & 67216319 /* Value */ ? getTypeOfSymbol(targetSymbol) : unknownType; } @@ -29121,7 +30256,7 @@ 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 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -29485,7 +30620,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 107455 /* Value */) { + if (symbolFlags & 67216319 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; @@ -29548,8 +30683,18 @@ var ts; error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } + var symbolLinks_1 = getSymbolLinks(lateSymbol); + if (!symbolLinks_1.nameType) { + // Retain link to name type so that it can be reused later + symbolLinks_1.nameType = type; + } addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); - lateSymbol.parent = parent; + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } return links.resolvedSymbol = lateSymbol; } } @@ -29751,7 +30896,7 @@ var ts; } return [signature]; } - var result = undefined; + var result; for (var i = 0; i < signatureLists.length; i++) { // 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); @@ -29768,7 +30913,7 @@ var ts; // 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; + var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; @@ -29899,7 +31044,7 @@ var ts; else { // Combinations of function, class, enum and module var members = emptySymbols; - var stringIndexInfo = undefined; + var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); } @@ -29998,13 +31143,12 @@ var ts; // 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 templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = ts.escapeLeadingUnderscores(t.value); + var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); @@ -30021,7 +31165,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } - prop.syntheticLiteralTypeOrigin = t; + prop.nameType = t; members.set(propName, prop); } else if (t.flags & (1 /* Any */ | 2 /* String */)) { @@ -30206,7 +31350,7 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getDefaultConstraintOfConditionalType(type) { - return getUnionType([type.trueType, type.falseType]); + return getUnionType([getInferredTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); } function getConstraintOfDistributiveConditionalType(type) { // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained @@ -30214,13 +31358,11 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (isDistributiveConditionalType(type)) { + if (type.root.isDistributive) { var constraint = getConstraintOfType(type.checkType); if (constraint) { - var target = type.target || type; - var mapper = createTypeMapper([target.checkType], [constraint]); - var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper; - return instantiateType(target, combinedMapper); + var mapper = createTypeMapper([type.root.checkType], [constraint]); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); } } return undefined; @@ -30228,17 +31370,27 @@ var ts; function getConstraintOfConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } - function getBaseConstraintOfType(type) { + function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { if (type.flags & (7372800 /* InstantiableNonPrimitive */ | 393216 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 524288 /* Index */) { + } + function getBaseConstraintOfType(type) { + var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); + if (!constraint && type.flags & 524288 /* Index */) { return stringType; } - return undefined; + return constraint; + } + /** + * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` + * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable) + */ + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; } function hasNonCircularBaseConstraint(type) { return getResolvedBaseConstraint(type) !== circularConstraintType; @@ -30278,8 +31430,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -30302,7 +31454,8 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 2097152 /* Conditional */) { - return getBaseConstraint(getConstraintOfConditionalType(t)); + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); } if (t.flags & 4194304 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -30413,7 +31566,7 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; + var commonType; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; if (prop.declarations) { @@ -30553,23 +31706,13 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 279 /* JSDocOptionalType */) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 279 /* JSDocOptionalType */; - } - } - } - } + return ts.isInJavaScriptFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 279 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 279 /* JSDocOptionalType */; + })); } function tryFindAmbientModule(moduleName, withAugmentations) { if (ts.isExternalModuleNameRelative(moduleName)) { @@ -30670,11 +31813,15 @@ var ts; var parameters = []; var hasLiteralTypes = false; var minArgumentCount = 0; - var thisParameter = undefined; + var thisParameter = void 0; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJavaScriptFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(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. @@ -30683,7 +31830,7 @@ var ts; var paramSymbol = param.symbol; // 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); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -30699,8 +31846,8 @@ var ts; // 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) || - isUntypedSignatureInJSFile; + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -30725,18 +31872,21 @@ var ts; } return links.resolvedSignature; } + /** + * A JS function gets a synthetic rest parameter if it references `arguments` AND: + * 1. It has no parameters but at least one `@param` with a type that starts with `...` + * OR + * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` + */ function maybeAddJsSyntheticRestParameter(declaration, parameters) { - // JS functions get a free rest parameter if: - // a) The last parameter has `...` preceding its type - // b) It references `arguments` somewhere + if (!containsArgumentsReference(declaration)) { + return false; + } var lastParam = ts.lastOrUndefined(declaration.parameters); - var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); var lastParamVariadicType = 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; @@ -30802,32 +31952,18 @@ var ts; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; - switch (node.kind) { - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 280 /* 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) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); + if (!ts.isFunctionLike(node)) + continue; + // 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) { + continue; + } } + result.push(getSignatureFromDeclaration(node)); } return result; } @@ -30923,7 +32059,10 @@ var ts; return instantiation; } function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); } function getErasedSignature(signature) { return signature.typeParameters ? @@ -31197,6 +32336,7 @@ var ts; if (ts.isEntityNameExpression(expr)) { return expr; } + // fall through; } return undefined; } @@ -31219,24 +32359,23 @@ var ts; var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 32768 /* TypeParameter */ ? getConstrainedTypeParameter(res, node) : res : + res.flags & 32768 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : unknownType; } - if (!(symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67216319 /* 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 assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + var referenceType = valueType.symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType || assignedType) { + return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -31252,24 +32391,33 @@ var ts; return getInferredClassType(symbol); } } - function getSubstitutionType(typeParameter, substitute) { + function getSubstitutionType(typeVariable, substitute) { var result = createType(4194304 /* Substitution */); - result.typeParameter = typeParameter; + result.typeVariable = typeVariable; result.substitute = substitute; return result; } - function getConstrainedTypeParameter(typeParameter, node) { + function isUnaryTupleTypeNode(node) { + return node.kind === 167 /* TupleType */ && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { var constraints; while (ts.isPartOfTypeNode(node)) { var parent = node.parent; if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) { - if (getTypeFromTypeNode(parent.checkType) === typeParameter) { - constraints = ts.append(constraints, getTypeFromTypeNode(parent.extendsType)); + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); } } node = parent; } - return constraints ? getSubstitutionType(typeParameter, getIntersectionType(ts.append(constraints, typeParameter))) : typeParameter; + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { return node.flags & 1048576 /* JSDoc */ && node.kind === 161 /* TypeReference */; @@ -31337,10 +32485,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 793064 /* Type */; + var meaning = 67901928 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 107455 /* Value */; + meaning |= 67216319 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -31395,10 +32543,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -31449,18 +32597,9 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67901928 /* 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 /* 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. */ @@ -31572,6 +32711,8 @@ var ts; } else if (flags & 1 /* Any */) { includes |= 1 /* Any */; + if (type === wildcardType) + includes |= 4096 /* Wildcard */; } else if (!strictNullChecks && flags & 12288 /* Nullable */) { if (flags & 4096 /* Undefined */) @@ -31692,7 +32833,7 @@ var ts; var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); if (includes & 1 /* Any */) { - return anyType; + return includes & 4096 /* Wildcard */ ? wildcardType : anyType; } switch (unionReduction) { case 1 /* Literal */: @@ -31785,6 +32926,8 @@ var ts; } else if (flags & 1 /* Any */) { includes |= 1 /* Any */; + if (type === wildcardType) + includes |= 4096 /* Wildcard */; } else if (flags & 16384 /* Never */) { includes |= 8 /* Never */; @@ -31835,7 +32978,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return anyType; + return includes & 4096 /* Wildcard */ ? wildcardType : anyType; } if (includes & 1024 /* EmptyObject */ && !(includes & 512 /* ObjectType */)) { typeSet.push(emptyObjectType); @@ -31877,19 +33020,29 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? - neverType : - getLiteralType(ts.symbolName(prop)); + var links = getSymbolLinks(getLateBoundSymbol(prop)); + if (!links.nameType) { + if (links.target && links.target !== unknownSymbol && links.target !== resolvingSymbol && links.target.escapedName === prop.escapedName) { + links.nameType = getLiteralTypeFromPropertyName(links.target); + } + else { + links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? + neverType : + getLiteralType(ts.symbolName(prop)); + } + } + return links.nameType; } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) : - ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : - type === wildcardType ? wildcardType : - type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : - getLiteralTypeFromPropertyNames(type); + return type.flags & 262144 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) : + maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : + getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); @@ -31952,6 +33105,9 @@ var ts; } return indexInfo.type; } + if (indexType.flags & 16384 /* Never */) { + return neverType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (getIndexTypeOfType(objectType, 1 /* Number */)) { @@ -32050,10 +33206,13 @@ var ts; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper; + var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } // 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 @@ -32092,7 +33251,13 @@ var ts; function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 1048576 /* IndexedAccess */ && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; } return links.resolvedType; } @@ -32110,76 +33275,74 @@ var ts; } return links.resolvedType; } - function getActualTypeParameter(type) { - return type.flags & 4194304 /* Substitution */ ? type.typeParameter : type; + function getActualTypeVariable(type) { + return type.flags & 4194304 /* Substitution */ ? type.typeVariable : type; } - function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) { - var type = createType(2097152 /* Conditional */); - type.checkType = checkType; - type.extendsType = extendsType; - type.trueType = trueType; - type.falseType = falseType; - type.inferTypeParameters = inferTypeParameters; - type.target = target; - type.mapper = mapper; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - return type; - } - function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) { - // Instantiate extends type without instantiating any 'infer T' type parameters - var extendsType = instantiateType(baseExtendsType, mapper); - // Return falseType for a definitely false extends check. We check an instantations of the two - // types with type parameters mapped to the wildcard type, the most permissive instantiations - // possible (the wildcard type is assignable to and from all types). If those are not related, - // then no instatiations will be and we can just return the false branch type. - if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) { - return instantiateType(baseFalseType, mapper); + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; } - // The check could be true for some instantiation + // If this is a distributive conditional type and the check type is generic we need to defer + // resolution of the conditional type such that a later instantiation will properly distribute + // over union types. + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */); var combinedMapper; - if (inferTypeParameters) { - var inferences = ts.map(inferTypeParameters, createInferenceInfo); - // We don't want inferences from constraints as they may cause us to eagerly resolve the - // conditional type instead of deferring resolution. Also, we always want strict function - // types rules (i.e. proper contravariance) for inferences. - inferTypes(inferences, checkType, extendsType, 8 /* NoConstraints */ | 16 /* AlwaysStrict */); - // We infer 'never' when there are no candidates for a type parameter - var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; }); - var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes); - combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + } + combinedMapper = combineTypeMappers(mapper, context); } - // Return union of trueType and falseType for any and never since they match anything - if (checkType.flags & 1 /* Any */ || (checkType.flags & 16384 /* Never */ && !(extendsType.flags & 16384 /* Never */))) { - return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]); - } - // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType; - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type - // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { - return instantiateType(baseTrueType, combinedMapper || mapper); + if (!isDeferred) { + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // Return falseType for a definitely false extends check. We check an instantations of the two + // types with type parameters mapped to the wildcard type, the most permissive instantiations + // possible (the wildcard type is assignable to and from all types). If those are not related, + // then no instatiations will be and we can just return the false branch type. + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + // Return trueType for a definitely true extends check. The definitely assignable relation excludes + // type variable constraints from consideration. Without the definitely assignable relation, the type + // type Foo = T extends { x: string } ? string : number + // would immediately resolve to 'string' instead of being deferred. + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } } // Return a deferred type for a check that is neither definitely true nor definitely false - var erasedCheckType = getActualTypeParameter(checkType); - var trueType = instantiateType(baseTrueType, mapper); - var falseType = instantiateType(baseFalseType, mapper); - // We compute the cache key from the ids of the four constituent types, plus an indicator of whether the - // type is distributive (i.e. whether the original declaration has a type parameter as the check type). - var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 /* TypeParameter */ ? 1 : 0; - var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive; - var cached = conditionalTypes.get(id); - if (cached) { - return cached; - } - var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper)); - conditionalTypes.set(id, result); + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(2097152 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); return result; } - function isDistributiveConditionalType(type) { - return !!((type.target || type).checkType.flags & 32768 /* TypeParameter */); + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferredTrueTypeFromConditionalType(type) { + return type.combinedMapper ? + type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper)) : + getTrueTypeFromConditionalType(type); } function getInferTypeParameters(node) { var result; @@ -32195,7 +33358,28 @@ var ts; function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), /*target*/ undefined, /*mapper*/ undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var checkType = getTypeFromTypeNode(node.checkType); + var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 32768 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: getAliasSymbolForTypeNode(node), + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, /*mapper*/ undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } } return links.resolvedType; } @@ -32451,9 +33635,10 @@ var ts; return getTypeFromIntersectionTypeNode(node); case 277 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); + case 279 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); case 172 /* ParenthesizedType */: case 278 /* JSDocNonNullableType */: - case 279 /* JSDocOptionalType */: case 274 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); case 281 /* JSDocVariadicType */: @@ -32540,14 +33725,18 @@ var ts; return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { - return !!mapper.signature; + return !!mapper.typeParameters; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { @@ -32673,8 +33862,8 @@ var ts; // between the node and the type parameter declaration, if the node contains actual references to the // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_1 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 211 /* Block */ ? "quit" : n === container_1; })) { + var container_2 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 211 /* Block */ ? "quit" : n === container_2; })) { return ts.forEachChild(node, containsReference); } } @@ -32729,22 +33918,35 @@ var ts; return result; } function getConditionalTypeInstantiation(type, mapper) { - var target = type.target || type; - var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + var root = type.root; + if (root.outerTypeParameters) { + // We are instantiating a conditional 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 typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { // Check if we have a conditional type where the check type is a naked type parameter. If so, // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). - if (isDistributiveConditionalType(target)) { - var checkType_1 = target.checkType; - var instantiatedType = combinedMapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072 /* Union */) { - return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); }); + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 /* Union */ | 16384 /* Never */)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } - return instantiateConditionalType(target, combinedMapper); - } - function instantiateConditionalType(type, mapper) { - return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments); + return getConditionalType(root, mapper); } function instantiateType(type, mapper) { if (type && mapper && mapper !== identityMapper) { @@ -32785,10 +33987,10 @@ var ts; return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } if (type.flags & 2097152 /* Conditional */) { - return getConditionalTypeInstantiation(type, mapper); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } if (type.flags & 4194304 /* Substitution */) { - return mapper(type.typeParameter); + return instantiateType(type.typeVariable, mapper); } } return type; @@ -32855,7 +34057,8 @@ var ts; return node.body.kind === 211 /* Block */ ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { if (type.flags & 65536 /* Object */) { @@ -33329,10 +34532,10 @@ var ts; target = target.regularType; } if (source.flags & 4194304 /* Substitution */) { - source = relation === definitelyAssignableRelation ? source.typeParameter : source.substitute; + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } if (target.flags & 4194304 /* Substitution */) { - target = target.typeParameter; + target = target.typeVariable; } // 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) @@ -33458,11 +34661,11 @@ var ts; } } if (flags & 2097152 /* Conditional */) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { - if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { return result; } } @@ -33850,20 +35053,14 @@ var ts; } } else if (source.flags & 2097152 /* Conditional */) { - if (relation !== definitelyAssignableRelation) { - var constraint = getConstraintOfDistributiveConditionalType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } if (target.flags & 2097152 /* Conditional */) { - if (isTypeIdenticalTo(source.checkType, target.checkType) && - isTypeIdenticalTo(source.extendsType, target.extendsType)) { - if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { - result &= isRelatedTo(source.falseType, target.falseType, reportErrors); + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -33871,9 +35068,21 @@ var ts; } } } - else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } } else { @@ -34219,6 +35428,11 @@ var ts; if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { continue; } + // Skip over symbol-named members + var nameType = getLiteralTypeFromPropertyName(prop); + if (nameType !== undefined && !(isRelatedTo(nameType, stringType) || isRelatedTo(nameType, numberType))) { + continue; + } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -34738,8 +35952,18 @@ var ts; ts.Debug.assert(strictNullChecks); return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]); } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; + } + // Use NonNullable global type alias if available to improve quick info/declaration emit + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior + } function getNonNullableType(type) { - return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; } /** * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module @@ -34841,6 +36065,10 @@ var ts; } var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name); result.type = undefinedType; + var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name)); + if (associatedKeyType.flags & 32 /* StringLiteral */) { + result.nameType = associatedKeyType; + } undefinedProperties.set(name, result); return result; } @@ -34943,6 +36171,7 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 198 /* BinaryExpression */: case 151 /* PropertyDeclaration */: case 150 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; @@ -35004,9 +36233,10 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, compareTypes, baseInferences) { - var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); var context = mapper; + context.typeParameters = typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -35125,7 +36355,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return getTypeFromInference(inference) || emptyObjectType; + return getTypeFromInference(inference); } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -35140,21 +36370,38 @@ var ts; } return undefined; } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with different arity are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && getTypeReferenceArity(source) !== getTypeReferenceArity(target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : - undefined; + emptyObjectType; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; var contravariant = false; + var propagationType; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; } + if (source === wildcardType) { + // We are inferring from an 'any' type. We want to infer this type for every type parameter + // referenced in the target type, so we record it as the propagation type and infer from the + // target to itself. Then, as we find candidates we substitute the propagation type. + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + 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. @@ -35224,14 +36471,15 @@ var ts; inference.priority = priority; } if (priority === inference.priority) { + var candidate = propagationType || source; if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, source); + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, source); + inference.candidates = ts.append(inference.candidates, candidate); } } - if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -35261,7 +36509,10 @@ var ts; else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; + var savePriority = priority; + priority |= 16 /* LiteralKeyof */; inferFromTypes(empty, target.type); + priority = savePriority; contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { @@ -35271,8 +36522,8 @@ var ts; else if (source.flags & 2097152 /* Conditional */ && target.flags & 2097152 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(source.trueType, target.trueType); - inferFromTypes(source.falseType, target.falseType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else if (target.flags & 393216 /* UnionOrIntersection */) { var targetTypes = target.types; @@ -35308,7 +36559,7 @@ var ts; } } else { - if (!(priority && 8 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) { + if (!(priority & 32 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) { source = getApparentType(source); } if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) { @@ -35339,7 +36590,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 16 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -35378,7 +36629,7 @@ var ts; var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 2 /* MappedType */; + priority |= 2 /* HomomorphicMappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -35388,14 +36639,16 @@ var ts; 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. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); return; } } - // 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)) { + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0 /* Call */); inferFromSignatures(source, target, 1 /* Construct */); @@ -35493,62 +36746,73 @@ var ts; } return candidates; } + function getContravariantInference(inference) { + return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, context, signature) { + // 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 occurrences 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 widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + 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 = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } 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(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 = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? - getUnionType(baseCandidates, 2 /* Subtype */) : - getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unwidenedType); - // If we have inferred 'never' but have contravariant candidates. To get a more specific type we - // infer from the contravariant candidates instead. - if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { - inferredType = getCommonSubtype(inference.contraCandidates); + var signature = context.signature; + if (signature) { + if (inference.candidates) { + inferredType = getCovariantInference(inference, context, signature); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getContravariantInference(inference); + } } - } - else if (inference.contraCandidates) { - // We only have contravariant inferences, infer the best common subtype of those - inferredType = getCommonSubtype(inference.contraCandidates); - } - else if (context.flags & 2 /* NoDefault */) { - // We use silentNeverType as the wildcard that signals no inferences. - 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 if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getContravariantInference(inference); + } + else if (context.flags & 2 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + // 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 /* AnyDefault */)); + } } } + else { + inferredType = getTypeFromInference(inference); + } inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -35573,7 +36837,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -35593,7 +36857,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -35812,8 +37076,8 @@ var ts; } if (flags & 65536 /* Object */) { return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : - strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (2048 /* Void */ | 4096 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -35825,7 +37089,7 @@ var ts; return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } if (flags & 134217728 /* NonPrimitive */) { - return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & 7897088 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); @@ -35833,7 +37097,7 @@ var ts; if (flags & 393216 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 8388607 /* All */; + return 4194303 /* All */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -35847,7 +37111,7 @@ var ts; } function getTypeOfDestructuredProperty(type, name) { var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType; @@ -36031,6 +37295,9 @@ 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, noReductions) { + if (type.flags & 16384 /* Never */) { + return type; + } if (!(type.flags & 131072 /* Union */)) { return mapper(type); } @@ -36869,29 +38136,28 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } - function isApparentTypePosition(node) { + function isConstraintPosition(node) { var parent = node.parent; return parent.kind === 183 /* PropertyAccessExpression */ || parent.kind === 185 /* CallExpression */ && parent.expression === node || parent.kind === 184 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 207 /* NonNullExpression */ || parent.kind === 180 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 7372800 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getApparentTypeForLocation(type, node) { + function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getApparentType); + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); } return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -36963,7 +38229,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -37527,47 +38793,47 @@ var ts; // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter) { var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = func.parameters.indexOf(parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(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)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = func.parameters.indexOf(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)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } - 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. @@ -37613,7 +38879,7 @@ var ts; var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { + if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function return undefined; } var contextualReturnType = getContextualReturnType(func); @@ -37691,9 +38957,11 @@ var ts; 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. + // expression has no contextual type, the right operand is contextually typed by the type of the left operand, + // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right ? getTypeOfExpression(left, /*cache*/ true) : type; + return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? + getTypeOfExpression(left, /*cache*/ true) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; @@ -37716,6 +38984,7 @@ var ts; case 2 /* ModuleExports */: case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: + case 6 /* Prototype */: return false; default: ts.Debug.assertNever(kind); @@ -37781,7 +39050,7 @@ var ts; function getContextualTypeForChildJsxExpression(node) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // 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(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; } function getContextualTypeForJsxExpression(node) { @@ -37933,15 +39202,9 @@ var ts; return anyType; } var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } - function getJsxSignaturesParameterTypes(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false); - } - function getJsxSignaturesParameterTypesJs(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true); - } - function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + function getJsxSignaturesParameterTypes(valueType, isJs, context) { // 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 (valueType.flags & 2 /* String */) { return anyType; @@ -37951,7 +39214,7 @@ var ts; // For example: // var CustomTag: "h1" = "h1"; // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = valueType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -37977,21 +39240,24 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */); + if (context.typeArguments) { + signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + } + return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); } - function getJsxPropsTypeFromCallSignature(sig) { + function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignature(sig); - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { propsType = intersectTypes(intrinsicAttribs, propsType); } return propsType; } - function getJsxPropsTypeFromClassType(hostClassType, isJs) { + function getJsxPropsTypeFromClassType(hostClassType, isJs, context) { if (isTypeAny(hostClassType)) { return hostClassType; } - var propsName = getJsxElementPropertiesName(); + var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context)); if (propsName === undefined) { // There is no type ElementAttributesProperty, return 'any' return anyType; @@ -38013,14 +39279,14 @@ var ts; else { // Normal case -- add in IntrinsicClassElements and IntrinsicElements var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); if (intrinsicClassAttribs !== unknownType) { var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); apparentAttributesType = intersectTypes(typeParams ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) : intrinsicClassAttribs, apparentAttributesType); } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); } @@ -38028,18 +39294,12 @@ var ts; } } } - function getJsxPropsTypeFromConstructSignatureJs(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true); - } - function getJsxPropsTypeFromConstructSignature(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false); - } - function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + function getJsxPropsTypeFromConstructSignature(sig, isJs, context) { var hostClassType = getReturnTypeOfSignature(sig); if (hostClassType) { - return getJsxPropsTypeFromClassType(hostClassType, isJs); + return getJsxPropsTypeFromClassType(hostClassType, isJs, context); } - return getJsxPropsTypeFromCallSignature(sig); + return getJsxPropsTypeFromCallSignature(sig, context); } // 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. @@ -38088,7 +39348,16 @@ var ts; // union type of return types from these signatures function getContextualSignature(node) { ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); + var type; + if (ts.isInJavaScriptFile(node)) { + var jsdoc = ts.getJSDocType(node); + if (jsdoc) { + type = getTypeFromTypeNode(jsdoc); + } + } + if (!type) { + type = getContextualTypeForFunctionLikeDeclaration(node); + } if (!type) { return undefined; } @@ -38281,19 +39550,29 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createSymbolTable(); + var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; var propagatedFlags = 8388608 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 178 /* ObjectBindingPattern */ || contextualType.pattern.kind === 182 /* ObjectLiteralExpression */); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node); + var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - var isInJSFile = ts.isInJavaScriptFile(node); + if (isInJSFile && node.properties.length === 0) { + // an empty JS object literal that nonetheless has members is a JS namespace + var symbol = getSymbolOfNode(node); + if (symbol.exports) { + propertiesTable = symbol.exports; + symbol.exports.forEach(function (symbol) { return propertiesArray.push(getMergedSymbol(symbol)); }); + return createObjectLiteralType(); + } + } + propertiesTable = ts.createSymbolTable(); var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; @@ -38329,9 +39608,13 @@ var ts; } typeFlags |= type.flags; var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; - var prop = nameType && isTypeUsableAsLateBoundName(nameType) + var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType); + var prop = hasLateBoundName ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); + if (hasLateBoundName) { + prop.nameType = nameType; + } 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. @@ -38455,7 +39738,7 @@ var ts; } function checkJsxSelfClosingElement(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxElement(node, checkMode) { // Check attributes @@ -38467,14 +39750,16 @@ var ts; else { checkExpression(node.closingElement.tagName); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxFragment(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); - if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { - error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } /** * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers @@ -38519,7 +39804,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -38586,7 +39871,10 @@ var ts; if (hasSpreadAnyType) { return anyType; } - return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + if (typeToIntersect && spread !== emptyObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -38624,12 +39912,11 @@ var ts; function checkJsxAttributes(node, checkMode) { return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType; } /** * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic @@ -38640,11 +39927,11 @@ var ts; function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); if (intrinsicElementsType !== unknownType) { // Property case if (!ts.isIdentifier(node.tagName)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); if (intrinsicProp) { links.jsxFlags |= 1 /* IntrinsicNamedElement */; @@ -38693,20 +39980,66 @@ var ts; } // Instantiate in context of source type var instantiatedSignatures = []; + var candidateForTypeArgumentError; + var hasTypeArgumentError = !!node.typeArguments; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); + if (typeArgumentInstantiated) { + hasTypeArgumentError = false; + instantiatedSignatures.push(typeArgumentInstantiated); + } + else { + if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + candidateForTypeArgumentError = signature; + } + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } } else { instantiatedSignatures.push(signature); } } + if (node.typeArguments && hasTypeArgumentError) { + if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); + } + // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine + else if (node.typeArguments.length !== 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); + } + } return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } + function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (!node.typeArguments) { + return; + } + if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + return; + } + var args = checkTypeArguments(signature, node.typeArguments, reportErrors); + if (!args) { + return; + } + return getSignatureInstantiation(signature, args, isJavascript); + } + function getJsxNamespaceAt(location) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + return candidate; + } + } + // JSX global fallback + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + } /** * 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. @@ -38714,11 +40047,9 @@ var ts; * @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) { - // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -38728,6 +40059,8 @@ var ts; if (propertiesOfJsxElementAttribPropInterface.length === 0) { return ""; } + // Element Attributes has one property, so the element attributes type will be the type of the corresponding + // property of the class instance type else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } @@ -38743,19 +40076,11 @@ var ts; /// 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; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } - function getJsxElementChildrenPropertyName() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - return _jsxElementChildrenPropertyName; + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } function getApparentTypeOfJsxPropsType(propsType) { if (!propsType) { @@ -38784,7 +40109,7 @@ var ts; function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); @@ -38794,7 +40119,7 @@ var ts; paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { paramType = intersectTypes(intrinsicAttributes, paramType); } @@ -38819,7 +40144,7 @@ var ts; 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(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; @@ -38853,7 +40178,7 @@ var ts; result = allMatchingAttributesType; } // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { result = intersectTypes(intrinsicAttributes, result); } @@ -38896,7 +40221,7 @@ var ts; // For example: // var CustomTag: "h1" = "h1"; // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -38926,7 +40251,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -38957,7 +40282,7 @@ var ts; * @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) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -38997,32 +40322,26 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.escapedText); return prop || unknownSymbol; } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === unknownType) + return undefined; + return type; } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); } - return deferredJsxStatelessElementType; } /** * Returns all the properties of the Jsx.IntrinsicElements interface */ - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; } function checkJsxPreconditions(errorNode) { @@ -39030,7 +40349,7 @@ var ts; if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); } - if (getJsxGlobalElementType() === undefined) { + if (getJsxElementTypeAt(errorNode) === undefined) { if (noImplicitAny) { error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); } @@ -39045,9 +40364,9 @@ var ts; // 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 reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* 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 @@ -39121,7 +40440,7 @@ var ts; // 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) || getPropertiesOfType(sourceAttributesType).length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement)))); } else { // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties @@ -39166,7 +40485,9 @@ var ts; return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || + ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */ || + ts.isInJavaScriptFile(symbol.valueDeclaration) && ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(symbol.valueDeclaration))); } /** * Check whether the requested property access is valid. @@ -39328,7 +40649,7 @@ var ts; return unknownType; } } - propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -39439,7 +40760,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455 /* Value */); + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 67216319 /* Value */); return suggestion && ts.symbolName(suggestion); } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { @@ -39454,6 +40775,10 @@ var ts; }); return result && ts.symbolName(result); } + function getSuggestionForNonexistentModule(name, targetModule) { + var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + return suggestion && ts.symbolName(suggestion); + } /** * 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. @@ -39478,7 +40803,8 @@ var ts; for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; var candidateName = ts.symbolName(candidate); - if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + if (candidateName.charCodeAt(0) === 34 /* doubleQuote */ + || !(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { continue; } var candidateNameLowerCase = candidateName.toLowerCase(); @@ -39572,15 +40898,23 @@ var ts; return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } - function isValidMethodAccess(method, type) { + function isValidMethodAccess(method, actualThisType) { var propType = getTypeOfFuncClassEnumModule(method); var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { - var thisType = getThisTypeOfSignature(sig); - return !thisType || isTypeAssignableTo(type, thisType); + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); }); } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type === unknownType || isTypeAny(type)) { return true; @@ -39831,13 +41165,7 @@ var ts; typeArguments = node.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 || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { + if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { 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. @@ -39853,6 +41181,14 @@ var ts; var hasEnoughArguments = argCount >= signature.minArgumentCount; return callIsIncomplete || hasEnoughArguments; } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + // 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); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { if (type.flags & 65536 /* Object */) { @@ -39866,13 +41202,13 @@ var ts; } // 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 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, 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 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -39923,7 +41259,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); @@ -40354,6 +41690,17 @@ var ts; return arg; } } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 187 /* TaggedTemplateExpression */; var isDecorator = node.kind === 149 /* Decorator */; @@ -40470,21 +41817,13 @@ var ts; 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; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); - } - var paramCount = min < max ? min + "-" + max : min; - diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { - var sig = signatures_6[_a]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -40556,7 +41895,7 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : + createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : undefined; while (true) { candidate = originalCandidate; @@ -40980,19 +42319,49 @@ var ts; return false; } function getJavaScriptClassType(symbol) { - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + var initializer = ts.getDeclaredJavascriptInitializer(symbol.valueDeclaration); + if (initializer) { + symbol = getSymbolOfNode(initializer); } + var inferred; if (isJavaScriptConstructor(symbol.valueDeclaration)) { - return getInferredClassType(symbol); + inferred = getInferredClassType(symbol); } - if (symbol.flags & 3 /* Variable */) { - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { - return getInferredClassType(valueType.symbol); + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + if (assignmentSymbol) { + var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); + if (prototype) { + return checkExpression(prototype); } } } + function getAssignedJavascriptPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 183 /* PropertyAccessExpression */) { + parent = parent.parent; + } + return parent && ts.isBinaryExpression(parent) && + ts.isPrototypeAccess(parent.left) && + parent.operatorToken.kind === 58 /* EqualsToken */ && + ts.isObjectLiteralExpression(parent.right) && + parent.right; + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -41070,7 +42439,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -41123,13 +42492,13 @@ var ts; return type; } function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ 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 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (!resolvedRequire) { // project does not contain symbol named 'require' - assume commonjs require return true; @@ -41320,7 +42689,7 @@ var ts; } else { var types = checkAndAggregateReturnExpressionTypes(func, checkMode); - if (functionFlags & 1 /* Generator */) { + if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { var iterableIteratorAny = functionFlags & 2 /* Async */ @@ -41389,25 +42758,21 @@ var ts; } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); + var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0; ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - // A yield* expression effectively yields everything that its operand yields - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); - } - 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); - } - ts.pushIfUnique(aggregatedTypes, type); - } + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); }); return aggregatedTypes; } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpressionCached(node.expression, checkMode) : undefinedWideningType; + // A `yield*` expression effectively yields everything that its operand yields + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.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); + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; @@ -41431,7 +42796,7 @@ var ts; } return true; } - /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ function checkAndAggregateReturnExpressionTypes(func, checkMode) { var functionFlags = ts.getFunctionFlags(func); var aggregatedTypes = []; @@ -41460,7 +42825,9 @@ var ts; if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -41531,7 +42898,6 @@ var ts; ts.Debug.assert(node.kind !== 153 /* 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 @@ -41586,7 +42952,7 @@ var ts; ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : // Async function getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function - if ((functionFlags & 1 /* Generator */) === 0) { + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } @@ -41610,11 +42976,11 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function 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); } - else { + else { // Normal function checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } @@ -42070,6 +43436,9 @@ var ts; return (target.flags & 12288 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + return checkExpression(node.right, checkMode); + } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { @@ -42279,52 +43648,35 @@ var ts; error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); } } - 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) { - // 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 */); - } - // Generator functions prior to ES2015 require the __values helper - if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && - languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256 /* Values */); - } + var func = ts.getContainingFunction(node); + var functionFlags = func ? ts.getFunctionFlags(func) : 0 /* Normal */; + if (!(functionFlags & 1 /* Generator */)) { + // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. + return anyType; + } + if (node.asteriskToken) { + // 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 & 1 /* Generator */) { - var expressionType = checkExpressionCached(node.expression); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - 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 /* Async */) !== 0) || anyType; - if (nodeIsYieldStar) { - 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, - /*headMessage*/ undefined); - } - else { - 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, - /*headMessage*/ undefined); - } - } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); } } + var isAsync = (functionFlags & 2 /* Async */) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + // 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), isAsync) || anyType; + checkTypeAssignableTo(yieldedType, signatureElementType, node.expression || node, /*headMessage*/ undefined); + } // Both yield and yield* expressions have type 'any' return anyType; } @@ -42385,10 +43737,27 @@ var ts; return node.kind === 188 /* TypeAssertionExpression */ || node.kind === 206 /* AsExpression */; } function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); - return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + var inJs = ts.isInJavaScriptFile(declaration); + var initializer = inJs && ts.getDeclaredJavascriptInitializer(declaration) || declaration.initializer; + var type = getTypeOfExpression(initializer, /*cache*/ true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (inJs) { + if (widened.flags & 12288 /* Nullable */) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyType); + } + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyArrayType); + } + return anyArrayType; + } + } + return widened; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { @@ -42469,7 +43838,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 === 185 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true) && !isSymbolOrSymbolForCall(node)) { + if (node.kind === 185 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -42771,6 +44140,7 @@ var ts; if (node.kind === 159 /* IndexSignature */) { checkGrammarIndexSignature(node); } + // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled else if (node.kind === 162 /* FunctionType */ || node.kind === 232 /* FunctionDeclaration */ || node.kind === 163 /* ConstructorType */ || node.kind === 157 /* CallSignature */ || node.kind === 154 /* Constructor */ || node.kind === 158 /* ConstructSignature */) { @@ -43589,7 +44959,7 @@ var ts; case 230 /* VariableDeclaration */: case 180 /* BindingElement */: case 232 /* FunctionDeclaration */: - case 246 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 + case 246 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -43816,7 +45186,7 @@ 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 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; if (promiseConstructorType === unknownType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -43839,7 +45209,7 @@ var ts; } // 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 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; @@ -43893,7 +45263,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -44041,7 +45411,20 @@ var ts; 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 === 145 /* QualifiedName */ ? node.name.right : node.name)); + var decl = ts.getHostSignatureFromJSDoc(node); + // don't issue an error for invalid hosts -- just functions -- + // and give a better error message when the host function mentions `arguments` + // but the tag doesn't have an array type + if (decl) { + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + } + } } } function checkJSDocAugmentsTag(node) { @@ -44050,7 +45433,7 @@ var ts; error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } - var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 285 /* JSDocAugmentsTag */); + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); 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); @@ -44113,7 +45496,7 @@ var ts; var body = node.kind === 152 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - if ((functionFlags & 1 /* Generator */) === 0) { + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ ? checkAsyncFunctionReturnType(node) // Async function : getTypeFromTypeNode(returnTypeNode)); // normal function @@ -44136,6 +45519,8 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { if (deferredUnusedIdentifierNodes) { + // TODO: GH#22580 + // Debug.assert(addToSeen(seenDeferredUnusedIdentifiers, getNodeId(node)), "Deferring unused identifier check twice"); deferredUnusedIdentifierNodes.push(node); } } @@ -44229,14 +45614,14 @@ var ts; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); + diagnostics.add(ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 /* Identifier */ && ts.idText(node).charCodeAt(0) === 95 /* _ */; + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { @@ -44295,18 +45680,60 @@ var ts; } function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports_1 = ts.createMap(); node.locals.forEach(function (local) { - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration, ts.symbolName(local)); + if (local.isReferenced || local.exportSymbol) + return; + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + var importClause = importClauseFromImported(declaration); + var key = String(getNodeId(importClause)); + var group_1 = unusedImports_1.get(key); + if (group_1) { + group_1[1].push(declaration); } + else { + unusedImports_1.set(key, [importClause, [declaration]]); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local)); } } }); + unusedImports_1.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name)); + } + } + else if (unuseds.length === 1) { + error(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)); + } + else { + error(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)); + } + }); } } + function isImportedDeclaration(node) { + return node.kind === 243 /* ImportClause */ || node.kind === 246 /* ImportSpecifier */ || node.kind === 244 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 243 /* ImportClause */ ? decl : decl.kind === 244 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function forEachImportedDeclaration(importClause, cb) { + var defaultName = importClause.name, namedBindings = importClause.namedBindings; + return (defaultName && cb(importClause)) || + namedBindings && (namedBindings.kind === 244 /* NamespaceImport */ ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); + } function checkBlock(node) { // Grammar checking for SyntaxKind.Block if (node.kind === 211 /* Block */) { @@ -44326,7 +45753,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -44360,12 +45787,12 @@ var ts; return true; } function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { + if (languageVersion <= 1 /* ES5 */ && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_this")) { potentialThisCollisions.push(node); } } function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + if (languageVersion <= 1 /* ES5 */ && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_newTarget")) { potentialNewTargetCollisions.push(node); } } @@ -44399,6 +45826,9 @@ var ts; }); } function checkCollisionWithCapturedSuperVariable(node, name) { + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } @@ -44420,7 +45850,7 @@ var ts; } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { // No need to check for require or exports for ES6 modules and later - if (modulekind >= ts.ModuleKind.ES2015) { + if (modulekind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { return; } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { @@ -44438,7 +45868,7 @@ var ts; } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } // Uninstantiated modules shouldnt do this check @@ -44488,7 +45918,7 @@ var ts; var symbol = getSymbolOfNode(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!ts.isIdentifier(node.name)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && @@ -44537,7 +45967,7 @@ var ts; 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); + var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -44656,7 +46086,8 @@ var ts; // 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 !== 219 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); + var initializer = ts.isInJavaScriptFile(node) && ts.getDeclaredJavascriptInitializer(node) || node.initializer; + checkTypeAssignableTo(checkExpressionCached(initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } } @@ -45191,7 +46622,7 @@ var ts; var isGenerator = functionFlags & 1 /* Generator */; if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (isGenerator) { + 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 types of generators when return type tracking is added @@ -45209,7 +46640,7 @@ var ts; } } else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2 /* Async */) { + if (functionFlags & 2 /* Async */) { // Async function 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) { @@ -45295,8 +46726,7 @@ var ts; return "quit"; } if (current.kind === 226 /* 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)); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } }); @@ -45651,7 +47081,7 @@ var ts; var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && baseProp) { var rootChain = function () { return ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { issuedMemberError = true; } @@ -46166,7 +47596,6 @@ var ts; // - 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); @@ -46271,7 +47700,11 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { + if (ts.nodeIsMissing(moduleName)) { + // Should be a parse error. + return false; + } + if (!ts.isStringLiteral(moduleName)) { error(moduleName, ts.Diagnostics.String_literal_expected); return false; } @@ -46282,7 +47715,7 @@ var ts; ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { // 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)) { @@ -46306,8 +47739,8 @@ var ts; // 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) | + var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | + (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 250 /* ExportSpecifier */ ? @@ -46318,7 +47751,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 250 /* ExportSpecifier */ - && !(target.flags & 107455 /* Value */) + && !(target.flags & 67216319 /* Value */) && !(node.flags & 2097152 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -46369,14 +47802,14 @@ var ts; if (node.moduleReference.kind !== 252 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 107455 /* Value */) { + if (target.flags & 67216319 /* 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 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67216319 /* 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 /* Type */) { + if (target.flags & 67901928 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -46436,7 +47869,7 @@ var ts; 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 */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* 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.idText(exportedName)); @@ -46712,8 +48145,14 @@ var ts; function checkJSDocVariadicType(node) { checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); - // Only legal location is in the *last* parameter tag. + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } @@ -46738,22 +48177,26 @@ var ts; 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); + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { /* - Only return an array type if the corresponding parameter is marked as a rest parameter. + Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: /** @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)) { + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { return createArrayType(type); } } } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } return addOptionality(type); } // Function and class expression bodies are checked after all statements in the enclosing body. This is @@ -46822,6 +48265,7 @@ var ts; checkUnusedIdentifiers(); } deferredNodes = undefined; + seenDeferredUnusedIdentifiers.clear(); deferredUnusedIdentifierNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); @@ -46924,7 +48368,7 @@ var ts; // (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(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); } break; case 190 /* FunctionExpression */: @@ -47065,7 +48509,7 @@ var ts; } if (entityName.parent.kind === 247 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } if (entityName.kind !== 183 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import @@ -47080,10 +48524,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 205 /* ExpressionWithTypeArguments */) { - meaning = 793064 /* Type */; + meaning = 67901928 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455 /* Value */; + meaning |= 67216319 /* Value */; } } else { @@ -47113,7 +48557,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 183 /* PropertyAccessExpression */ || entityName.kind === 145 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -47130,7 +48574,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 161 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 161 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 260 /* JsxAttribute */) { @@ -47206,7 +48650,7 @@ var ts; // 3). Dynamic import call or require in javascript if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 242 /* ImportDeclaration */ || node.parent.kind === 248 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } // falls through @@ -47231,7 +48675,7 @@ var ts; // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. if (location && location.kind === 269 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 107455 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -47239,7 +48683,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 4194304 /* InWithStatement */) { @@ -47424,13 +48868,13 @@ var ts; // 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 /* Value */) + ? !!(moduleSymbol.flags & 67216319 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 107455 /* Value */); + return s && !!(s.flags & 67216319 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -47480,7 +48924,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // 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 */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -47493,7 +48937,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -47589,7 +49033,7 @@ var ts; } // 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 */ && + return target.flags & 67216319 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -47602,7 +49046,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 107455 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -47614,6 +49058,8 @@ var ts; } function isImplementationOfOverload(node) { if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload @@ -47687,9 +49133,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // 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); + var valueSymbol = resolveEntityName(typeName, 67216319 /* 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); + var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -47739,7 +49185,11 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { + declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(119 /* AnyKeyword */); + } // 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 /* TypeLiteral */ | 131072 /* Signature */)) @@ -47749,18 +49199,26 @@ var ts; type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 131072 /* AddUndefined */) { + if (addUndefined) { type = getOptionalType(type); } - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { + signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(119 /* AnyKeyword */); + } var signature = getSignatureFromDeclaration(signatureDeclaration); - typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { + expr = ts.getParseTreeNode(expr, ts.isExpression); + if (!expr) { + return ts.createToken(119 /* AnyKeyword */); + } var type = getWidenedType(getRegularTypeOfExpression(expr)); - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -47779,7 +49237,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -47800,9 +49258,12 @@ var ts; } return false; } - function writeLiteralConstValue(node, writer) { + function literalTypeToNode(type) { + return ts.createLiteral(type.value); + } + function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); + return literalTypeToNode(type); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -47845,9 +49306,10 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -47869,8 +49331,7 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } }; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -47882,8 +49343,8 @@ var ts; // 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 === 183 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) - ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793064 /* Type */ | 1920 /* Namespace */; + ? 67216319 /* Value */ | 1048576 /* ExportValue */ + : 67901928 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -47947,7 +49408,7 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 237 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); if (!moduleSymbol) { return undefined; @@ -48048,7 +49509,7 @@ var ts; 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 */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -48687,6 +50148,7 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; @@ -49079,8 +50541,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } } @@ -49232,8 +50694,8 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { 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), /*length*/ 0, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } } @@ -49283,7 +50745,7 @@ var ts; case 243 /* ImportClause */: // For default import case 241 /* ImportEqualsDeclaration */: case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */:// For rename import `x as y` + case 246 /* ImportSpecifier */: // For rename import `x as y` return true; case 71 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. @@ -49329,14 +50791,14 @@ var ts; * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. */ function createNodeArray(elements, hasTrailingComma) { - if (elements) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else { if (ts.isNodeArray(elements)) { return elements; } } - else { - elements = []; - } var array = elements; array.pos = -1; array.end = -1; @@ -49367,7 +50829,7 @@ var ts; return clone; } ts.getSynthesizedClone = getSynthesizedClone; - function createLiteral(value) { + function createLiteral(value, isSingleQuote) { if (typeof value === "number") { return createNumericLiteral(value + ""); } @@ -49375,7 +50837,10 @@ var ts; return value ? createTrue() : createFalse(); } if (ts.isString(value)) { - return createStringLiteral(value); + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; } return createLiteralFromNode(value); } @@ -49448,6 +50913,15 @@ var ts; return name; } ts.createUniqueName = createUniqueName; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 5 /* OptimisticUnique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateFlags = 4 /* Node */; @@ -49486,6 +50960,49 @@ var ts; return createSynthesizedNode(86 /* FalseKeyword */); } ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(84 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(124 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(79 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(76 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(114 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(112 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(113 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(117 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(115 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(132 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(120 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { var node = createSynthesizedNode(145 /* QualifiedName */); @@ -49501,9 +51018,15 @@ var ts; : node; } ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || + expression.kind === 296 /* CommaListExpression */ ? + createParen(expression) : + expression; + } function createComputedPropertyName(expression) { var node = createSynthesizedNode(146 /* ComputedPropertyName */); - node.expression = expression; + node.expression = parenthesizeForComputedName(expression); return node; } ts.createComputedPropertyName = createComputedPropertyName; @@ -51134,31 +52657,35 @@ var ts; : node; } ts.updateJsxElement = updateJsxElement; - function createJsxSelfClosingElement(tagName, attributes) { + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(254 /* JsxSelfClosingElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxSelfClosingElement = createJsxSelfClosingElement; - function updateJsxSelfClosingElement(node, tagName, attributes) { + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxSelfClosingElement(tagName, attributes), node) + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; - function createJsxOpeningElement(tagName, attributes) { + function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(255 /* JsxOpeningElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxOpeningElement = createJsxOpeningElement; - function updateJsxOpeningElement(node, tagName, attributes) { + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxOpeningElement(tagName, attributes), node) + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxOpeningElement = updateJsxOpeningElement; @@ -51300,7 +52827,7 @@ var ts; var node = createSynthesizedNode(268 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); return node; } ts.createPropertyAssignment = createPropertyAssignment; @@ -51353,8 +52880,11 @@ var ts; } ts.updateEnumMember = updateEnumMember; // Top-level nodes - function updateSourceFileNode(node, statements) { - if (node.statements !== statements) { + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences)) { var updated = createSynthesizedNode(272 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); @@ -51362,18 +52892,15 @@ var ts; updated.fileName = node.fileName; updated.path = node.path; updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; - if (node.referencedFiles !== undefined) - updated.referencedFiles = node.referencedFiles; - if (node.typeReferenceDirectives !== undefined) - updated.typeReferenceDirectives = node.typeReferenceDirectives; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; - if (node.isDeclarationFile !== undefined) - updated.isDeclarationFile = node.isDeclarationFile; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; if (node.hasNoDefaultLib !== undefined) @@ -51410,6 +52937,12 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; return updateNode(updated, node); } return node; @@ -51953,7 +53486,8 @@ var ts; requestEmitHelper: ts.noop, resumeLexicalEnvironment: ts.noop, startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, }; function createTypeCheck(value, tag) { return tag === "undefined" @@ -52086,7 +53620,7 @@ var ts; var valuesHelper = { name: "typescript:values", scoped: false, - text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };\n " + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" }; function createValuesHelper(context, expression, location) { context.requestEmitHelper(valuesHelper); @@ -52097,7 +53631,7 @@ var ts; var readHelper = { name: "typescript:read", scoped: false, - text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };\n " + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" }; function createReadHelper(context, iteratorRecord, count, location) { context.requestEmitHelper(readHelper); @@ -52158,7 +53692,7 @@ var ts; } ts.restoreEnclosingLabel = restoreEnclosingLabel; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { - var target = skipParentheses(node); + var target = ts.skipParentheses(node); switch (target.kind) { case 71 /* Identifier */: return cacheIdentifiers; @@ -52987,7 +54521,7 @@ var ts; do { previousNode = node; if (kinds & 1 /* Parentheses */) { - node = skipParentheses(node); + node = ts.skipParentheses(node); } if (kinds & 2 /* Assertions */) { node = skipAssertions(node); @@ -52999,13 +54533,6 @@ var ts; return node; } ts.skipOuterExpressions = skipOuterExpressions; - function skipParentheses(node) { - while (node.kind === 189 /* ParenthesizedExpression */) { - node = node.expression; - } - return node; - } - ts.skipParentheses = skipParentheses; function skipAssertions(node) { while (ts.isAssertionExpression(node) || node.kind === 207 /* NonNullExpression */) { node = node.expression; @@ -53767,9 +55294,9 @@ var ts; case 253 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 254 /* JsxSelfClosingElement */: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 255 /* JsxOpeningElement */: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 256 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 257 /* JsxFragment */: @@ -54337,9 +55864,10 @@ var ts; var Debug; (function (Debug) { var isDebugInfoEnabled = false; - 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; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; 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; @@ -54444,7 +55972,7 @@ var ts; var uniqueExports = ts.createMap(); var exportedNames; var hasExportDefault = false; - var exportEquals = undefined; + var exportEquals; var hasExportStarsToExportValues = false; var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -55361,8 +56889,7 @@ var ts; case 210 /* SemicolonClassElement */: return node; default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { @@ -55533,8 +57060,7 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitSourceFile(node) { @@ -56048,7 +57574,7 @@ var ts; ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); 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))); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); } /** * Gets all property declarations with initializers on either the static or instance side of a class. @@ -56662,10 +58188,8 @@ var ts; case 86 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: - ts.Debug.failBadSyntaxKind(node.literal); - break; + return ts.Debug.failBadSyntaxKind(node.literal); } - break; case 134 /* NumberKeyword */: return ts.createIdentifier("Number"); case 138 /* SymbolKeyword */: @@ -56686,8 +58210,7 @@ var ts; case 173 /* ThisType */: break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } @@ -56711,6 +58234,8 @@ var ts; // One of the individual is global object, return immediately return serializedIndividual; } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || @@ -56874,7 +58399,7 @@ var ts; function visitPropertyNameOfClassElement(member) { var name = member.name; var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); - if (expr) { + if (expr) { // expr only exists if `name` is a computed property name // 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])); @@ -58496,12 +60021,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: "\n const _super = name => super[name];\n " + text: "\n const _super = name => super[name];" }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - 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 " + 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);" }; })(ts || (ts = {})); /// @@ -59082,7 +60607,7 @@ var ts; var awaitHelper = { name: "typescript:await", scoped: false, - text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" }; function createAwaitHelper(context, expression) { context.requestEmitHelper(awaitHelper); @@ -59091,7 +60616,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -59108,7 +60633,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -59119,7 +60644,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -59186,8 +60711,7 @@ var ts; case 257 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxElement(node, isChild) { @@ -59225,14 +60749,14 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } return element; } function visitJsxOpeningFragment(node, children, isChild, location) { - var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -59264,7 +60788,7 @@ var ts; return visitJsxExpression(node); } else { - ts.Debug.failBadSyntaxKind(node); + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxText(node) { @@ -60424,6 +61948,7 @@ var ts; if (statement.kind === 223 /* ReturnStatement */) { return true; } + // An if-statement with two covered branches is covered. else if (statement.kind === 215 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { @@ -60431,6 +61956,7 @@ var ts; isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } + // A block is covered if it has a last statement which is covered. else if (statement.kind === 211 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { @@ -60629,11 +62155,11 @@ var ts; 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 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter)) - ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */)); + ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); statements.push(statement); } /** @@ -60738,8 +62264,7 @@ var ts; 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; + return ts.Debug.failBadSyntaxKind(node); } var captureNewTargetStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -61382,26 +62907,23 @@ var ts; statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); } } - var bodyLocation; - var statementsLocation; if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); } else { var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); } else { statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); } } - // 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 createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { // The following ES6 code: @@ -61980,18 +63502,15 @@ var ts; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { - var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = transformFunctionBody(node); - if (node.kind === 155 /* GetAccessor */) { - updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); - } - else { - updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); - } + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 155 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { - updated = ts.visitEachChild(node, visitor, context); + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; @@ -62457,14 +63976,14 @@ var ts; */ 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)); + var span = _a[_i]; + expressions.push(ts.visitNode(span.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)); + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); } } } @@ -63177,8 +64696,7 @@ var ts; case 190 /* FunctionExpression */: return visitFunctionExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } /** @@ -65222,6 +66740,7 @@ var ts; withBlockStack.pop(); } break; + // default: do nothing } } } @@ -66738,7 +68257,7 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" }; function createExportStarHelper(context, module) { var compilerOptions = context.getCompilerOptions(); @@ -66756,13 +68275,13 @@ var ts; var importStarHelper = { name: "typescript:commonjsimportstar", scoped: false, - text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" }; // emit helper for `import Name from "foo"` var importDefaultHelper = { name: "typescript:commonjsimportdefault", scoped: false, - text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" }; })(ts || (ts = {})); /// @@ -67100,12 +68619,12 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_1 = dependencyGroups_1[_i]; + var group_2 = dependencyGroups_1[_i]; // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -68317,6 +69836,1435 @@ var ts; } ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + 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 === 233 /* 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 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 === 233 /* 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; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */) { + 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; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || + (node.kind === 148 /* 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 /* 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 === 233 /* ClassDeclaration */ || node.kind === 148 /* 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 : + 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; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 156 /* 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(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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_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; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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 /* 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: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: + case 152 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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 === 233 /* 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 : + 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 232 /* 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 : + 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; + break; + default: + ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 154 /* 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 158 /* ConstructSignature */: + case 163 /* ConstructorType */: + // 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: + case 152 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + 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 === 233 /* 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 : + 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 232 /* FunctionDeclaration */: + case 162 /* FunctionType */: + 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 : + 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; + default: + ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + 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 233 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 234 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 158 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 157 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 153 /* MethodDeclaration */: + case 152 /* 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 === 233 /* 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 232 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 235 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 233 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + 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 { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJavaScript(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var enclosingDeclaration; + var necessaryTypeRefernces; + var possibleImports; + var importDeclarationMap; + var suppressNewDiagnosticContexts; + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + }; + var errorNameNode; + var currentSourceFile; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + var host = context.getEmitHost(); + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeRefernces.set(ref, true); + } + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!possibleImports) { + possibleImports = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(possibleImports, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(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) { + context.addDiagnostic(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 transformRoot(node) { + if (node.kind === 272 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + return node; + } + if (node.kind === 273 /* Bundle */) { + isBundledEmit = true; + var refs_1 = ts.createMap(); + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + return; // Omit declaration files from bundle results, too + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + possibleImports = undefined; + suppressNewDiagnosticContexts = false; + importDeclarationMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + collectReferences(sourceFile, refs_1); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, updated, /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs_1.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + possibleImports = undefined; + importDeclarationMap = ts.createMap(); + necessaryTypeRefernces = undefined; + var refs = collectReferences(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + refs.forEach(referenceVisitor); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + if (ts.isExternalModule(node) && !resultHasExternalModuleIndicator) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences()); + return updated; + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeRefernces ? ts.map(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getNodeId(elem), elem); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 71 /* Identifier */) { + return name; + } + else { + if (name.kind === 179 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 204 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 148 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + if (node.kind === 156 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 148 /* Parameter */ + || node.kind === 151 /* PropertyDeclaration */ + || node.kind === 150 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 237 /* ModuleDeclaration */: + case 234 /* InterfaceDeclaration */: + case 233 /* ClassDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 236 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 230 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 241 /* ImportEqualsDeclaration */: + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + case 247 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.forEach(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237 /* ModuleDeclaration */; + if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 252 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 244 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function filterCandidateImports(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + var unconsideredImports = []; + while (ts.length(possibleImports)) { + var i = possibleImports.shift(); + if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope + unconsideredImports.push(i); + continue; + } + // Eagerly transform import equals - if they're not visible, we'll get nothing, if they are, we'll immediately add them since it's complete + if (i.kind === 241 /* ImportEqualsDeclaration */) { + var result_3 = transformImportEqualsDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result_3); + continue; + } + // Import declarations, on the other hand, can be partially painted by multiple aliases; so we can see many indeterminate states + // until we've marked all possible visibility + var result = transformImportDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result); + } + // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not + // be considered in the child scope + possibleImports = unconsideredImports; + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.mapDefined(statements, function (statement) { + if (ts.isImportDeclaration(statement) || ts.isImportEqualsDeclaration(statement)) { + var key = "" + ts.getNodeId(statement); + if (importDeclarationMap.has(key)) { + var result = importDeclarationMap.get(key); + importDeclarationMap.delete(key); + return result; + } + else { + return undefined; + } + } + else { + return statement; + } + }); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, input.modifiers, input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 165 /* TypeLiteral */ || input.kind === 176 /* MappedType */) && input.parent.kind !== 235 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 205 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 161 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 158 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 154 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 153 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(152 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 155 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 156 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 151 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 150 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 152 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 157 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 159 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + } + case 230 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 147 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 170 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 162 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 163 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 153 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 247 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + if (input.expression.kind === 71 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + case 241 /* ImportEqualsDeclaration */: + case 242 /* ImportDeclaration */: { + // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later + // to reduce the likelihood we need to rewrite it + possibleImports = possibleImports || []; + ts.pushIfUnique(possibleImports, input); + return input; + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var previousNeedsDeclare; + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var oldPossibleImports; + switch (input.kind) { + case 235 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 234 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 232 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + return cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + } + case 237 /* ModuleDeclaration */: { + previousNeedsDeclare = needsDeclare; + needsDeclare = false; + oldPossibleImports = possibleImports; + possibleImports = undefined; + var inner = input.body; + if (inner && inner.kind === 238 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + needsDeclare = false; + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + } + } + case 233 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 71 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 85 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 212 /* VariableStatement */: { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return cleanup(ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes))); + } + case 236 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(returnValue) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (input.kind === 237 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + possibleImports = ts.concatenate(oldPossibleImports, possibleImports); + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (returnValue) { + if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) { + // Exported top-level member indicates moduleness + resultHasExternalModuleIndicator = true; + } + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 204 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function ensureModifiers(node) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 272 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((isBundledEmit && parentIsFile ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_6 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_6(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 234 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 155 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 230 /* VariableDeclaration */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: + case 148 /* Parameter */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 237 /* ModuleDeclaration */: + case 241 /* ImportEqualsDeclaration */: + case 234 /* InterfaceDeclaration */: + case 233 /* ClassDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 236 /* EnumDeclaration */: + case 212 /* VariableStatement */: + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + case 247 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 158 /* ConstructSignature */: + case 154 /* Constructor */: + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: + case 152 /* MethodSignature */: + case 157 /* CallSignature */: + case 159 /* IndexSignature */: + case 230 /* VariableDeclaration */: + case 147 /* TypeParameter */: + case 205 /* ExpressionWithTypeArguments */: + case 161 /* TypeReference */: + case 170 /* ConditionalType */: + case 162 /* FunctionType */: + case 163 /* ConstructorType */: + return true; + } + return false; + } +})(ts || (ts = {})); /// /// /// @@ -68330,6 +71278,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -68411,6 +71360,7 @@ var ts; var onSubstituteNode = function (_, node) { return node; }; var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; var state = 0 /* Uninitialized */; + var diagnostics = []; // The transformation context is provided to each transformer as part of transformer // initialization. var context = { @@ -68440,6 +71390,9 @@ var ts; 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; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); } }; // Ensure the parse tree is clean before applying transformations @@ -68462,7 +71415,8 @@ var ts; transformed: transformed, substituteNode: substituteNode, emitNodeWithNotification: emitNodeWithNotification, - dispose: dispose + dispose: dispose, + diagnostics: diagnostics }; function transformRoot(node) { return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; @@ -68665,8 +71619,8 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); + function createSourceMapWriter(host, writer, compilerOptions) { + if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSource; var currentSourceText; @@ -68679,11 +71633,11 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; + var sourceMapDataList; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, - getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitNodeWithSourceMap: emitNodeWithSourceMap, @@ -68704,13 +71658,14 @@ var ts; * @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) { + function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { if (disabled) { return; } if (sourceMapData) { reset(); } + sourceMapDataList = outputSourceMapDataList; currentSource = undefined; currentSourceText = undefined; // Current source map file and its index in the sources list @@ -68740,7 +71695,7 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 272 /* SourceFile */) { + if (sourceFileOrBundle.kind === 272 /* SourceFile */) { // emitting single module file // 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)); @@ -68768,6 +71723,10 @@ var ts; if (disabled) { return; } + // Record source map data for the test harness. + if (sourceMapDataList) { + sourceMapDataList.push(sourceMapData); + } currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -68775,6 +71734,7 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + sourceMapDataList = undefined; } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -68993,7 +71953,7 @@ var ts; } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(getText()); + var base64SourceMapText = ts.base64encode(ts.sys, getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; } else { @@ -69247,7 +72207,15 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -69275,6 +72243,8 @@ var ts; forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -69372,6 +72342,8 @@ var ts; } } function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (emitPos) emitPos(commentPos); ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); @@ -69389,1828 +72361,8 @@ var ts; } ts.createCommentWriter = createCommentWriter; })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var declarationDiagnostics = ts.createDiagnosticCollection(); - ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); - return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); - function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) { - var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false); - } - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 273 /* Bundle */; - var newLine = host.getNewLine(); - var compilerOptions = host.getCompilerOptions(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer; - createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var resultHasExternalModuleIndicator; - var currentText; - var currentLineMap; - var currentIdentifiers; - var isCurrentFileExternalModule; - var reportedDeclarationError = false; - var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; - var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - 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; - } - emittedReferencedFiles.push(referencedFile); - } - }); - } - resultHasExternalModuleIndicator = false; - if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - needsDeclare = true; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - needsDeclare = false; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - 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 === 242 /* ImportDeclaration */); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - increaseIndent(); - } - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - decreaseIndent(); - } - } - }); - setWriter(oldWriter); - allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - if (!isBundledEmit && ts.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 {};"); - writeLine(); - } - }); - if (usedTypeDirectiveReferences) { - ts.forEachKey(usedTypeDirectiveReferences, function (directive) { - referencesOutput += "/// " + newLine; - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput, - }; - function hasInternalAnnotation(range) { - var comment = currentText.substring(range.pos, range.end); - return ts.stringContains(comment, "@internal"); - } - function stripInternal(node) { - if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); - if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { - return; - } - emitNode(node); - } - } - function createAndSetNewTextWriterWithSymbolWriter() { - 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; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeProperty = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsynchronousModuleElements(nodes) { - var oldWriter = writer; - ts.forEach(nodes, function (declaration) { - var nodeToCheck; - if (declaration.kind === 230 /* VariableDeclaration */) { - nodeToCheck = declaration.parent.parent; - } - else if (declaration.kind === 245 /* NamedImports */ || declaration.kind === 246 /* ImportSpecifier */ || declaration.kind === 243 /* ImportClause */) { - ts.Debug.fail("We should be getting ImportDeclaration instead to write"); - } - else { - nodeToCheck = declaration; - } - var moduleElementEmitInfo = ts.forEach(moduleElementDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - 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 === 242 /* 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 { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); - asynchronousSubModuleDeclarationEmitInfo = []; - } - writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; - asynchronousSubModuleDeclarationEmitInfo = undefined; - } - moduleElementEmitInfo.asynchronousOutput = writer.getText(); - } - } - }); - setWriter(oldWriter); - } - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { - if (!typeReferenceDirectives) { - return; - } - if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); - } - for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { - var directive = typeReferenceDirectives_1[_i]; - if (!usedTypeDirectiveReferences.has(directive)) { - usedTypeDirectiveReferences.set(directive, directive); - } - } - } - function handleSymbolAccessibilityError(symbolAccessibilityResult) { - 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) { - if (errorInfo.typeName) { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - else { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); - } - function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - reportedDeclarationError = true; - 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_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); - } - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - // 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 === 148 /* Parameter */ && - (resolver.isRequiredInitializedParameter(declaration) || - resolver.isOptionalUninitializedParameterProperty(declaration)); - if (type && !shouldUseResolverType) { - // Write the type - emitType(type); - } - else { - errorNameNode = declaration.name; - var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | - 2048 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); - errorNameNode = undefined; - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - // Write the type - emitType(signature.type); - } - else { - errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - errorNameNode = undefined; - } - } - function emitLines(nodes) { - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var node = nodes_6[_i]; - emit(node); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; - if (!canEmitFn || canEmitFn(node)) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(node); - } - } - } - function emitCommaList(nodes, eachNodeEmitFn, canEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); - } - function writeJsDocComments(declaration) { - if (declaration) { - var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - // 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) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 135 /* ObjectKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 173 /* ThisType */: - case 177 /* LiteralType */: - return writeTextOfNode(currentText, type); - case 205 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(type); - case 161 /* TypeReference */: - return emitTypeReference(type); - case 164 /* TypeQuery */: - return emitTypeQuery(type); - case 166 /* ArrayType */: - return emitArrayType(type); - case 167 /* TupleType */: - return emitTupleType(type); - case 168 /* UnionType */: - return emitUnionType(type); - case 169 /* IntersectionType */: - return emitIntersectionType(type); - case 170 /* ConditionalType */: - return emitConditionalType(type); - case 171 /* InferType */: - return emitInferType(type); - case 172 /* ParenthesizedType */: - return emitParenType(type); - case 174 /* TypeOperator */: - return emitTypeOperator(type); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(type); - case 176 /* MappedType */: - return emitMappedType(type); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - return emitSignatureDeclarationWithJsDocComments(type); - case 165 /* TypeLiteral */: - return emitTypeLiteral(type); - case 71 /* Identifier */: - return emitEntityName(type); - case 145 /* QualifiedName */: - return emitEntityName(type); - case 160 /* TypePredicate */: - return emitTypePredicate(type); - } - function writeEntityName(entityName) { - if (entityName.kind === 71 /* Identifier */) { - writeTextOfNode(currentText, entityName); - } - else { - var left = entityName.kind === 145 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 145 /* QualifiedName */ ? entityName.right : entityName.name; - writeEntityName(left); - write("."); - writeTextOfNode(currentText, right); - } - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, - // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 241 /* 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 === 183 /* PropertyAccessExpression */); - emitEntityName(node.expression); - if (node.typeArguments) { - write("<"); - emitCommaList(node.typeArguments, emitType); - write(">"); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypePredicate(type) { - writeTextOfNode(currentText, type.parameterName); - write(" is "); - emitType(type.type); - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitIntersectionType(type) { - emitSeparatedList(type.types, " & ", emitType); - } - function emitConditionalType(node) { - emitType(node.checkType); - write(" extends "); - emitType(node.extendsType); - write(" ? "); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node.trueType; - emitType(node.trueType); - enclosingDeclaration = prevEnclosingDeclaration; - write(" : "); - emitType(node.falseType); - } - function emitInferType(node) { - write("infer "); - writeTextOfNode(currentText, node.typeParameter.name); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeOperator(type) { - write(ts.tokenToString(type.operator)); - write(" "); - emitType(type.type); - } - function emitIndexedAccessType(node) { - emitType(node.objectType); - write("["); - emitType(node.indexType); - write("]"); - } - function emitMappedType(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write("{"); - writeLine(); - increaseIndent(); - if (node.readonlyToken) { - write(node.readonlyToken.kind === 37 /* PlusToken */ ? "+readonly " : - node.readonlyToken.kind === 38 /* MinusToken */ ? "-readonly " : - "readonly "); - } - write("["); - writeEntityName(node.typeParameter.name); - write(" in "); - emitType(node.typeParameter.constraint); - write("]"); - if (node.questionToken) { - write(node.questionToken.kind === 37 /* PlusToken */ ? "+?" : - node.questionToken.kind === 38 /* MinusToken */ ? "-?" : - "?"); - } - write(": "); - emitType(node.type); - write(";"); - writeLine(); - decreaseIndent(); - write("}"); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - // write members - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentText = node.text; - currentLineMap = ts.getLineStarts(node); - currentIdentifiers = node.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(node); - enclosingDeclaration = node; - 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; - } - var count = 0; - while (true) { - count++; - var name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; - } - } - } - function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { - var tempVarName = getExportTempVariableName(baseName); - if (needsDeclare) { - write("declare "); - } - write("const "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - write(";"); - writeLine(); - return tempVarName; - } - function emitExportAssignment(node) { - if (ts.isSourceFile(node.parent)) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - } - if (node.expression.kind === 71 /* Identifier */) { - write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentText, node.expression); - } - else { - var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }, needsDeclare); - write(node.isExportEquals ? "export = " : "export default "); - write(tempVarName); - } - write(";"); - writeLine(); - // 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); - } - } - function isModuleElementVisible(node) { - return resolver.isDeclarationVisible(node); - } - function emitModuleElement(node, isModuleElementVisible) { - if (isModuleElementVisible) { - writeModuleElement(node); - } - else if (node.kind === 241 /* ImportEqualsDeclaration */ || - (node.parent.kind === 272 /* SourceFile */ && isCurrentFileExternalModule)) { - var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 272 /* SourceFile */) { - // Import declaration of another module that is visited async so lets put it in right spot - asynchronousSubModuleDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - else { - if (node.kind === 242 /* ImportDeclaration */) { - var importDeclaration = node; - if (importDeclaration.importClause) { - isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || - isVisibleNamedBinding(importDeclaration.importClause.namedBindings); - } - } - moduleElementDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - } - } - function writeModuleElement(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - return writeFunctionDeclaration(node); - case 212 /* VariableStatement */: - return writeVariableStatement(node); - case 234 /* InterfaceDeclaration */: - return writeInterfaceDeclaration(node); - case 233 /* ClassDeclaration */: - return writeClassDeclaration(node); - case 235 /* TypeAliasDeclaration */: - return writeTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: - return writeEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return writeModuleDeclaration(node); - case 241 /* ImportEqualsDeclaration */: - return writeImportEqualsDeclaration(node); - case 242 /* ImportDeclaration */: - return writeImportDeclaration(node); - default: - ts.Debug.fail("Unknown symbol kind"); - } - } - 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 === 272 /* SourceFile */) { - var modifiers = ts.getModifierFlags(node); - // If the node is exported - if (modifiers & 1 /* Export */) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - write("export "); - } - if (modifiers & 512 /* Default */) { - write("default "); - } - else if (node.kind !== 234 /* InterfaceDeclaration */ && needsDeclare) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(flags) { - if (flags & 8 /* Private */) { - write("private "); - } - else if (flags & 16 /* Protected */) { - write("protected "); - } - if (flags & 32 /* Static */) { - write("static "); - } - if (flags & 64 /* Readonly */) { - write("readonly "); - } - 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 /* Export */)) { - write("export "); - } - write("import "); - writeTextOfNode(currentText, node.name); - write(" = "); - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - emitExternalModuleSpecifier(node); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function isVisibleNamedBinding(namedBindings) { - if (namedBindings) { - if (namedBindings.kind === 244 /* NamespaceImport */) { - return resolver.isDeclarationVisible(namedBindings); - } - else { - return namedBindings.elements.some(function (namedImport) { return resolver.isDeclarationVisible(namedImport); }); - } - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1 /* Export */)) { - write("export "); - } - write("import "); - if (node.importClause) { - var currentWriterPos = writer.getTextPos(); - if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentText, node.importClause.name); - } - 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 === 244 /* NamespaceImport */) { - write("* as "); - writeTextOfNode(currentText, node.importClause.namedBindings.name); - } - else { - write("{ "); - emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); - write(" }"); - } - } - write(" from "); - } - emitExternalModuleSpecifier(node); - write(";"); - writer.writeLine(); - } - function emitExternalModuleSpecifier(parent) { - // 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 !== 237 /* ModuleDeclaration */; - var moduleSpecifier = parent.kind === 241 /* ImportEqualsDeclaration */ ? ts.getExternalModuleImportEqualsDeclarationExpression(parent) : - parent.kind === 237 /* ModuleDeclaration */ ? parent.name : parent.moduleSpecifier; - if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); - if (moduleName) { - write('"'); - write(moduleName); - write('"'); - return; - } - } - writeTextOfNode(currentText, moduleSpecifier); - } - function emitImportOrExportSpecifier(node) { - if (node.propertyName) { - writeTextOfNode(currentText, node.propertyName); - write(" as "); - } - writeTextOfNode(currentText, node.name); - } - 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) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - emitJsDocComments(node); - write("export "); - if (node.exportClause) { - write("{ "); - emitCommaList(node.exportClause.elements, emitExportSpecifier); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitExternalModuleSpecifier(node); - } - write(";"); - writer.writeLine(); - } - function writeModuleDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isGlobalScopeAugmentation(node)) { - write("global "); - } - else { - if (node.flags & 16 /* Namespace */) { - write("namespace "); - } - else { - write("module "); - } - if (ts.isExternalModuleAugmentation(node)) { - emitExternalModuleSpecifier(node); - } - else { - writeTextOfNode(currentText, node.name); - } - } - while (node.body && node.body.kind !== 238 /* ModuleBlock */) { - node = node.body; - write("."); - writeTextOfNode(currentText, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - if (node.body) { - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - else { - write(";"); - } - } - function writeTypeAliasDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function writeEnumDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentText, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentText, node.name); - var enumMemberValue = resolver.getConstantValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(ts.getTextOfConstantValue(enumMemberValue)); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 153 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - 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 === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - if (node.default && !isPrivateMethodTypeParameter(node)) { - write(" = "); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.default); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError); - } - } - 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 233 /* ClassDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 234 /* InterfaceDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 158 /* ConstructSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 157 /* CallSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 153 /* MethodDeclaration */: - case 152 /* 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 === 233 /* 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 232 /* FunctionDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - case 235 /* TypeAliasDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - } - else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { - write("null"); - } - function getHeritageClauseVisibilityError() { - var diagnosticMessage; - // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 233 /* 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 { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: ts.getNameOfDeclaration(node.parent.parent) - }; - } - } - } - function writeClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) { - emitPropertyDeclaration(param); - } - }); - } - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - var tempVarName; - if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { - 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 === 237 /* ModuleDeclaration */; })); - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.hasModifier(node, 128 /* Abstract */)) { - write("abstract "); - } - write("class "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - if (baseTypeNode) { - if (!ts.isEntityNameExpression(baseTypeNode.expression)) { - write(" extends "); - write(tempVarName); - if (baseTypeNode.typeArguments) { - write("<"); - emitCommaList(baseTypeNode.typeArguments, emitType); - write(">"); - } - } - else { - emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); - } - } - emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(ts.getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function writeInterfaceDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); - if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); - } - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - emitJsDocComments(node); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - emitVariableDeclaration(node); - 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 !== 230 /* VariableDeclaration */ || isVariableDeclarationVisible(node)) { - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */) && node.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (resolver.isLiteralConstDeclaration(node)) { - write(" = "); - resolver.writeLiteralConstValue(node, writer); - } - else if (!ts.hasModifier(node, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 230 /* 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* 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 /* 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 === 233 /* ClassDeclaration */ || node.kind === 148 /* 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 : - 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; - } - } - } - function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : 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 !== 204 /* OmittedExpression */ && isVariableDeclarationVisible(element)) { - elements.push(element); - } - } - emitCommaList(elements, emitBindingElement); - } - function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - writeTextOfNode(currentText, bindingElement.name); - 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 (ts.hasType(node)) { - write(": "); - emitType(node.type); - } - } - function isVariableStatementVisible(node) { - 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; - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isLet(node.declarationList)) { - write("let "); - } - else if (ts.isConst(node.declarationList)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); - write(";"); - writeLine(); - } - function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - var accessorWithTypeAnnotation; - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - 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) { - // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 155 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 155 /* 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 === 233 /* 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 === 156 /* 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_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_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; - } - } - else { - if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - 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 /* 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: accessorWithTypeAnnotation.name - }; - } - } - function writeFunctionDeclaration(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 === 232 /* FunctionDeclaration */) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 153 /* MethodDeclaration */ || node.kind === 154 /* Constructor */) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - } - if (node.kind === 232 /* FunctionDeclaration */) { - write("function "); - writeTextOfNode(currentText, node.name); - } - else if (node.kind === 154 /* Constructor */) { - write("constructor"); - } - else { - 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 === 233 /* 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); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var closeParenthesizedFunctionType = false; - if (node.kind === 159 /* IndexSignature */) { - // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - write("["); - } - else { - if (node.kind === 154 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { - write("();"); - writeLine(); - return; - } - // Construct signature or constructor type write new Signature - if (node.kind === 158 /* ConstructSignature */ || node.kind === 163 /* ConstructorType */) { - write("new "); - } - else if (node.kind === 162 /* 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("("); - } - } - emitTypeParameters(node.typeParameters); - write("("); - } - // Parameters - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 159 /* IndexSignature */) { - write("]"); - } - else { - write(")"); - } - // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 162 /* FunctionType */ || node.kind === 163 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 165 /* TypeLiteral */) { - // Emit type literal signature return type only if specified - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 154 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - else if (closeParenthesizedFunctionType) { - write(")"); - } - function getReturnTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - 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 === 233 /* 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 : - 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 232 /* 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 : - 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; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - 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 { - writeTextOfNode(currentText, node.name); - } - if (resolver.isOptionalParameter(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!ts.hasModifier(node.parent, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - switch (node.parent.kind) { - case 154 /* 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 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node.parent, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - 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 === 233 /* 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 : - 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 232 /* 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 : - 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; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - } - function emitBindingPattern(bindingPattern) { - // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 178 /* ObjectBindingPattern */) { - write("{"); - emitCommaList(bindingPattern.elements, emitBindingElement); - write("}"); - } - else if (bindingPattern.kind === 179 /* ArrayBindingPattern */) { - write("["); - var elements = bindingPattern.elements; - emitCommaList(elements, emitBindingElement); - if (elements && elements.hasTrailingComma) { - write(", "); - } - write("]"); - } - } - function emitBindingElement(bindingElement) { - if (bindingElement.kind === 204 /* 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, ,]) {} - // tslint:disable-next-line no-double-space - // emit : function foo([ , x, , ]) {} - write(" "); - } - else if (bindingElement.kind === 180 /* 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 /* 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("..."); - } - writeTextOfNode(currentText, bindingElement.name); - } - } - } - } - } - function emitNode(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 237 /* ModuleDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 234 /* InterfaceDeclaration */: - case 233 /* ClassDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: - return emitModuleElement(node, isModuleElementVisible(node)); - case 212 /* VariableStatement */: - return emitModuleElement(node, isVariableStatementVisible(node)); - case 242 /* ImportDeclaration */: - // Import declaration without import clause is visible, otherwise it is not visible - return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 248 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return writeFunctionDeclaration(node); - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 159 /* IndexSignature */: - return emitSignatureDeclarationWithJsDocComments(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return emitPropertyDeclaration(node); - case 271 /* EnumMember */: - return emitEnumMemberDeclaration(node); - case 247 /* ExportAssignment */: - return emitExportAssignment(node); - case 272 /* 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, - /*isAbsolutePathAnUrl*/ false); - referencesOutput += "/// " + newLine; - } - 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 === 273 /* Bundle */; - if (isBundledEmit && !addBundledFileReference) { - return; - } - ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); - declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; - addedBundledEmitReference = isBundledEmit; - } - } - } - /* @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 || emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var declarationOutput = emitDeclarationResult.referencesOutput - + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); - } - return emitSkipped; - 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); - declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); - return declarationOutput; - } - } - ts.writeDeclarationFile = writeDeclarationFile; -})(ts || (ts = {})); /// /// -/// /// /// var ts; @@ -71231,10 +72383,8 @@ var ts; var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var bundle = ts.createBundle(sourceFiles); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; } @@ -71243,10 +72393,7 @@ var ts; else { for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { var sourceFile = sourceFiles_1[_a]; - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); if (result) { return result; } @@ -71254,8 +72401,29 @@ var ts; } } ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 273 /* Bundle */) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + else { + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJavaScript(sourceFile); + var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; + return (options.sourceMap && !options.inlineSourceMap) ? 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. @@ -71274,51 +72442,31 @@ var ts; } return ".js" /* Js */; } - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 273 /* 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); - var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); var writer = ts.createTextWriter(newLine); var sourceMap = ts.createSourceMapWriter(host, writer); + var declarationSourceMap = ts.createSourceMapWriter(host, writer, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); var currentSourceFile; var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; - var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); - // 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); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); - // Clean up emit nodes on parse tree - transform.dispose(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -71326,19 +72474,9 @@ var ts; sourceMaps: sourceMapDataList }; 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 && !compilerOptions.emitDeclarationOnly) { - if (!emitOnlyDtsFiles) { - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); - } - } - else { - emitSkipped = true; - } - if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; - } + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { emittedFilesList.push(jsFilePath); @@ -71351,11 +72489,76 @@ var ts; } } } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Make sure not to write js file and source map file if any of them cannot be written + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + emitSkipped = true; + return; + } + if (emitOnlyDtsFiles) { + return; + } + // 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, + }); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true }), { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // sourcemap hooks + onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: declarationSourceMap.emitPos, + onSetSourceFile: setSourceFileForDeclarationSourceMaps, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + } + declarationTransform.dispose(); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 272 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); + mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { bundledHelpers = ts.createMap(); isOwnFileEmit = false; @@ -71366,22 +72569,18 @@ var ts; printer.writeFile(sourceFile, writer); } writer.writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); + var sourceMappingURL = mapRecorder.getSourceMappingURL(); if (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(), /*writeByteOrderMark*/ false, sourceFiles); - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); + if (sourceMapFilePath) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state - sourceMap.reset(); + mapRecorder.reset(); writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; @@ -71391,6 +72590,10 @@ var ts; currentSourceFile = node; sourceMap.setSourceFile(node); } + function setSourceFileForDeclarationSourceMaps(node) { + currentSourceFile = node; + declarationSourceMap.setSourceFile(node); + } function emitHelpers(node, writeLines) { var helpersEmitted = false; var bundle = node.kind === 273 /* Bundle */ ? node : undefined; @@ -71528,6 +72731,7 @@ var ts; emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpersIndirect(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { var sourceFile = _b[_a]; print(0 /* SourceFile */, sourceFile, sourceFile); @@ -71885,6 +73089,8 @@ var ts; // Enum case 271 /* EnumMember */: return emitEnumMember(node); + // JSDoc nodes (ignored) + // Transformation nodes (ignored) } // If the node is an expression, try to emit it as an expression with // substitution. @@ -72080,7 +73286,8 @@ var ts; else { emitTypeAnnotation(node.type); } - emitInitializer(node.initializer); + // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); } function emitDecorator(decorator) { writePunctuation("@"); @@ -72102,8 +73309,9 @@ var ts; emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); + emitIfPresent(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { @@ -72222,7 +73430,7 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); writePunctuation("}"); } @@ -72237,7 +73445,7 @@ var ts; } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 336 /* TupleTypeElements */); + emitList(node, node.elementTypes, 272 /* TupleTypeElements */); writePunctuation("]"); } function emitUnionType(node) { @@ -72348,7 +73556,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } // // Expressions @@ -72385,7 +73593,10 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - writePunctuation(shouldEmitDotDot ? ".." : "."); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -72411,9 +73622,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - writePunctuation("["); + var openPos = emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - writePunctuation("]"); + emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); @@ -72421,7 +73632,7 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - writeKeyword("new"); + emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); @@ -72439,9 +73650,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - writePunctuation("("); + var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -72459,22 +73670,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - writeKeyword("delete"); + emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - writeKeyword("typeof"); + emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - writeKeyword("void"); + emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - writeKeyword("await"); + emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -72542,7 +73753,7 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - writeKeyword("yield"); + emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } @@ -72586,17 +73797,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); - // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; emitList(node, node.statements, format); + emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -72611,15 +73818,15 @@ var ts; writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 215 /* IfStatement */) { writeSpace(); emit(node.elseStatement); @@ -72629,8 +73836,15 @@ var ts; } } } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } function emitDoStatement(node) { - writeKeyword("do"); + emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -72638,55 +73852,48 @@ var ts; else { writeLineOrSpace(node); } - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(");"); + emitWhileClause(node, node.statement.end); + writePunctuation(";"); } function emitWhileStatement(node) { - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(")"); + emitWhileClause(node, node.pos); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - writeSemicolon(); + pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.condition); - writeSemicolon(); + pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.incrementor); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("in"); + emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("of"); + emitTokenWithComment(144 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -72700,22 +73907,34 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } - function emitTokenWithComment(token, pos, writer, contextNode) { - var node = contextNode && ts.getParseTreeNode(contextNode); - if (node && node.kind === contextNode.kind) { + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); - if (node && node.kind === contextNode.kind) { + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; @@ -72726,35 +73945,35 @@ var ts; writeSemicolon(); } function emitWithStatement(node) { - writeKeyword("with"); + var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); - writePunctuation("("); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - writePunctuation(":"); + emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - writeKeyword("throw"); + emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); writeSemicolon(); } function emitTryStatement(node) { - writeKeyword("try"); + emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -72763,7 +73982,7 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - writeKeyword("finally"); + emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } @@ -72778,7 +73997,7 @@ var ts; function emitVariableDeclaration(node) { emit(node.name); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); @@ -72916,7 +74135,7 @@ var ts; increaseIndent(); } emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); @@ -72969,6 +74188,8 @@ var ts; } emit(node.name); var body = node.body; + if (!body) + return writeSemicolon(); while (body.kind === 237 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); @@ -72979,23 +74200,21 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); - writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); + emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); + emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - writePunctuation("="); + emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); writeSemicolon(); @@ -73010,12 +74229,12 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - writeKeyword("from"); + emitTokenWithComment(142 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -73024,15 +74243,15 @@ var ts; function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - writePunctuation(","); + emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - writePunctuation("*"); + var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -73043,41 +74262,42 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - writeOperator("="); + emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node); } else { - writeKeyword("default"); + emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); writeSemicolon(); } function emitExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - writePunctuation("*"); + nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); - writeKeyword("from"); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(142 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeKeyword("as"); + nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - writeKeyword("namespace"); + nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); writeSemicolon(); @@ -73090,14 +74310,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -73123,10 +74343,7 @@ var ts; writePunctuation("<"); emitJsxTagName(node.tagName); writeSpace(); - // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); - } + emit(node.attributes); writePunctuation("/>"); } function emitJsxFragment(node) { @@ -73138,11 +74355,10 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); - // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); - emit(node.attributes); } + emit(node.attributes); } writePunctuation(">"); } @@ -73189,44 +74405,31 @@ var ts; // Clauses // function emitCaseClause(node) { - writeKeyword("case"); + emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - writeKeyword("default"); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); } - function emitCaseOrDefaultClauseStatements(parentNode, statements) { + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { var emitAsSingleStatement = statements.length === 1 && ( // 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 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { + writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode); writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } + else { + emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + } emitList(parentNode, statements, format); } function emitHeritageClause(node) { @@ -73236,12 +74439,12 @@ var ts; emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -73287,7 +74490,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } // // Top-level nodes @@ -73308,11 +74511,31 @@ var ts; } emitSourceFileWorker(node); } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.referencedFiles, node.typeReferenceDirectives); + } + function emitTripleSlashDirectives(files, types) { + for (var _a = 0, files_1 = files; _a < files_1.length; _a++) { + var directive = files_1[_a]; + write("/// "); + writeLine(); + } + for (var _b = 0, types_18 = types; _b < types_18.length; _b++) { + var directive = types_18[_b]; + write("/// "); + writeLine(); + } + } function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -73404,10 +74627,10 @@ var ts; emit(node); } } - function emitInitializer(node) { + function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - writeOperator("="); + emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -73455,7 +74678,7 @@ var ts; emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures return emitTypeArguments(parentNode, parentNode.typeArguments); } emitList(parentNode, typeParameters, 26896 /* TypeParameters */); @@ -73532,6 +74755,9 @@ var ts; } if (format & 7680 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + } } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -73639,6 +74865,9 @@ var ts; onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { + if (isEmpty && !isUndefined) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists + } writePunctuation(getClosingBracket(format)); } } @@ -73735,9 +74964,9 @@ var ts; } function writeLines(text) { var lines = text.split(/\r\n?|\n/g); - var indentation = guessIndentation(lines); - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var lineText = lines_1[_a]; + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var lineText = lines_2[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); @@ -73746,21 +74975,6 @@ var ts; } } } - function guessIndentation(lines) { - var indentation; - 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) { - indentation = i; - break; - } - } - } - } - return indentation; - } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { increaseIndent(); @@ -73984,7 +75198,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -74029,8 +75243,15 @@ var ts; * 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. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName) { + function makeUniqueName(baseName, optimistic) { + if (optimistic) { + if (isUniqueName(baseName)) { + generatedNames.set(baseName, true); + return baseName; + } + } // Find the first unique 'name_n', where n is a positive number if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { baseName += "_"; @@ -74118,6 +75339,8 @@ var ts; return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); + case 5 /* OptimisticUnique */: + return makeUniqueName(ts.idText(name), /*optimistic*/ true); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -74219,7 +75442,7 @@ var ts; if (failed) { return ""; } - if (!commonPathComponents) { + if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } return ts.getNormalizedPathFromPathComponents(commonPathComponents); @@ -74351,8 +75574,7 @@ var ts; } 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(); + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " 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; @@ -74377,8 +75599,9 @@ var ts; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } @@ -74409,8 +75632,8 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { @@ -74451,9 +75674,7 @@ var ts; output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); output += " - "; } - var categoryColor = getCategoryFormat(diagnostic.category); - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { @@ -74764,8 +75985,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var sourceFile = files_1[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -74787,13 +76008,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_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -75419,6 +76640,8 @@ var ts; case 185 /* CallExpression */: case 186 /* NewExpression */: case 205 /* ExpressionWithTypeArguments */: + case 254 /* JsxSelfClosingElement */: + case 255 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -75426,8 +76649,8 @@ var ts; } break; } - for (var _b = 0, nodes_8 = nodes; _b < nodes_8.length; _b++) { - var node = nodes_8[_b]; + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; walk(node); } } @@ -75512,9 +76735,9 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 9 /* StringLiteral */ - ? b.kind === 9 /* StringLiteral */ && a.text === b.text - : b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText; + return a.kind === 71 /* Identifier */ + ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 9 /* StringLiteral */ && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -75533,7 +76756,7 @@ var ts; && !file.isDeclarationFile) { // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; @@ -75551,63 +76774,54 @@ var ts; file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { - switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { - break; + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // 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 (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // 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(node.name); } - 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 237 /* 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); } - 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, /*inAmbientModule*/ true); - } + // 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, /*inAmbientModule*/ true); } } } + } } } function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - (imports || (imports = [])).push(node.arguments[0]); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); } - else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) { - (imports || (imports = [])).push(node.arguments[0]); + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); } else { ts.forEachChild(node, collectDynamicImportOrRequireCalls); @@ -75706,6 +76920,7 @@ var ts; modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } + // See if we need to reprocess the imports due to prior skipped imports else if (file_1 && modulesWithElidedImports.get(file_1.path)) { if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports.set(file_1.path, false); @@ -75994,9 +77209,9 @@ var ts; if (options.out && options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } - if (options.mapRoot && !options.sourceMap) { + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { // Error to specify --mapRoot without --sourcemap - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { if (!options.declaration) { @@ -76006,6 +77221,9 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } + if (options.declarationMap && !options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } @@ -76021,14 +77239,14 @@ var ts; } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } 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)); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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) { @@ -76036,15 +77254,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - 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")); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } // 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) { + options.mapRoot) { // there is --mapRoot specified // 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 @@ -76060,7 +77278,7 @@ var ts; } if (options.emitDeclarationOnly) { if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -76159,18 +77377,18 @@ var ts; } return ts.emptyArray; } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } function getCompilerOptionsObjectLiteralSyntax() { @@ -76188,11 +77406,11 @@ var ts; } return _compilerOptionsObjectLiteralSyntax; } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { var props = ts.getPropertyAssignment(objectLiteral, key1, key2); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); } return !!props.length; } @@ -77147,7 +78365,7 @@ var ts; createNewValue: createMissingFileWatch, // Files that are no longer missing (e.g. because they are no longer required) // should no longer be watched. - onDeleteValue: closeFileWatcher + onDeleteValue: ts.closeFileWatcher }); } ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; @@ -77190,75 +78408,74 @@ var ts; return program.isEmittedFile(file); } ts.isEmittedFileOfProgram = isEmittedFileOfProgram; - function addFileWatcher(host, file, cb) { - return host.watchFile(file, cb); + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); } - 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); + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); } - 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); + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); return { close: function () { - if (!logOnlyTrigger) { - log(watcherCaption + "Close: " + info); - } + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); watcher.close(); } }; } - function closeFileWatcher(watcher) { - watcher.close(); + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : ""); } - ts.closeFileWatcher = closeFileWatcher; function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } @@ -77275,15 +78492,17 @@ var ts; var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // 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 nonRelaticeModuleNameCache = ts.createMap(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); - var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); - var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -77356,6 +78575,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); + nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); } function finishCachingPerDirectoryResolution() { @@ -77369,7 +78589,7 @@ var ts; clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); // 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; @@ -77415,15 +78635,8 @@ var ts; 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) { + watchFailedLookupLocationOfResolution(resolution); + if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { @@ -77503,8 +78716,9 @@ var ts; if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { return { dir: rootDir, dirPath: rootPath }; } - var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); - var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // 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); @@ -77530,78 +78744,91 @@ var ts; 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; - } + function watchFailedLookupLocationOfResolution(resolution) { + // No need to set the resolution refCount + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + 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]; + if (resolution.refCount !== undefined) { + resolution.refCount++; + return; + } + resolution.refCount = 1; + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_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; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; if (!ignore) { - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - if (dirWatcher) { - dirWatcher.refCount++; + // 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); + } + if (dirPath === rootPath) { + setAtRoot = true; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + setDirectoryWatcher(dir, dirPath); } } } + if (setAtRoot) { + setDirectoryWatcher(rootDir, rootPath); + } + } + function setDirectoryWatcher(dir, dirPath) { + 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); + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + return; } - } - function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { - var failedLookupLocations = _a.failedLookupLocations; - for (var i = startIndex; i < failedLookupLocations.length; i++) { - var failedLookupLocation = failedLookupLocations[i]; + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + if (!ignore) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - 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--; - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { @@ -77688,7 +78915,8 @@ var ts; // 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)) { + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory isChangedFailedLookupLocation = function (location) { var locationPath = resolutionHost.toPath(location); @@ -77717,7 +78945,17 @@ var ts; function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); } - function createTypeRootsWatch(_typeRootPath, typeRoot) { + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); @@ -77729,6 +78967,12 @@ var ts; // 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(); + // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered + // So handle to failed lookup locations here as well to ensure we are invalidating resolutions + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } }, 1 /* Recursive */); } /** @@ -77802,6 +79046,7 @@ var ts; ts.createDiagnosticReporter = createDiagnosticReporter; function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && + !options.preserveWatchOutput && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code && !options.extendedDiagnostics && !options.diagnostics) { @@ -78040,16 +79285,15 @@ var ts; parseConfigFile(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); - var writeLog = loggingEnabled ? trace : ts.noop; - var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; - var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; - var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectoryWorker = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var newLine = updateNewLine(); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, writeLog); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High); } var compilerHost = { // Members for CompilerHost @@ -78127,7 +79371,7 @@ var ts; return builderProgram; } // Compile the program - if (loggingEnabled) { + if (watchLogLevel !== ts.WatchLogLevel.None) { writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); @@ -78208,7 +79452,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); } } else { @@ -78222,7 +79466,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -78276,6 +79520,9 @@ var ts; (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); } else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } sourceFilesCache.delete(oldSourceFile.path); resolutionCache.removeResolutionsOfFile(oldSourceFile.path); } @@ -78360,10 +79607,10 @@ var ts; } } function watchDirectory(directory, cb, flags) { - return watchDirectoryWorker(host, directory, cb, flags, writeLog); + return watchDirectoryWorker(host, directory, cb, flags); } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -78495,6 +79742,13 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, { name: "watch", shortName: "w", @@ -78576,9 +79830,10 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "es2018.promise": "lib.es2018.promise.d.ts", + "es2018.regexp": "lib.es2018.regexp.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, @@ -78618,6 +79873,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, { name: "emitDeclarationOnly", type: "boolean", @@ -79609,7 +80871,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_6 = function (name) { + var _loop_7 = 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 @@ -79638,7 +80900,7 @@ var ts; } }; for (var name in options) { - _loop_6(name); + _loop_7(name); } return result; } @@ -80230,7 +81492,7 @@ var ts; function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); - var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; // 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. @@ -80420,22 +81682,6 @@ 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. @@ -80446,7 +81692,7 @@ var ts; for (var key in opts) { if (opts.hasOwnProperty(key)) { var type = getOptionFromName(key); - if (type !== undefined) { + if (type !== undefined) { // Ignore unknown options out[key] = getOptionValueWithEmptyStrings(opts[key], type); } } @@ -80456,11 +81702,11 @@ var ts; ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; function getOptionValueWithEmptyStrings(value, option) { switch (option.type) { - case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "". + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". return ""; - case "string":// Could be any arbitrary string -- use empty string instead. + case "string": // Could be any arbitrary string -- use empty string instead. return ""; - case "number":// Allow numbers, but be sure to check it's actually a 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 : ""; @@ -80504,6 +81750,8 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.defaultPreferences = {}; var TextChange = /** @class */ (function () { function TextChange() { } @@ -80896,16 +82144,13 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 71 /* Identifier */ && - (node.parent.kind === 222 /* BreakStatement */ || node.parent.kind === 221 /* ContinueStatement */) && - node.parent.label === node; + return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 /* Identifier */ && - node.parent.kind === 226 /* LabeledStatement */ && - node.parent.label === node; + return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; } + ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } @@ -81042,6 +82287,8 @@ var ts; case 5 /* Property */: // static method / property return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 6 /* Prototype */: + return "local class" /* localClassElement */; default: { ts.assertTypeIsNever(kind); return "" /* unknown */; @@ -81271,12 +82518,7 @@ var ts; // 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; - } - }); + var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); }); // 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; @@ -81516,6 +82758,102 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { + var tokenKind = token.kind; + var remainingMatchingTokens = 0; + while (true) { + token = findPrecedingToken(token.getFullStart(), sourceFile); + if (!token) { + return undefined; + } + if (token.kind === matchingTokenKind) { + if (remainingMatchingTokens === 0) { + return token; + } + remainingMatchingTokens--; + } + else if (token.kind === tokenKind) { + remainingMatchingTokens++; + } + } + } + ts.findPrecedingMatchingToken = findPrecedingMatchingToken; + function isPossiblyTypeArgumentPosition(token, sourceFile) { + // This function determines if the node could be type argument position + // Since during editing, when type argument list is not complete, + // the tree could be of any shape depending on the tokens parsed before current node, + // scanning of the previous identifier followed by "<" before current node would give us better result + // Note that we also balance out the already provided type arguments, arrays, object literals while doing so + var remainingLessThanTokens = 0; + while (token) { + switch (token.kind) { + case 27 /* LessThanToken */: + // Found the beginning of the generic argument expression + token = findPrecedingToken(token.getFullStart(), sourceFile); + var tokenIsIdentifier = token && ts.isIdentifier(token); + if (!remainingLessThanTokens || !tokenIsIdentifier) { + return tokenIsIdentifier; + } + remainingLessThanTokens--; + break; + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + remainingLessThanTokens = +3; + break; + case 46 /* GreaterThanGreaterThanToken */: + remainingLessThanTokens = +2; + break; + case 29 /* GreaterThanToken */: + remainingLessThanTokens++; + break; + case 18 /* CloseBraceToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); + if (!token) + return false; + break; + case 20 /* CloseParenToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); + if (!token) + return false; + break; + case 22 /* CloseBracketToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); + if (!token) + return false; + break; + // Valid tokens in a type name. Skip. + case 26 /* CommaToken */: + case 36 /* EqualsGreaterThanToken */: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 103 /* TypeOfKeyword */: + case 85 /* ExtendsKeyword */: + case 128 /* KeyOfKeyword */: + case 23 /* DotToken */: + case 49 /* BarToken */: + case 55 /* QuestionToken */: + case 56 /* ColonToken */: + break; + default: + if (ts.isTypeNode(token)) { + break; + } + // Invalid token in type + return false; + } + token = findPrecedingToken(token.getFullStart(), sourceFile); + } + return false; + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; /** * Returns true if the cursor at position in sourceFile is within a comment. * @@ -81712,16 +83050,6 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; - /** Add a value to a set, and return true if it wasn't already present. */ - function addToSeen(seen, key) { - key = String(key); - if (seen.has(key)) { - return false; - } - seen.set(key, true); - return true; - } - ts.addToSeen = addToSeen; function getSnapshotText(snap) { return snap.getText(0, snap.getLength()); } @@ -82019,32 +83347,35 @@ var ts; */ /* @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); - } - } + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); } ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + /* @internal */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + /* @internal */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } + function getFirstChild(node) { + return node.forEachChild(function (child) { return child; }); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -82258,7 +83589,7 @@ var ts; case 13 /* NoSubstitutionTemplateLiteral */: return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; default: - throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; @@ -82365,7 +83696,7 @@ var ts; case 0 /* None */: return { prefix: "" }; default: - throw ts.Debug.assertNever(lexState); + return ts.Debug.assertNever(lexState); } } function isBinaryExpressionOperatorToken(token) { @@ -82924,29 +84255,38 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function createPathCompletion(name, kind, span) { - return { name: name, kind: kind, span: span }; + function nameAndKind(name, kind) { + return { name: name, kind: kind }; + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind; + return ({ name: name, kind: kind, span: span }); + }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker)); + } + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + function getStringLiteralCompletionsFromModuleNamesWorker(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(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); } } else { // Check for node modules - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } - 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 @@ -82961,21 +84301,21 @@ var ts; // 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) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); var result = []; for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, host, exclude, result); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); } 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) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -83004,8 +84344,8 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var filePath = files_2[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; @@ -83016,7 +84356,7 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createPathCompletion(foundFile, "script" /* scriptElement */, span)); + result.push(nameAndKind(foundFile, "script" /* scriptElement */)); }); } // If possible, get folder completion as well @@ -83025,7 +84365,7 @@ var ts; 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(createPathCompletion(directoryName, "directory" /* directory */, span)); + result.push(nameAndKind(directoryName, "directory" /* directory */)); } } } @@ -83038,26 +84378,26 @@ var ts; * 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) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; var fileExtensions = ts.getSupportedExtensions(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (name, kind) { + var _loop_8 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { - result.push(createPathCompletion(name, kind, span)); + result.push(nameAndKind(name, kind)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_7(name, kind); + _loop_8(name, kind); } } } @@ -83066,14 +84406,14 @@ var ts; 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); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); } }); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { var moduleName = _d[_c]; - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } return result; } @@ -83180,23 +84520,13 @@ var ts; } 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); - return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); - } - 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; - } + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) + : undefined; + return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); @@ -83212,7 +84542,7 @@ var ts; try { typeRoots = ts.getEffectiveTypeRoots(options, host); } - catch (_b) { } + catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; @@ -83244,7 +84574,7 @@ var ts; } function pushResult(moduleName) { if (!seen.has(moduleName)) { - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); seen.set(moduleName, true); } } @@ -83308,9 +84638,11 @@ var ts; } // Replace everything after the last directory seperator that appears function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); } // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) function isPathRelativeToScript(path) { @@ -83360,7 +84692,7 @@ var ts; try { return ts.directoryProbablyExists(path, host); } - catch (_a) { } + catch ( /*ignore*/_a) { /*ignore*/ } return undefined; } function tryIOAndConsumeErrors(host, toApply) { @@ -83371,7 +84703,7 @@ var ts; try { return toApply && toApply.apply(host, args); } - catch (_a) { } + catch ( /*ignore*/_a) { /*ignore*/ } return undefined; } })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); @@ -83387,11 +84719,18 @@ var ts; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { + var GlobalsSearch; + (function (GlobalsSearch) { + GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue"; + GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; + GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; + })(GlobalsSearch || (GlobalsSearch = {})); + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && convertPathCompletions(entries); @@ -83400,19 +84739,19 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log); + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, preferences, compilerOptions.target); if (!completionData) { return undefined; } switch (completionData.kind) { case 0 /* Data */: - return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); case 1 /* JsDocTagName */: // If the current position is a jsDoc tag name, only tag names should be provided for completion return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); @@ -83422,11 +84761,11 @@ var ts; case 3 /* JsDocParameterName */: return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); default: - throw ts.Debug.assertNever(completionData); + return ts.Debug.assertNever(completionData); } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log) { + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -83435,12 +84774,12 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "var" /* variableElement */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } default: return ts.Debug.assertNever(completion); @@ -83458,8 +84797,8 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.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. @@ -83477,14 +84816,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, 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, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -83494,7 +84833,7 @@ var ts; if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isMemberCompletionKind(kind) { switch (kind) { @@ -83523,7 +84862,7 @@ var ts; } }); } - function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); if (!info) { return undefined; @@ -83531,12 +84870,12 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (includeInsertTextCompletions) { + if (preferences.includeCompletionsWithInsertText) { if (origin && origin.type === "this-type") { - insertText = needsConvertPropertyAccess ? "this[" + quote(name) + "]" : "this." + name; + insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; } else if (needsConvertPropertyAccess) { - insertText = "[" + quote(name) + "]"; + insertText = "[" + quote(name, preferences) + "]"; var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; @@ -83551,7 +84890,7 @@ var ts; } } } - if (insertText !== undefined && !includeInsertTextCompletions) { + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -83573,9 +84912,17 @@ var ts; replacementSpan: replacementSpan, }; } - function quote(text) { - // TODO: GH#20619 Use configured quote style - return JSON.stringify(text); + function quote(text, preferences) { + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || @@ -83587,7 +84934,7 @@ var ts; function getSourceFromOrigin(origin) { return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. @@ -83597,7 +84944,7 @@ var ts; for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { var symbol = symbols_4[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } @@ -83663,7 +85010,7 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeFromTypeNode(node.parent.parent.objectType).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); default: return undefined; } @@ -83681,8 +85028,7 @@ var ts; // foo({ // '/*completion position*/' // }); - var type = typeChecker.getContextualType(node.parent.parent); - return { kind: 1 /* Properties */, symbols: type && type.getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); } return fromContextualType(); case 184 /* ElementAccessExpression */: { @@ -83694,13 +85040,13 @@ var ts; // } // let a: A; // a['/*completion position*/'] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeAtLocation(expression).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); } return undefined; } case 185 /* CallExpression */: case 186 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { var argumentInfo_1 = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -83733,6 +85079,9 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker), typeChecker) }; } } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } function getStringLiteralTypes(type, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 32768 /* TypeParameter */) { @@ -83746,7 +85095,7 @@ var ts; } 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, includeInsertTextCompletions: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } @@ -83771,9 +85120,16 @@ var ts; || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; } - function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName, preferences) { var typeChecker = program.getTypeChecker(); var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker); + } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); switch (symbolCompletion.type) { @@ -83792,40 +85148,46 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, 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 }; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, codeActions, sourceDisplay); } - case "none": { + case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. - if (allKeywordsCompletions().some(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 allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createCompletionDetails(name, "" /* none */, "keyword" /* keyword */, [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)]) : undefined; } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo && symbolOriginInfo.type === "export" - ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) - : { codeActions: undefined, sourceDisplay: undefined }; + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, codeActions, sourceDisplay) { + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || symbolOriginInfo.type !== "export") { + return { codeActions: undefined, sourceDisplay: undefined }; + } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { @@ -83843,7 +85205,6 @@ var ts; var CompletionKind; (function (CompletionKind) { CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; - /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */ CompletionKind[CompletionKind["Global"] = 1] = "Global"; CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; @@ -83920,7 +85281,7 @@ var ts; function isModuleSymbol(symbol) { return symbol.declarations.some(function (d) { return d.kind === 272 /* SourceFile */; }); } - function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, preferences, target) { var start = ts.timestamp(); 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.) @@ -83930,6 +85291,7 @@ var ts; var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); var insideJsDocTagTypeExpression = false; + var isInSnippetScope = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { @@ -84103,9 +85465,9 @@ var ts; getTypeScriptMemberSymbols(); } else if (isRightOfOpenTag) { - var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNames(), "getJsxIntrinsicTagNames() should all be defined"); + var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); })); } else { symbols = tagSymbols; @@ -84130,7 +85492,7 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, position, sourceFile, typeChecker); - return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 287 /* JSDocParameterTag */: @@ -84147,6 +85509,7 @@ var ts; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile)); if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { @@ -84156,7 +85519,7 @@ var ts; var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; - var isValidAccess = isRhsOfImportDeclaration ? + var isValidAccess = allowTypeOrValue ? // 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; @@ -84179,6 +85542,7 @@ var ts; } } function addTypeProperties(type) { + isNewIdentifierLocation = hasIndexSignature(type); 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 @@ -84197,50 +85561,42 @@ var ts; } } function tryGetGlobalSymbols() { - var objectLikeContainer; - var namedImportsOrExports; - var classLikeContainer; - var jsxContainer; - if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { - 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 - completionKind = 5 /* None */; - // Declaring new property/method/accessor - isNewIdentifierLocation = true; - // 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 === 254 /* JsxSelfClosingElement */) || (jsxContainer.kind === 255 /* 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); - completionKind = 3 /* MemberLike */; - isNewIdentifierLocation = false; - return true; - } - } - } + var result = tryGetObjectLikeCompletionSymbols() + || tryGetImportOrExportClauseCompletionSymbols() + || tryGetConstructorCompletion() + || tryGetClassLikeCompletionSymbols() + || tryGetJsxCompletionSymbols() + || (getGlobalCompletions(), 1 /* Success */); + return result === 1 /* Success */; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) + return 0 /* Continue */; + // no members, only keywords + completionKind = 5 /* None */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 3 /* ConstructorParameterKeywords */; + return 1 /* Success */; + } + function tryGetJsxCompletionSymbols() { + var jsxContainer = tryGetContainingJsxElement(contextToken); + // Cursor is inside a JSX self-closing element or opening element + var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + if (!attrsType) + return 0 /* Continue */; + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + return 1 /* Success */; + } + function getGlobalCompletions() { if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 3 /* FunctionLikeBodyKeywords */; + keywordFilters = 4 /* FunctionLikeBodyKeywords */; } // Get all entities in the current scope. - completionKind = 5 /* None */; + completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -84274,13 +85630,11 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (isGlobalCompletionScope(scopeNode)) { - completionKind = 1 /* Global */; - } - var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + isInSnippetScope = isSnippetScope(scopeNode); + var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (options.includeInsertTextCompletions && scopeNode.kind !== 272 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 272 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { @@ -84290,13 +85644,13 @@ var ts; } } } - if (options.includeExternalModuleExports) { + // Don't suggest import completions for a commonjs-only module + if (preferences.includeCompletionsForModuleExports && !(sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator)) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } filterGlobalCompletion(symbols); - return true; } - function isGlobalCompletionScope(scopeNode) { + function isSnippetScope(scopeNode) { switch (scopeNode.kind) { case 272 /* SourceFile */: case 200 /* TemplateExpression */: @@ -84308,9 +85662,10 @@ var ts; } } function filterGlobalCompletion(symbols) { - var isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - if (isTypeCompletion) - keywordFilters = 4 /* TypeKeywords */; + var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile); + if (isTypeOnlyCompletion) + keywordFilters = 5 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -84322,19 +85677,22 @@ var ts; if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); } - if (isTypeCompletion) { + if (allowTypes) { // Its a type, but you can reach it by namespace.type as well - return symbolCanBeReferencedAtTypeLocation(symbol); + var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); + if (symbolAllowedAsType || isTypeOnlyCompletion) { + return symbolAllowedAsType; + } } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); }); } function isContextTokenValueLocation(contextToken) { return contextToken && contextToken.kind === 103 /* TypeOfKeyword */ && - contextToken.parent.kind === 164 /* TypeQuery */; + (contextToken.parent.kind === 164 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { @@ -84358,7 +85716,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 793064 /* Type */) { + if (symbol.flags & 67901928 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -84472,7 +85830,7 @@ var ts; || containingNodeKind === 159 /* IndexSignature */ // [ | : string ] || containingNodeKind === 146 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 129 /* ModuleKeyword */: // module | - case 130 /* NamespaceKeyword */:// namespace | + case 130 /* NamespaceKeyword */: // namespace | return true; case 23 /* DotToken */: return containingNodeKind === 237 /* ModuleDeclaration */; // module A.| @@ -84491,10 +85849,10 @@ var ts; return containingNodeKind === 151 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": + switch (keywordForNode(previousToken)) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: return true; } } @@ -84526,18 +85884,19 @@ var ts; * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + function tryGetObjectLikeCompletionSymbols() { + var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); + if (!objectLikeContainer) + return 0 /* Continue */; // We're looking up possible property names from contextual/inferred/declared type. completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 182 /* 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; + return 2 /* Fail */; + isNewIdentifierLocation = hasIndexSignature(typeForObject); typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); existingMembers = objectLikeContainer.properties; } @@ -84547,7 +85906,7 @@ var ts; isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (!ts.isVariableLike(rootDeclaration)) - throw ts.Debug.fail("Root declaration is not variable-like."); + return ts.Debug.fail("Root declaration is not variable-like."); // 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. @@ -84565,7 +85924,7 @@ var ts; if (canGetType) { var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); if (!typeForObject) - return false; + return 2 /* Fail */; // 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; @@ -84575,7 +85934,7 @@ var ts; // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); } - return true; + return 1 /* Success */; } /** * Aggregates relevant symbols for completion in import clauses and export clauses @@ -84592,72 +85951,70 @@ var ts; * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + function tryGetImportOrExportClauseCompletionSymbols() { + var namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken); + if (!namedImportsOrExports) + return undefined; + // cursor is in an import clause + // try to show exported member for imported module var declarationKind = namedImportsOrExports.kind === 245 /* NamedImports */ ? 242 /* ImportDeclaration */ : 248 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { - return false; + return 2 /* Fail */; } completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { symbols = ts.emptyArray; - return true; + return 2 /* Fail */; } var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); - return true; + return 1 /* Success */; } /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. */ - function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + function tryGetClassLikeCompletionSymbols() { + var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location); + if (!decl) + return 0 /* Continue */; // We're looking up possible property names from parent type. completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - // 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 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 /* Private */; - break; - case "static": - classElementModifierFlags = classElementModifierFlags | 32 /* Static */; - break; - } - } - // No member list for private methods - if (!(classElementModifierFlags & 8 /* Private */)) { - var baseClassTypeToGetPropertiesFrom = void 0; - if (baseTypeNode) { - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); - if (classElementModifierFlags & 32 /* Static */) { - // Use static class to get property symbols from - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); - } - } - 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); + keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + // If you're in an interface you don't want to repeat things from super-interface. So just stop here. + if (!ts.isClassLike(decl)) + return 1 /* Success */; + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // 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 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; } } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + // List of property symbols of base type that are not private and already implemented + var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } + return 1 /* Success */; } /** * Returns the immediate owning object literal or binding pattern of a context token, @@ -84667,7 +86024,7 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */:// const x = { a: 0, | + case 26 /* CommaToken */: // const x = { a: 0, | var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; @@ -84685,7 +86042,7 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // import { | - case 26 /* CommaToken */:// import { a as 0, | + case 26 /* CommaToken */: // import { a as 0, | switch (contextToken.parent.kind) { case 245 /* NamedImports */: case 249 /* NamedExports */: @@ -84695,61 +86052,9 @@ var ts; } return undefined; } - function isFromClassElementDeclaration(node) { - return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); - } - function isParameterOfConstructorDeclaration(node) { - return ts.isParameter(node) && ts.isConstructorDeclaration(node.parent); - } function isConstructorParameterCompletion(node) { - return node.parent && - 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 /* OpenBraceToken */:// class c { | - if (ts.isClassLike(contextToken.parent)) { - return contextToken.parent; - } - break; - // class c {getValue(): number, | } - case 26 /* CommaToken */: - if (ts.isClassLike(contextToken.parent)) { - return contextToken.parent; - } - break; - // 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) && - (isClassMemberCompletionKeyword(contextToken.kind) || - isClassMemberCompletionKeywordText(contextToken.getText()))) { - return contextToken.parent.parent; - } - } - } - // class c { method() { } | method2() { } } - if (location && location.kind === 293 /* SyntaxList */ && ts.isClassLike(location.parent)) { - return location.parent; - } - return undefined; + return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent) + && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node)); } /** * Returns the immediate owning class declaration of a context token, @@ -84871,14 +86176,7 @@ var ts; return containingNodeKind === 267 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: - return containingNodeKind === 236 /* EnumDeclaration */ || // enum a { | - containingNodeKind === 234 /* InterfaceDeclaration */ || // interface a { | - containingNodeKind === 165 /* TypeLiteral */; // const x : { | - case 25 /* SemicolonToken */: - return containingNodeKind === 150 /* PropertySignature */ && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 234 /* InterfaceDeclaration */ || // interface a { f; | - contextToken.parent.parent.kind === 165 /* TypeLiteral */); // const x : { a; | + return containingNodeKind === 236 /* EnumDeclaration */; // enum a { | case 27 /* LessThanToken */: return containingNodeKind === 233 /* ClassDeclaration */ || // class A< | containingNodeKind === 203 /* ClassExpression */ || // var C = class D< | @@ -84901,7 +86199,7 @@ var ts; containingNodeKind === 244 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromClassElementDeclaration(contextToken)) { + if (isFromObjectTypeDeclaration(contextToken)) { return false; } // falls through @@ -84914,13 +86212,12 @@ var ts; case 110 /* LetKeyword */: case 76 /* ConstKeyword */: case 116 /* YieldKeyword */: - case 139 /* TypeKeyword */:// type htm| + case 139 /* 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)) { + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; } if (isConstructorParameterCompletion(contextToken)) { @@ -84929,28 +86226,28 @@ var ts; // - its name of the parameter and not being edited // eg. constructor(a |<- this shouldnt show completion if (!ts.isIdentifier(contextToken) || - isConstructorParameterCompletionKeywordText(contextToken.getText()) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || isCurrentlyEditingNode(contextToken)) { return false; } } // Previous token may have been a keyword that was converted to an identifier. - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": + switch (keywordForNode(contextToken)) { + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 75 /* ClassKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 83 /* EnumKeyword */: + case 89 /* FunctionKeyword */: + case 109 /* InterfaceKeyword */: + case 110 /* LetKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 115 /* StaticKeyword */: + case 104 /* VarKeyword */: + case 116 /* YieldKeyword */: return true; } return ts.isDeclarationName(contextToken) @@ -85029,7 +86326,7 @@ var ts; // 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); + existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } existingMemberNames.set(existingName, true); } @@ -85040,7 +86337,7 @@ var ts; * * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags */ - function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; @@ -85060,10 +86357,7 @@ var ts; continue; } // 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)) { + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { continue; } var existingName = ts.getPropertyNameForPropertyNameNode(m.name); @@ -85071,23 +86365,11 @@ var ts; existingMemberNames.set(existingName, true); } } - var result = []; - 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++) { - var property = properties_12[_i]; - if (isValidProperty(property, inValidModifierFlags)) { - result.push(property); - } - } - } - function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.escapedName) && - propertySymbol.getDeclarations() && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); - } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. @@ -85110,7 +86392,7 @@ var ts; return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { - return node.getStart() <= position && position <= node.getEnd(); + return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { @@ -85133,10 +86415,10 @@ var ts; // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2 /* PropertyAccess */: - case 5 /* None */: case 1 /* Global */: // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 5 /* None */: case 4 /* String */: return validIdentiferResult; default: @@ -85166,62 +86448,36 @@ var ts; return kind !== 140 /* UndefinedKeyword */; case 1 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* ConstructorParameterKeywords */: - return isConstructorParameterCompletionKeyword(kind); - case 3 /* FunctionLikeBodyKeywords */: - return isFunctionLikeBodyCompletionKeyword(kind); - case 4 /* TypeKeywords */: + case 2 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 3 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 4 /* FunctionLikeBodyKeywords */: + return !isClassMemberCompletionKeyword(kind); + case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); } })); } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 132 /* ReadonlyKeyword */; + } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: case 123 /* ConstructorKeyword */: - case 132 /* ReadonlyKeyword */: case 125 /* GetKeyword */: case 136 /* SetKeyword */: case 120 /* AsyncKeyword */: return true; + default: + return ts.isClassMemberModifier(kind); } } - function isClassMemberCompletionKeywordText(text) { - return isClassMemberCompletionKeyword(ts.stringToToken(text)); - } - function isConstructorParameterCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - } - } - function isConstructorParameterCompletionKeywordText(text) { - return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); - } - function isFunctionLikeBodyCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: - case 117 /* AbstractKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 140 /* UndefinedKeyword */: - return false; - } - return true; + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } function isEqualityOperatorKind(kind) { switch (kind) { @@ -85279,6 +86535,48 @@ var ts; }); return ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined"); } + /** + * 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 tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 293 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 25 /* SemicolonToken */: // class c {getValue(): number; | } + case 18 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 17 /* OpenBraceToken */: // class c { | + case 26 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && (ts.isClassElement(node.parent) || ts.isTypeElement(node.parent)) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -85309,30 +86607,17 @@ var ts; } function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); - return referenceEntries && convertReferencedSymbols(referenceEntries); - } - function convertReferencedSymbols(referenceEntries) { - var fileNameToDocumentHighlights = ts.createMap(); - for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { - var entry = referenceEntries_1[_i]; - var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span; - var highlightSpans = fileNameToDocumentHighlights.get(fileName); - if (!highlightSpans) { - fileNameToDocumentHighlights.set(fileName, highlightSpans = []); - } - highlightSpans.push(span_12); - } - return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) { + if (!referenceEntries) + return undefined; + var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); + return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; return ({ fileName: fileName, highlightSpans: highlightSpans }); }); } function getSyntacticDocumentHighlights(node, sourceFile) { var highlightSpans = getHighlightSpans(node, sourceFile); - if (!highlightSpans || highlightSpans.length === 0) { - return undefined; - } - return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { @@ -85873,7 +87158,9 @@ var ts; } else if (ts.isDefaultImport(direct)) { var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); - addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + if (!isAvailableThroughGlobal) { + addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + } directImports.push(direct); } else { @@ -86025,7 +87312,7 @@ var ts; 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) { + if (!isForRename) { // If renaming `foo`, don't touch `bar`, just `foo`. // Search locally for `bar`. addSearch(name, checker.getSymbolAtLocation(name)); } @@ -86121,8 +87408,8 @@ var ts; function forEachImport(sourceFile, action) { if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); } } else { @@ -86149,19 +87436,6 @@ var ts; }); } } - function importerFromModuleSpecifier(moduleSpecifier) { - var decl = moduleSpecifier.parent; - switch (decl.kind) { - case 185 /* CallExpression */: - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - return decl; - case 252 /* 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. @@ -86200,12 +87474,15 @@ var ts; return exportInfo(symbol, getExportKindForDeclaration(exportNode)); } } + // If we are in `export = a;` or `export default a;`, `parent` is the export assignment. else if (ts.isExportAssignment(parent)) { return getExportAssignmentExport(parent); } + // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. else if (ts.isExportAssignment(parent.parent)) { return getExportAssignmentExport(parent.parent); } + // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } @@ -86276,10 +87553,10 @@ var ts; return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } var decl = importedSymbol.valueDeclaration; - if (ts.isExportAssignment(decl)) { + if (ts.isExportAssignment(decl)) { // `export = class {}` return ts.Debug.assertDefined(decl.expression.symbol); } - else if (ts.isBinaryExpression(decl)) { + else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } return ts.Debug.fail(); @@ -86356,8 +87633,8 @@ var ts; if (parent.kind === 272 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 238 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent)); - return parent.parent; + ts.Debug.assert(parent.kind === 238 /* ModuleBlock */); + return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { return node.kind === 237 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; @@ -86379,12 +87656,13 @@ var ts; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {}); var checker = program.getTypeChecker(); return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { var definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. - return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }; + return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) }; }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; @@ -86404,9 +87682,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 269 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -86420,8 +87698,8 @@ var ts; } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); - return ts.map(x, toReferenceEntry); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { @@ -86429,60 +87707,50 @@ var ts; return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); - } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); } - function definitionToReferencedSymbolDefinitionInfo(def, checker) { + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { case "symbol": { - var symbol = def.symbol, node_3 = def.node; - var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var symbol = def.symbol; + var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - 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)] }; + 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)] }; } case "keyword": { - var node_5 = def.node; - var name_5 = ts.tokenToString(node_5.kind); - return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* 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 */ }] }; } case "this": { - 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 }; + 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 }; } case "string": { - 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)] }; + 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)] }; } + default: + return ts.Debug.assertNever(def); } })(); - if (!info) { - return undefined; - } var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); - return { - containerKind: "" /* unknown */, - containerName: "", - fileName: sourceFile.fileName, - kind: kind, - name: name, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: displayParts - }; + var textSpan = getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile); + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: textSpan, displayParts: displayParts }; } - function getDefinitionKindAndDisplayParts(symbol, node, checker) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind; + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); + var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } function toReferenceEntry(entry) { @@ -86513,7 +87781,7 @@ var ts; function implementationKindDisplayParts(node, checker) { var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node); if (symbol) { - return getDefinitionKindAndDisplayParts(symbol, node, checker); + return getDefinitionKindAndDisplayParts(symbol, checker, node); } else if (node.kind === 182 /* ObjectLiteralExpression */) { return { @@ -86547,8 +87815,8 @@ var ts; return { fileName: fileName, span: span }; } FindAllReferences.toHighlightSpan = toHighlightSpan; - function getTextSpan(node) { - var start = node.getStart(); + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); var end = node.getEnd(); if (node.kind === 9 /* StringLiteral */) { start += 1; @@ -86606,7 +87874,7 @@ var ts; case 248 /* ExportDeclaration */: return true; case 185 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); default: return false; } @@ -86638,10 +87906,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ - definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, - references: references - }]; + return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -86649,17 +87914,15 @@ var ts; 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.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 if (ts.isLabelOfLabeledStatement(node)) { + // 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); @@ -86673,11 +87936,11 @@ var ts; function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); + var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); var result = []; var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === 79 /* DefaultKeyword */) { - addReference(node, symbol, node, state); + addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { @@ -86686,7 +87949,7 @@ var ts; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); } else { // Global search @@ -86781,7 +88044,11 @@ var ts; this.symbolIdToReferences = []; // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. this.sourceFileToSeenSymbols = []; + this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; }); } + State.prototype.includesSourceFile = function (sourceFile) { + return this.includedSourceFiles.has(sourceFile.fileName); + }; /** 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) @@ -86795,11 +88062,11 @@ var ts; // 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). - 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 _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { - location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, + symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, }; }; @@ -86807,12 +88074,12 @@ var ts; * 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) { + State.prototype.referenceAdder = function (searchSymbol) { var symbolId = ts.getSymbolId(searchSymbol); var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references }); + this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; @@ -86837,7 +88104,7 @@ var ts; 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); + var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; addRef(singleRef); @@ -86873,7 +88140,9 @@ var ts; 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 /* Import */), state); + var exportingFile = declaration.getSourceFile(); + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); } } /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ @@ -86973,6 +88242,17 @@ var ts; // 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; } + /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ + function isSymbolReferencedInFile(definition, checker, sourceFile) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return true; // Be lenient with invalid code. + return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) { + var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), ts.isIdentifier); + return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol; + }); + } + Core.isSymbolReferencedInFile = isSymbolReferencedInFile; function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } var positions = []; @@ -87003,18 +88283,13 @@ var ts; return positions; } function getLabelReferencesInNode(container, targetLabel) { - var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); - for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { - var position = possiblePositions_1[_i]; + var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) { 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)); - } - } + return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined; + }); return [{ definition: { type: "label", node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { @@ -87022,9 +88297,11 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.text.length === searchSymbolName.length; + case 9 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + str.text.length === searchSymbolName.length; + } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; case 79 /* DefaultKeyword */: @@ -87034,43 +88311,35 @@ var ts; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { - var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); - } + return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; + }); + }); return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } - function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - 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, /*includeJsDocComment*/ true); - if (referenceLocation.kind === kind) { - references.push(FindAllReferences.nodeEntry(referenceLocation)); - } - } - } - function getReferencesInSourceFile(sourceFile, search, state) { + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } state.cancellationToken.throwIfCancellationRequested(); - return getReferencesInContainer(sourceFile, sourceFile, search, state); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); } /** * 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) { + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; - getReferencesAtLocation(sourceFile, position, search, state); + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } - function getReferencesAtLocation(sourceFile, position, search, state) { + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { 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 @@ -87099,7 +88368,7 @@ var ts; } if (ts.isExportSpecifier(parent)) { ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); - getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); @@ -87109,7 +88378,8 @@ var ts; } switch (state.specialSearchKind) { case 0 /* None */: - addReference(referenceLocation, relatedSymbol, search.location, state); + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); break; case 1 /* Constructor */: addConstructorReferences(referenceLocation, sourceFile, search, state); @@ -87122,7 +88392,7 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -87138,8 +88408,8 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, name, state); + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { + addReference(name, referenceSymbol, state); } } else { @@ -87161,7 +88431,8 @@ var ts; searchForImportedSymbol(imported, state); } function addRef() { - addReference(referenceLocation, localSymbol, search.location, state); + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); } } function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { @@ -87206,11 +88477,11 @@ var ts; * 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); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state); } } - function addReference(referenceLocation, relatedSymbol, searchLocation, state) { - var addRef = state.referenceAdder(relatedSymbol, searchLocation); + function addReference(referenceLocation, relatedSymbol, state) { + var addRef = state.referenceAdder(relatedSymbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } @@ -87221,9 +88492,9 @@ var ts; /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ function addConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { - addReference(referenceLocation, search.symbol, search.location, state); + addReference(referenceLocation, search.symbol, state); } - var pusher = function () { return state.referenceAdder(search.symbol, search.location); }; + var pusher = function () { return state.referenceAdder(search.symbol); }; if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. @@ -87238,11 +88509,11 @@ var ts; } } function addClassStaticThisReferences(referenceLocation, search, state) { - addReference(referenceLocation, search.symbol, search.location, state); - if (ts.isClassLike(referenceLocation.parent)) { + addReference(referenceLocation, search.symbol, state); + if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); // This is the class declaration. - addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol)); } } function addStaticThisReferences(classLike, pusher) { @@ -87367,7 +88638,7 @@ var ts; return result; } function getContainingTypeReference(node) { - var topLevelTypeReference = undefined; + var topLevelTypeReference; while (node) { if (ts.isTypeNode(node)) { topLevelTypeReference = node; @@ -87421,58 +88692,29 @@ var ts; * distinction between structurally compatible implementations and explicit implementations, so we * must use the AST. * - * @param child A class or interface Symbol + * @param symbol 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 /* Interface */; - return searchHierarchy(child); - function searchHierarchy(symbol) { - if (symbol === parent) { - return true; - } - var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); - var cached = cachedResults.get(key); - 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)) { - if (parentIsInterface) { - var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); - if (interfaceReferences) { - for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { - var typeReference = interfaceReferences_1[_i]; - if (searchTypeReference(typeReference)) { - return true; - } - } - } - } - return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - } - else if (declaration.kind === 234 /* InterfaceDeclaration */) { - if (parentIsInterface) { - return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); - } - } - return false; - }); - cachedResults.set(key, inherits); - return inherits; + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; } - function searchTypeReference(typeReference) { - if (typeReference) { + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { var type = checker.getTypeAtLocation(typeReference); - if (type && type.symbol) { - return searchHierarchy(type.symbol); - } - } - return false; - } + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; } function getReferencesForSuperKeyword(superKeyword) { var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); @@ -87495,24 +88737,19 @@ var ts; default: return undefined; } - var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== 97 /* SuperKeyword */) { - continue; + return; } 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 }]; + return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -87547,18 +88784,11 @@ var ts; return undefined; } var references = []; - var possiblePositions; - if (searchSpaceNode.kind === 272 /* SourceFile */) { - ts.forEach(sourceFiles, function (sourceFile) { - cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); - getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, staticFlag, references); - }); - } - else { - var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); - getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, references); + for (var _i = 0, _a = searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + cancellationToken.throwIfCancellationRequested(); + var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode); + getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFile : searchSpaceNode, positions, staticFlag, references); } return [{ definition: { type: "this", node: thisOrSuperKeyword }, @@ -87602,26 +88832,17 @@ var ts; }); } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { - var references = []; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); - getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); - } + return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) { + var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false), ts.isStringLiteral); + return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + }); + }); return [{ definition: { type: "string", node: node }, references: references }]; - 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_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. @@ -87703,9 +88924,6 @@ var ts; * 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: @@ -87717,25 +88935,17 @@ var ts; // 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)) { + if (!symbol || previousIterationSymbolsCache.has(symbol.escapedName)) { return; } 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 === 234 /* InterfaceDeclaration */) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = checker.getTypeAtLocation(typeReference); - if (type) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + for (var _b = 0, _c = ts.getAllSuperTypeNodes(declaration); _b < _c.length; _b++) { + var typeReference = _c[_b]; + var type = checker.getTypeAtLocation(typeReference); + if (!type) + continue; var propertySymbol = checker.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push.apply(result, checker.getRootSymbols(propertySymbol)); @@ -87793,7 +89003,10 @@ var ts; return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { // if it is in the list, then we are done if (search.includes(rootSymbol)) { - return rootSymbol; + // For a root symbol that is a component of a union or intersection, use the original (union/intersection) symbol. + // That we when a symbol references the whole union we avoid claiming it references some particular member of the union. + // For a transient symbol we want to use the root symbol instead. + return ts.getCheckFlags(sym) & 6 /* Synthetic */ ? sym : rootSymbol; } // 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 @@ -87805,7 +89018,7 @@ var ts; } var result = []; getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); - return ts.find(result, search.includes); + return result.some(search.includes) ? rootSymbol : undefined; } return undefined; }); @@ -87838,7 +89051,9 @@ var ts; * 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) { + function getIntersectingMeaningFromDeclarations(node, symbol) { + var meaning = ts.getMeaningFromLocation(node); + var declarations = symbol.declarations; if (declarations) { var lastIterationMeaning = void 0; do { @@ -87859,36 +89074,12 @@ var ts; } return meaning; } + Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; function isImplementation(node) { - if (!node) { - return false; - } - else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { - return true; - } - else if (node.kind === 230 /* VariableDeclaration */) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); - } - else if (ts.isFunctionLike(node)) { - return !!node.body || ts.hasModifier(node, 2 /* Ambient */); - } - else { - switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: - return true; - } - } - return false; - } - function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 212 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 231 /* VariableDeclarationList */); - return node.parent.parent; - } + return !!(node.flags & 2097152 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); } function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { var refSymbol = checker.getSymbolAtLocation(node); @@ -87915,12 +89106,6 @@ var ts; function tryGetClassByExtendingIdentifier(node) { return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); } - function isNameOfExternalModuleImportOrDeclaration(node) { - 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 @@ -87962,9 +89147,8 @@ var ts; } // Labels if (ts.isJumpStatementTarget(node)) { - var labelName = node.text; - var label = ts.getTargetLabel(node.parent, labelName); - return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined; + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -88177,8 +89361,8 @@ var ts; return createDefinitionInfo(decl, symbolKind, symbolName, containerName); } function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; + for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { + var ref = refs_2[_i]; if (ref.pos <= pos && pos <= ref.end) { return ref; } @@ -88820,8 +90004,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88903,7 +90087,7 @@ var ts; case 6 /* NameContainsNonURISafeCharacters */: return "Package name '" + typing + "' contains non URI safe characters"; case 0 /* Ok */: - throw ts.Debug.fail(); // Shouldn't have called this. + return ts.Debug.fail(); // Shouldn't have called this. default: ts.Debug.assertNever(result); } @@ -88919,19 +90103,19 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_8 = function (sourceFile) { + var _loop_9 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; } - ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { + sourceFile.getNamedDeclarations().forEach(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_8(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_9(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -88990,41 +90174,35 @@ var ts; return true; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - var text = ts.getTextOfIdentifierOrLiteral(name); - if (text !== undefined) { - containers.unshift(text); - } - else if (name.kind === 146 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } - } + var name = ts.getNameOfDeclaration(declaration); + if (name && ts.isPropertyNameLiteral(name)) { + containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); + return true; + } + else if (name && name.kind === 146 /* 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) { + if (ts.isPropertyNameLiteral(expression)) { + var text = ts.getTextOfIdentifierOrLiteral(expression); if (includeLastPortion) { containers.unshift(text); } return true; } - if (expression.kind === 183 /* PropertyAccessExpression */) { - var propertyAccess = expression; + if (ts.isPropertyAccessExpression(expression)) { if (includeLastPortion) { - containers.unshift(propertyAccess.name.text); + containers.unshift(expression.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); + return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true); } return false; } @@ -89327,6 +90505,7 @@ var ts; case 1 /* ExportsProperty */: case 2 /* ModuleExports */: case 3 /* PrototypeProperty */: + case 6 /* Prototype */: addNodeWithRecursiveChild(node, node.right); break; case 4 /* ThisProperty */: @@ -89663,16 +90842,20 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } + // See if it is a var initializer. If so, use the var name. else if (node.parent.kind === 230 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } + // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. else if (node.parent.kind === 198 /* BinaryExpression */ && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } + // See if it is a property assignment, and if so use the property name else if (node.parent.kind === 268 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } + // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -89697,44 +90880,111 @@ var ts; (function (ts) { var OrganizeImports; (function (OrganizeImports) { - function organizeImports(sourceFile, formatContext, host) { - // TODO (https://github.com/Microsoft/TypeScript/issues/10020): sort *within* ambient modules (find using isAmbientModule) - // All of the old ImportDeclarations in the file, in syntactic order. - var oldImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - if (oldImportDecls.length === 0) { - return []; - } - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { - return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); - }); - var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { - return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup)) - : importGroup; - }); + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); - // Delete or replace the first import. - if (newImportDecls.length === 0) { - changeTracker.deleteNode(sourceFile, oldImportDecls[0]); - } - else { - // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - useNonAdjustedStartPosition: false, - useNonAdjustedEndPosition: false, - suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + // All of the old ImportDeclarations in the file, in syntactic order. + var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(topLevelImportDecls); + for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { + var ambientModule = _a[_i]; + var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(ambientModuleImportDecls); } return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls) { + if (ts.length(oldImportDecls) === 0) { + return; + } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); + var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); + var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { + return getExternalModuleName(importGroup[0].moduleSpecifier) + ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + : importGroup; + }); + // Delete or replace the first import. + if (newImportDecls.length === 0) { + changeTracker.deleteNode(sourceFile, oldImportDecls[0], { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + }); + } + else { + // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), + }); + } + // Delete any subsequent imports. + for (var i = 1; i < oldImportDecls.length; i++) { + changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + } + } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports) { - return oldImports; // TODO (https://github.com/Microsoft/TypeScript/issues/10020) + function getModuleBlock(moduleDecl) { + var body = moduleDecl.body; + return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + } + function removeUnusedImports(oldImports, sourceFile, program) { + var typeChecker = program.getTypeChecker(); + var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var usedImports = []; + for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { + var importDecl = oldImports_1[_i]; + var importClause = importDecl.importClause; + if (!importClause) { + // Imports without import clauses are assumed to be included for their side effects and are not removed. + usedImports.push(importDecl); + continue; + } + var name = importClause.name, namedBindings = importClause.namedBindings; + // Default import + if (name && !isDeclarationUsed(name)) { + name = undefined; + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + // Namespace import + if (!isDeclarationUsed(namedBindings.name)) { + namedBindings = undefined; + } + } + else { + // List of named imports + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); + if (newElements.length < namedBindings.elements.length) { + namedBindings = newElements.length + ? ts.updateNamedImports(namedBindings, newElements) + : undefined; + } + } + } + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + // The JSX factory symbol is always used. + return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + } } function getExternalModuleName(specifier) { return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier) @@ -89749,7 +90999,7 @@ var ts; if (importGroup.length === 0) { return importGroup; } - var _a = getImportParts(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; + var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; var coalescedImports = []; if (importWithoutClause) { coalescedImports.push(importWithoutClause); @@ -89758,15 +91008,17 @@ var ts; // produce two import declarations in this special case. if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { // Add the namespace import to the existing default ImportDeclaration. - var defaultImportClause = defaultImports[0].parent; - coalescedImports.push(updateImportDeclarationAndClause(defaultImportClause, defaultImportClause.name, namespaceImports[0])); + var defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); return coalescedImports; } - var sortedNamespaceImports = ts.stableSort(namespaceImports, function (n1, n2) { return compareIdentifiers(n1.name, n2.name); }); + var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { + return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); + }); for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { var namespaceImport = sortedNamespaceImports_1[_i]; // Drop the name, if any - coalescedImports.push(updateImportDeclarationAndClause(namespaceImport.parent, /*name*/ undefined, namespaceImport)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -89774,30 +91026,37 @@ var ts; var newDefaultImport; var newImportSpecifiers = []; if (defaultImports.length === 1) { - newDefaultImport = defaultImports[0]; + newDefaultImport = defaultImports[0].importClause.name; } else { for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { var defaultImport = defaultImports_1[_b]; - newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (n) { return n.elements; })); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || compareIdentifiers(s1.name, s2.name); }); - var importClause = defaultImports.length > 0 - ? defaultImports[0].parent - : namedImports[0].parent; + var importDecl = defaultImports.length > 0 + ? defaultImports[0] + : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 ? undefined : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0], sortedImportSpecifiers); - coalescedImports.push(updateImportDeclarationAndClause(importClause, newDefaultImport, newNamedImports)); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; - function getImportParts(importGroup) { + /* + * Returns entire import declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + * + * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`. + */ + function getCategorizedImports(importGroup) { var importWithoutClause; var defaultImports = []; var namespaceImports = []; @@ -89812,14 +91071,14 @@ var ts; } var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; if (name) { - defaultImports.push(name); + defaultImports.push(importDeclaration); } if (namedBindings) { if (ts.isNamespaceImport(namedBindings)) { - namespaceImports.push(namedBindings); + namespaceImports.push(importDeclaration); } else { - namedImports.push(namedBindings); + namedImports.push(importDeclaration); } } } @@ -89833,12 +91092,11 @@ var ts; function compareIdentifiers(s1, s2) { return ts.compareStringsCaseSensitive(s1.text, s2.text); } - function updateImportDeclarationAndClause(importClause, name, namedBindings) { - var importDeclaration = importClause.parent; - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, name, namedBindings), importDeclaration.moduleSpecifier); - } } OrganizeImports.coalesceImports = coalesceImports; + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + } /* internal */ // Exported for testing function compareModuleSpecifiers(m1, m2) { var name1 = getExternalModuleName(m1); @@ -89886,13 +91144,13 @@ var ts; 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+(.*))?$/); + var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/); 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")); + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region")); } else { var region = regions.pop(); @@ -90131,10 +91389,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_14 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false)); + /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); } } } @@ -90236,7 +91494,7 @@ var ts; // // Only if all words have some sort of match is the pattern considered matched. var subWordTextChunks = segment.subWordTextChunks; - var matches = undefined; + var matches; for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { var subWordTextChunk = subWordTextChunks_1[_i]; // Try to match the candidate with this word @@ -90284,8 +91542,8 @@ var ts; // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; - var firstMatch = undefined; - var contiguous = undefined; + var firstMatch; + var contiguous; while (true) { // Let's consider our termination cases if (currentChunkSpan === chunkCharacterSpans.length) { @@ -90585,11 +91843,18 @@ var ts; function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { if (readImportFiles === void 0) { readImportFiles = true; } if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } - var referencedFiles = []; - var typeReferenceDirectives = []; + var pragmaContext = { + languageVersion: 1 /* ES5 */, + pragmas: undefined, + checkJsDirective: undefined, + referencedFiles: [], + typeReferenceDirectives: [], + amdDependencies: [], + hasNoDefaultLib: undefined, + moduleName: undefined + }; var importedFiles = []; 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 @@ -90604,23 +91869,6 @@ var ts; } return token; } - function processTripleSlashDirectives() { - var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); - ts.forEach(commentRanges, function (commentRange) { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); - if (referencePathMatchResult) { - isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; - if (fileReference) { - var collection = referencePathMatchResult.isTypeReferenceDirective - ? typeReferenceDirectives - : referencedFiles; - collection.push(fileReference); - } - } - }); - } function getFileReference() { var fileName = ts.scanner.getTokenValue(); var pos = ts.scanner.getTokenPos(); @@ -90881,7 +92129,8 @@ var ts; if (readImportFiles) { processImports(); } - processTripleSlashDirectives(); + ts.processCommentPragmas(pragmaContext, sourceText); + ts.processPragmasIntoFields(pragmaContext, ts.noop); if (externalModule) { // for external modules module all nested ambient modules are augmentations if (ambientExternalModules) { @@ -90891,7 +92140,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; } else { // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 @@ -90910,7 +92159,7 @@ var ts; } } } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -90941,22 +92190,17 @@ var ts; 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(); + var declarations = symbol.declarations; if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. - if (ts.some(declarations, isDefinedInLibraryFile)) { + if (declarations.some(isDefinedInLibraryFile)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // 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 */) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - if (!kind) { - return undefined; - } var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; @@ -90965,12 +92209,11 @@ var ts; return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } - else if (node.kind === 9 /* StringLiteral */) { + else if (ts.isStringLiteral(node)) { 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" /* variableElement */, "" /* none */, node, sourceFile); + return getRenameInfoSuccess(node.text, node.text, "var" /* variableElement */, "" /* none */, node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -91428,11 +92671,75 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program) { + program.getSemanticDiagnostics(sourceFile); + var checker = program.getDiagnosticsProducingTypeChecker(); + var diags = []; + if (sourceFile.commonJsModuleIndicator) { + diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + } + var isJsFile = ts.isSourceFileJavaScript(sourceFile); + function check(node) { + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 190 /* FunctionExpression */: + if (isJsFile) { + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + } + break; + } + if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + node.forEachChild(check); + } + check(sourceFile); + if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); + if (!name) + continue; + var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + } + } + } + return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + } + ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + function importNameForConvertToDefaultImport(node) { + switch (node.kind) { + case 242 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 241 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + if (result !== "" /* unknown */) { + return result; + } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { return ts.getDeclarationOfKind(symbol, 203 /* ClassExpression */) ? @@ -91446,17 +92753,14 @@ var ts; return "interface" /* interfaceElement */; if (flags & 262144 /* TypeParameter */) return "type parameter" /* typeParameterElement */; - var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - 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 */; - } + 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; @@ -91637,7 +92941,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) { + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) { // At constructor keyword of constructor declaration // 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 @@ -92119,7 +93423,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_10 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -92138,7 +93442,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_10(opt); } return options; } @@ -92915,7 +94219,7 @@ var ts; // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 234 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one + case 234 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -93749,8 +95053,8 @@ var ts; 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 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); + var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { @@ -94717,26 +96021,14 @@ var ts; function isControlFlowEndingStatement(kind, parent) { switch (kind) { case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: - switch (parent.kind) { - case 211 /* Block */: - var grandParent = parent.parent; - switch (grandParent && grandParent.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - // We may want to write inner functions after this. - return false; - default: - return true; - } - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 272 /* SourceFile */: - case 238 /* ModuleBlock */: - return true; - default: - throw ts.Debug.fail(); + case 227 /* ThrowStatement */: { + if (parent.kind !== 211 /* Block */) { + return true; } + var grandParent = parent.parent; + // In a function, we may want to write inner functions after this. + return !(grandParent && grandParent.kind === 190 /* FunctionExpression */ || grandParent.kind === 232 /* FunctionDeclaration */); + } case 221 /* ContinueStatement */: case 222 /* BreakStatement */: return true; @@ -94813,14 +96105,14 @@ var ts; ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; })(ChangeKind || (ChangeKind = {})); - function getSeparatorCharacter(separator) { - return ts.tokenToString(separator.kind); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - textChanges_1.getSeparatorCharacter = getSeparatorCharacter; function getAdjustedStartPosition(sourceFile, node, options, position) { if (options.useNonAdjustedStartPosition) { - return node.getStart(); + return node.getStart(sourceFile); } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); @@ -94847,7 +96139,6 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } - textChanges_1.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { return node.getEnd(); @@ -94858,7 +96149,6 @@ var ts; ? newEnd : end; } - textChanges_1.getAdjustedEndPosition = getAdjustedEndPosition; /** * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ @@ -94874,10 +96164,9 @@ var ts; } var ChangeTracker = /** @class */ (function () { /** Public for tests only. Other callers should use `ChangeTracker.with`. */ - function ChangeTracker(newLineCharacter, formatContext, validator) { + function ChangeTracker(newLineCharacter, formatContext) { this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; - this.validator = validator; this.changes = []; this.deletedNodesInLists = []; // 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 @@ -94895,6 +96184,7 @@ var ts; this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; }; + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); @@ -94954,47 +96244,39 @@ var ts; } return this; }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); }; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); - return this; + this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + }; + ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -95012,14 +96294,45 @@ var ts; var pos = before.getStart(sourceFile); this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); + var text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: { pos: pos, end: pos }, text: text }); + }; + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ + ChangeTracker.prototype.insertTypeAnnotation = function (sourceFile, node, type) { + var end = (ts.isFunctionLike(node) + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + ? ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile) || ts.first(node.parameters) + : node.kind !== 230 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name).end; + this.insertNodeAt(sourceFile, end, type, { prefix: ": " }); + }; + ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { + // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter + var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); + }; ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { if (ts.isStatement(before) || ts.isClassElement(before)) { return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; } - else if (ts.isVariableDeclaration(before)) { + else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2; return { suffix: ", " }; } - throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + else if (ts.isParameter(before)) { + return {}; + } + return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it }; ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { var firstStatement = ts.firstOrUndefined(ctr.body.statements); @@ -95040,7 +96353,7 @@ var ts; } }; ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { - this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); @@ -95074,17 +96387,11 @@ var ts; // 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 /* SemicolonToken */) - }); + this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, { pos: endPosition, end: endPosition }, newNode, this.getInsertNodeAfterOptions(after)); + return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); }; ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { @@ -95096,7 +96403,10 @@ var ts; else if (ts.isVariableDeclaration(node)) { return { prefix: ", " }; } - throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it + else if (ts.isParameter(node)) { + return {}; + } + return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, @@ -95161,17 +96471,9 @@ var ts; // let insert position be the beginning of the line that contains next element startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, - 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)) - } - }); + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -95203,13 +96505,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: ts.createToken(separator), - options: {} - }); + this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); // 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 @@ -95217,22 +96513,10 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: insertPos, end: insertPos }, - node: newNode, - options: { indentation: indentation, prefix: this.newLineCharacter } - }); + this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: newNode, - options: { prefix: ts.tokenToString(separator) + " " } - }); + this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; @@ -95244,95 +96528,86 @@ var ts; var newCls = cls.kind === 233 /* ClassDeclaration */ ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); - _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + _this.replaceNode(sourceFile, cls, newCls); }); }; - ChangeTracker.prototype.getChanges = function () { - var _this = this; + /** + * Note: after calling this, the TextChanges object must be discarded! + * @param validate only for tests + * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions, + * so we can only call this once and can't get the non-formatted text separately. + */ + ChangeTracker.prototype.getChanges = function (validate) { this.finishInsertNodeAtClassStart(); - return ts.group(this.changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { - var sourceFile = changesInFile[0].sourceFile; - var textChanges = ChangeTracker.normalize(changesInFile).map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), _this.computeNewText(c, sourceFile)); - }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; - }); - }; - ChangeTracker.prototype.computeNewText = function (change, sourceFile) { - var _this = this; - if (change.kind === ChangeKind.Remove) { - // deletion case - return ""; - } - var options = change.options || {}; - var text; - var pos = change.range.pos; - var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - if (change.kind === ChangeKind.ReplaceWithMultipleNodes) { - var lastIndex_1 = change.nodes.length - 1; - var parts = change.nodes.map(function (n, index) { - var formatted = _this.getFormattedTextOfNode(n, sourceFile, pos, options); - return index === lastIndex_1 || ts.endsWith(formatted, _this.newLineCharacter) - ? formatted - : (formatted + _this.newLineCharacter); - }); - text = parts.join(""); - } - else { - 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 || ""); - }; - ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) { - var nonformattedText = getNonformattedText(node, sourceFile, this.newLineCharacter); - if (this.validator) { - this.validator(nonformattedText); - } - var formatOptions = this.formatContext.options; - var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - var initialIndentation = options.indentation !== undefined - ? options.indentation - : (options.useIndentationFromFile !== false) - ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter)) - : 0; - var delta = options.delta !== undefined - ? options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(node) - ? (formatOptions.indentSize || 0) - : 0; - 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); - } - return normalized; + return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); }; return ChangeTracker; }()); textChanges_1.ChangeTracker = ChangeTracker; - function getNonformattedText(node, sourceFile, newLine) { - var writer = new Writer(newLine); - var printer = ts.createPrinter({ newLine: newLine === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */ }, writer); - printer.writeNode(4 /* Unspecified */, node, sourceFile, writer); - return { text: writer.getText(), node: assignPositionsToNode(node) }; - } - 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, formatContext); - return applyChanges(nonFormattedText.text, changes); - } + var changesToText; + (function (changesToText) { + function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { + return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + var sourceFile = changesInFile[0].sourceFile; + // order changes by start position + var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); + var _loop_11 = function (i) { + ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { + return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + }); + }; + // verify that change intervals do not overlap, except possibly at end points. + for (var i = 0; i < normalized.length - 1; i++) { + _loop_11(i); + } + var textChanges = normalized.map(function (c) { + return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + }); + return { fileName: sourceFile.fileName, textChanges: textChanges }; + }); + } + changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + if (change.kind === ChangeKind.Remove) { + return ""; + } + if (change.kind === ChangeKind.Text) { + return change.text; + } + var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; + var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; + var text = change.kind === ChangeKind.ReplaceWithMultipleNodes + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter) + : format(change.node); + // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line + var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + return (options.prefix || "") + noIndent + (options.suffix || ""); + } + /** Note: this may mutate `nodeIn`. */ + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; + if (validate) + validate(node, text); + var formatOptions = formatContext.options; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn) ? (formatOptions.indentSize || 0) : 0; + } + var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; + var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); + return applyChanges(text, changes); + } + /** Note: output node may be mutated input node. */ + function getNonformattedText(node, sourceFile, newLineCharacter) { + var writer = new Writer(newLineCharacter); + var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + return { text: writer.getText(), node: assignPositionsToNode(node) }; + } + })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; @@ -95502,7 +96777,7 @@ var ts; 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])) { + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { position = ranges[0].end; advancePastLineBreak(); ranges = ranges.slice(1); @@ -95530,6 +96805,10 @@ var ts; } } } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + } + textChanges_1.isValidLocationToAddComment = isValidLocationToAddComment; })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -95539,6 +96818,22 @@ var ts; (function (codefix) { var codeFixRegistrations = []; var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(changes, description) { + return createCodeFixActionWorker(diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(description, changes, fixId, fixAllDescription, command) { + return { description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } function registerCodeFix(reg) { for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { var error = _a[_i]; @@ -95602,16 +96897,9 @@ var ts; return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; - function codeFixAllWithTextChanges(context, errorCodes, use) { - var changes = []; - eachDiagnostic(context, errorCodes, function (diag) { return use(changes, diag); }); - changes.sort(function (a, b) { return b.span.start - a.span.start; }); - return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); - } - codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges; function eachDiagnostic(_a, errorCodes, cb) { var program = _a.program, sourceFile = _a.sourceFile; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) { + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) { var diag = _b[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); @@ -95661,7 +96949,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, @@ -95677,6 +96965,797 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "annotateWithTypeFromJSDoc"; + var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var decl = getDeclaration(diag.file, diag.start); + if (decl) + doChange(changes, diag.file, decl); + }); }, + }); + function getDeclaration(file, pos) { + var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false); + // For an arrow function with no name, 'name' lands on the first parameter. + return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc; + function hasUsableJSDoc(decl) { + return ts.isFunctionLikeDeclaration(decl) + ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)) + : !decl.type && !!ts.getJSDocType(decl); + } + function doChange(changes, sourceFile, decl) { + if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { + if (!decl.typeParameters) { + var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); + if (typeParameters) + changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19 /* OpenParenToken */)); + for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (!param.type) { + var paramType = ts.getJSDocType(param); + if (paramType) + changes.insertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20 /* CloseParenToken */)); + if (!decl.type) { + var returnType = ts.getJSDocReturnType(decl); + if (returnType) + changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + } + } + else { + var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix + ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. + changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + } + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 230 /* VariableDeclaration */ || + node.kind === 150 /* PropertySignature */ || + node.kind === 151 /* PropertyDeclaration */; + } + function transformJSDocType(node) { + switch (node.kind) { + case 275 /* JSDocAllType */: + case 276 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 279 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 278 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 277 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 281 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 280 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 161 /* 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) { + return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 281 /* 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 === 134 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* 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; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertFunctionToEs6Class"; + var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, + }); + function doChange(changes, sourceFile, position, checker) { + var deletedNodes = []; + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false)); + if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + // Bad input + return undefined; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 232 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 230 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return undefined; + } + copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); + for (var _i = 0, deletedNodes_1 = deletedNodes; _i < deletedNodes_1.length; _i++) { + var _a = deletedNodes_1[_i], node = _a.node, inList = _a.inList; + if (inList) { + changes.deleteNodeInList(sourceFile, node); + } + else { + changes.deleteNode(sourceFile, node); + } + } + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + // If parent node has already been deleted, do nothing + if (!deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n.node); })) { + deletedNodes.push({ node: node, inList: inList }); + } + } + 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, /*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 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + 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) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + 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 === 214 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 190 /* FunctionExpression */: { + var functionExpression = assignmentBinaryExpression.right; + 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, sourceFile); + return method; + } + case 191 /* ArrowFunction */: { + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 211 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + } + 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, sourceFile); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + return prop; + } + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 190 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + 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(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + 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 copyComments(sourceNode, targetNode, sourceFile) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + 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); + }); + } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, sourceFile, changes); + } + } + }); + // No support for fix-all since this applies to the whole file at once anyway. + return [codefix.createCodeFixActionNoFixId(changes, ts.Diagnostics.Convert_to_ES6_module)]; + }, + }); + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 241 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + break; + case 185 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); + } + break; + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 212 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 214 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 185 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + } + return false; + } + case 198 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 178 /* ObjectBindingPattern */: + case 179 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 269 /* ShorthandPropertyAssignment */: + case 270 /* SpreadAssignment */: + return undefined; + case 268 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); + case 153 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right)); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 190 /* FunctionExpression */: + case 191 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 203 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 185 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 190 /* FunctionExpression */: { + var expressionName = exported.name; + if (expressionName && expressionName.text !== name) { + // `exports.f = function g() {}` -> `export const f = function g() {}` + return exportConst(); + } + } + // falls through + case 191 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 203 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + return exportConst(); + } + function exportConst() { + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 178 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 179 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 183 /* PropertyAccessExpression */: + return parent.name !== node; + case 180 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + return makeImportDeclaration(name, namedImports, moduleSpecifier); + } + function makeImportDeclaration(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier); + } + codefix.makeImportDeclaration = makeImportDeclaration; + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -95689,8 +97768,8 @@ var ts; if (!qualifiedName) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); - return [{ description: description, changes: changes, fixId: fixId }]; + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -95727,11 +97806,8 @@ var ts; var classDeclaration = getClass(sourceFile, span.start); var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - return { description: description, changes: changes, fixId: fixId }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, fixIds: [fixId], @@ -95742,31 +97818,29 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); }, }); function getClass(sourceFile, pos) { - var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)); - ts.Debug.assert(!!classDeclaration); - return classDeclaration; + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false))); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { // 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 /* Private */); }); var classType = checker.getTypeAtLocation(classDeclaration); - if (!checker.getIndexTypeOfType(classType, 1 /* Number */)) { + if (!classType.getNumberIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } - if (!checker.getIndexTypeOfType(classType, 0 /* String */)) { + if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { @@ -95793,7 +97867,7 @@ var ts; if (!info) return undefined; var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs ? ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); @@ -95803,7 +97877,7 @@ var ts; getAllCodeActions: function (context) { var seenNames = ts.createMap(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var program = context.program; + var program = context.program, preferences = context.preferences; var info = getInfo(diag.file, diag.start, program.getTypeChecker()); if (!info) return; @@ -95813,7 +97887,7 @@ var ts; } // Always prefer to add a method declaration if possible. if (call) { - addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, preferences); } else { if (inJs) { @@ -95872,10 +97946,8 @@ var ts; } function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); - return { description: description, changes: changes, fixId: fixId }; + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { @@ -95914,9 +97986,8 @@ var ts; return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); - return { description: description, changes: changes, fixId: fixId }; + return codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( @@ -95940,15 +98011,14 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); - return { description: description, changes: changes, fixId: fixId }; + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic, preferences); changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -95972,8 +98042,7 @@ var ts; return undefined; var node = info.node, suggestion = info.suggestion; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); - return [{ description: description, changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96010,10 +98079,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 793064 /* Type */; + flags |= 67901928 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 107455 /* Value */; + flags |= 67216319 /* Value */; } return flags; } @@ -96029,37 +98098,27 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); - return codeAction && [__assign({ fixId: fixId }, codeAction)]; + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = getTypesPackageNameToInstall(host, sourceFile, start); + return packageName === undefined ? [] + : [codefix.createCodeFixAction(/*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start); if (pkg) { commands.push(getCommand(diag.file.fileName, pkg)); } }); }, }); - function getModuleName(sourceFile, pos) { - return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; - } function getCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, moduleName) { + function getTypesPackageNameToInstall(host, sourceFile, pos) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; var packageName = ts.getPackageName(moduleName).packageName; - // If !registry, registry not available yet, can't do anything. return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; } - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { - var packageName = getTypesPackageNameToInstall(host, moduleName); - return packageName === undefined ? undefined : { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), - changes: [], - commands: [getCommand(fileName, packageName)], - }; - } - codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -96077,30 +98136,34 @@ var ts; getCodeActions: function (context) { var program = context.program, sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); }); - return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes); - }); }, + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + } + }); + }, }); function getClass(sourceFile, pos) { - // This is the identifier in the case of a class declaration + // Token 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, pos, /*includeJsDocComment*/ false); - var classDeclaration = token.parent; - ts.Debug.assert(ts.isClassLike(classDeclaration)); - return classDeclaration; + return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { 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 abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -96126,7 +98189,7 @@ var ts; return undefined; var constructor = nodes.constructor, superCall = nodes.superCall; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -96179,7 +98242,7 @@ var ts; var sourceFile = context.sourceFile, span = context.span; var ctr = getNode(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96213,7 +98276,7 @@ var ts; return undefined; var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96229,7 +98292,7 @@ var ts; return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && heritageClauses[0].token === 85 /* ExtendsKeyword */ && @@ -96265,7 +98328,7 @@ var ts; return undefined; } var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_this_to_unresolved_variable, fixId, ts.Diagnostics.Add_this_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96282,7 +98345,7 @@ var ts; } // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper ts.suppressLeadingAndTrailingTrivia(token); - changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -96296,29 +98359,33 @@ var ts; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = getToken(sourceFile, context.span.start); + var errorCode = context.errorCode, sourceFile = context.sourceFile; + var importDecl = tryGetFullImport(sourceFile, context.span.start); + if (importDecl) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } + var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); if (deletion.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); - result.push({ description: description, changes: deletion, fixId: fixIdDelete }); + result.push(codefix.createCodeFixAction(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } - var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, context.errorCode, sourceFile, token); }); + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); - result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + result.push(codefix.createCodeFixAction(prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); } return result; }, fixIds: [fixIdPrefix, fixIdDelete], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var sourceFile = context.sourceFile; - var token = getToken(diag.file, diag.start); + var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); switch (context.fixId) { case fixIdPrefix: if (ts.isIdentifier(token) && canPrefix(token)) { @@ -96326,17 +98393,28 @@ var ts; } break; case fixIdDelete: - tryDeleteDeclaration(changes, sourceFile, token); + var importDecl = tryGetFullImport(diag.file, diag.start); + if (importDecl) { + changes.deleteNode(sourceFile, importDecl); + } + else { + tryDeleteDeclaration(changes, sourceFile, token); + } break; default: ts.Debug.fail(JSON.stringify(context.fixId)); } }); }, }); + // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. + function tryGetFullImport(sourceFile, pos) { + var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; + } function getToken(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.findPrecedingToken(pos, sourceFile); // this handles var ["computed"] = 12; - return token.kind === 21 /* OpenBracketToken */ ? ts.getTokenAtPosition(sourceFile, pos + 1, /*includeJsDocComment*/ false) : token; + return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. @@ -96401,6 +98479,10 @@ var ts; break; case 148 /* Parameter */: var oldFunction = parent.parent; + if (ts.isSetAccessor(oldFunction)) { + // Setter must have a parameter + break; + } if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the @@ -96411,7 +98493,7 @@ var ts; // to replace the span (vs the full span) of the old function - the old leading // and trailing trivia will remain. ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction, ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, oldFunction, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); @@ -96432,9 +98514,9 @@ var ts; changes.deleteNodeInList(sourceFile, parent); } break; - case 243 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + case 243 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *' var importClause = parent; - if (!importClause.namedBindings) { + if (!importClause.namedBindings) { // |import d from './file'| changes.deleteNode(sourceFile, ts.getAncestor(importClause, 242 /* ImportDeclaration */)); } else { @@ -96530,47 +98612,40 @@ var ts; return undefined; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); - var actions = [fix(type, fixIdPlain)]; + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; if (typeNode.kind === 277 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable)); + actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; - function fix(type, fixId) { - var newText = typeString(type, checker); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], - fixId: fixId, - }; + function fix(type, fixId, fixAllDescription) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], getAllCodeActions: function (context) { var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; var checker = program.getTypeChecker(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + return codefix.codeFixAll(context, errorCodes, function (changes, err) { var info = getInfo(err.file, err.start, checker); if (!info) return; var typeNode = info.typeNode, type = info.type; var fixedType = typeNode.kind === 277 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; - changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + doChange(changes, sourceFile, typeNode, fixedType, checker); }); } }); + function doChange(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); + } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); var typeNode = decl && decl.type; return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; } - function createChange(declaration, sourceFile, newText) { - return ts.createTextChange(ts.createTextSpanFromNode(declaration, sourceFile), newText); - } - function typeString(type, checker) { - return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); - } function isTypeContainer(node) { // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments @@ -96616,7 +98691,7 @@ var ts; if (!nodes) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96639,6 +98714,9 @@ var ts; function getNodes(sourceFile, start) { var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } var insertBefore; switch (containingFunction.kind) { case 153 /* MethodDeclaration */: @@ -96690,9 +98768,8 @@ var ts; getAllCodeActions: ts.notImplemented, }); function createCodeAction(descriptionDiagnostic, diagnosticArgs, changes) { - var description = ts.formatMessage.apply(undefined, [undefined, descriptionDiagnostic].concat(diagnosticArgs)); // TODO: GH#20315 - return { description: description, changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(changes, [descriptionDiagnostic].concat(diagnosticArgs)); } function convertToImportCodeFixContext(context, symbolToken, symbolName) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; @@ -96708,7 +98785,8 @@ var ts; cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolName, - symbolToken: symbolToken + symbolToken: symbolToken, + preferences: context.preferences, }; } var ImportKind; @@ -96718,12 +98796,12 @@ var ts; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken) { + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken, preferences) { var exportInfos = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host)).moduleSpecifier; - var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken }; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } codefix.getImportCompletionAction = getImportCompletionAction; @@ -96785,34 +98863,20 @@ var ts; var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); var cached = cachedImportDeclarations[moduleSymbolId]; if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { - var declaration = checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; - return declaration && { declaration: declaration, importKind: importKind }; + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 242 /* ImportDeclaration */ || i.kind === 241 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } return cached; } - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 242 /* ImportDeclaration */: - return parent; - case 252 /* ExternalModuleReference */: - return parent.parent; - case 248 /* ExportDeclaration */: - case 185 /* CallExpression */:// For "require()" calls - // Ignore these, can't add imports to them. - return undefined; - default: - ts.Debug.fail(); - } - } function getCodeActionForNewImport(context, _a) { var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; - var sourceFile = context.sourceFile, symbolName = context.symbolName; + var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); + var quotedModuleSpecifier = ts.createLiteral(moduleSpecifierWithoutQuotes, shouldUseSingleQuote(sourceFile, preferences)); var importDecl = importKind !== 3 /* Equals */ ? ts.createImportDeclaration( /*decorators*/ undefined, @@ -96833,11 +98897,14 @@ var ts; // are there are already a new line seperating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } - 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 shouldUseSingleQuote(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single"; + } + else { + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + } } function usesJsExtensionOnImports(sourceFile) { return ts.firstDefined(sourceFile.imports, function (_a) { @@ -96858,35 +98925,40 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { - var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; + function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var addJsExtension = usesJsExtensionOnImports(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); if (global) { return [global]; } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); - if (!baseUrl) { + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), compilerOptions, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { return [relativePath]; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { return [relativePath]; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, compilerOptions, addJsExtension); if (paths) { var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); if (fromPaths) { return [fromPaths]; } } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); if (isPathRelativeToParent(relativeToBaseUrl)) { return [relativePath]; } @@ -97140,7 +99212,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); return newImportInfos.map(function (info) { return getCodeActionForNewImport(ctx, info); }); } function newImportInfoFromExistingSpecifier(_a) { @@ -97219,7 +99291,7 @@ var ts; var parent = token.parent; var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent); if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258 /* JsxOpeningFragment */) { - umdSymbol = checker.resolveName(checker.getJsxNamespace(), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false); + umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false); } } if (ts.isUMDExportSymbol(umdSymbol)) { @@ -97249,7 +99321,7 @@ var ts; // Fall back to the `import * as ns` style import. return 2 /* Namespace */; default: - throw ts.Debug.assertNever(moduleKind); + return ts.Debug.assertNever(moduleKind); } } function getActionsForNonUMDImport(context) { @@ -97257,13 +99329,14 @@ var ts; var sourceFile = context.sourceFile, span = context.span, program = context.program, cancellationToken = context.cancellationToken; var checker = program.getTypeChecker(); var symbolToken = ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false); - var isJsxNamespace = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken; - if (!isJsxNamespace && !ts.isIdentifier(symbolToken)) { + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; + if (!symbolName) return undefined; - } - var symbolName = isJsxNamespace ? checker.getJsxNamespace() : symbolToken.text; - var allSourceFiles = program.getSourceFiles(); - var compilerOptions = program.getCompilerOptions(); // "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 currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); @@ -97273,7 +99346,7 @@ var ts; function addSymbol(moduleSymbol, exportedSymbol, importKind) { originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); } - forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); // check the default export var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); @@ -97281,7 +99354,7 @@ var ts; var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if ((localSymbol && localSymbol.escapedName === symbolName || getEscapedNameForExportDefault(defaultExport) === symbolName || - moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { addSymbol(moduleSymbol, localSymbol || defaultExport, 1 /* Default */); } } @@ -97342,21 +99415,22 @@ var ts; return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { - return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); } codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); var res = ""; var lastCharWasValid = true; - var firstCharCode = moduleSpecifier.charCodeAt(0); + var firstCharCode = baseName.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); + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); var isValid = ts.isIdentifierPart(ch, target); if (isValid) { var char = String.fromCharCode(ch); @@ -97386,55 +99460,39 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, span = context.span; + var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } - var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter).change])], - fixId: fixId, - }, - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [ - ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), - ])], - // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - fixId: undefined, - }]; + var fixes = [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId([codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), + ]; + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); + } + return fixes; }, fixIds: [fixId], getAllCodeActions: function (context) { - var seenLines = ts.createMap(); // Only need to add `// @ts-ignore` for a line once. - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { - if (err.start !== undefined) { - var _a = getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options)), lineNumber = _a.lineNumber, change = _a.change; - if (ts.addToSeen(seenLines, lineNumber)) { - changes.push(change); - } + var seenLines = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { + makeChange(changes, diag.file, diag.start, seenLines); } }); }, }); - function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) { + function makeChange(changes, sourceFile, position, seenLines) { var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; - var lineStartPosition = ts.getStartPositionOfLine(lineNumber, 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, /*includeJsDocComment*/ false); - var tokenLeadingComments = ts.getLeadingCommentRangesOfNode(token, sourceFile); - if (!tokenLeadingComments || !tokenLeadingComments.length || tokenLeadingComments[0].pos >= startPosition) { - return { lineNumber: lineNumber, change: ts.createTextChangeFromStartLength(startPosition, 0, "// @ts-ignore" + newLineCharacter) }; - } + // Only need to add `// @ts-ignore` for a line once. + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } - // If all fails, add an extra new line immediately before the error span. - return { lineNumber: lineNumber, change: ts.createTextChangeFromStartLength(position, 0, (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter) }; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -97449,12 +99507,12 @@ var ts; * @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, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); } } } @@ -97462,7 +99520,7 @@ var ts; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -97500,7 +99558,7 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { @@ -97510,11 +99568,11 @@ var ts; } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); } else { ts.Debug.assert(declarations.length === signatures.length); - out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); } break; } @@ -97539,7 +99597,7 @@ var ts; function getSynthesizedDeepClones(nodes) { return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); } - function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { + function createMethodFromCallExpression(_a, methodName, inJs, makeStatic, preferences) { var typeArguments = _a.typeArguments, args = _a.arguments; return ts.createMethod( /*decorators*/ undefined, @@ -97550,7 +99608,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody()); + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, minArgumentCount, inJs) { @@ -97568,7 +99626,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers) { + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { /** 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. @@ -97600,16 +99658,16 @@ var ts; } return createStubbedMethod(modifiers, name, optional, /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined); + /*returnType*/ undefined, preferences); } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } - function createStubbedMethodBody() { + function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), - /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], /*multiline*/ true); } function createVisibilityModifier(flags) { @@ -97647,28 +99705,23 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (_a) { - var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; if (ts.isSourceFileJavaScript(sourceFile)) { return undefined; // TODO: GH#20113 } var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var fix = getFix(sourceFile, token, errorCode, program, cancellationToken); - if (!fix) - return undefined; - var declaration = fix.declaration, textChanges = fix.textChanges; - var name = ts.getNameOfDeclaration(declaration); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); - return [{ description: description, changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }], fixId: fixId }]; + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); + return changes.length === 0 ? undefined + : [codefix.createCodeFixAction(changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; var seenFunctions = ts.createMap(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { - var fix = getFix(sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); - if (fix) - changes.push.apply(changes, fix.textChanges); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); }); }, }); @@ -97682,18 +99735,26 @@ var ts; return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function getFix(sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { - if (!isAllowedTokenKind(token.kind)) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { return undefined; } + var parent = token.parent; 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, program, cancellationToken); + if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + return parent; + } + return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, program, cancellationToken); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + return symbol.valueDeclaration; + } } } var containingFunction = ts.getContainingFunction(token); @@ -97704,43 +99765,41 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction, program, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return !seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction)) - ? getCodeActionForParameters(ts.cast(token.parent, ts.isParameter), containingFunction, sourceFile, program, cancellationToken) - : undefined; + if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + return param; + } + return undefined; // 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, sourceFile, program, cancellationToken) : undefined; + if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + return containingFunction; + } + return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, program, cancellationToken) : undefined; + if (ts.isSetAccessor(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + return containingFunction; + } + return undefined; default: - throw ts.Debug.fail(String(errorCode)); + return ts.Debug.fail(String(errorCode)); } } - function isAllowedTokenKind(kind) { - switch (kind) { - case 71 /* Identifier */: - case 24 /* DotDotDotToken */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; + function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); } } - function getCodeActionForVariableDeclaration(declaration, program, cancellationToken) { - if (!ts.isIdentifier(declaration.name)) - return undefined; - var type = inferTypeForVariableFromUsage(declaration.name, program, cancellationToken); - return makeFix(declaration, declaration.name.getEnd(), type, program); - } function isApplicableFunctionForInference(declaration) { switch (declaration.kind) { case 232 /* FunctionDeclaration */: @@ -97752,47 +99811,47 @@ var ts; } return false; } - function getCodeActionForParameters(parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; + return; } var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - if (!types) - return undefined; // We didn't actually find a set of type inference positions matching each parameter position - if (containingFunction.parameters.length !== types.length) { - return undefined; + if (!types || containingFunction.parameters.length !== types.length) { + return; } - var textChanges = ts.arrayFrom(ts.mapDefinedIterator(ts.zipToIterator(containingFunction.parameters, types), function (_a) { - var parameter = _a[0], type = _a[1]; - return type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined; - })); - return textChanges.length ? { declaration: parameterDeclaration, textChanges: textChanges } : undefined; + ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (!parameter.type && !parameter.initializer) { + annotate(changes, sourceFile, parameter, type, program); + } + }); } - function getCodeActionForSetAccessor(setAccessorDeclaration, program, cancellationToken) { - var setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { - return undefined; + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || + inferTypeForVariableFromUsage(param.name, program, cancellationToken); + annotate(changes, sourceFile, param, type, program); } - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(setAccessorParameter.name, program, cancellationToken); - return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); } - function getCodeActionForGetAccessor(getAccessorDeclaration, sourceFile, program, cancellationToken) { - if (!ts.isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, program, cancellationToken); - var closeParenToken = ts.findChildOfKind(getAccessorDeclaration, 20 /* CloseParenToken */, sourceFile); - return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + function annotate(changes, sourceFile, declaration, type, program) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); + if (typeNode) + changes.insertTypeAnnotation(sourceFile, declaration, typeNode); } - function makeFix(declaration, start, type, program) { - return type && { declaration: declaration, textChanges: [makeChange(declaration, start, type, program)] }; - } - function makeChange(declaration, start, type, program) { - var typeString = type && typeToString(type, declaration, program.getTypeChecker()); - return typeString === undefined ? undefined : ts.createTextChangeFromStartLength(start, 0, ": " + typeString); + function getTypeNodeIfAccessible(type, enclosingScope, checker) { + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + }); + return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. @@ -97818,48 +99877,6 @@ var ts; } } } - function getTypeAccessiblityWriter(checker) { - var str = ""; - var typeIsAccessible = true; - var writeText = function (text) { return str += text; }; - return { - getText: function () { return typeIsAccessible ? str : undefined; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - write: writeText, - writeTextOfNode: writeText, - rawWrite: writeText, - writeLiteral: writeText, - getTextPos: function () { return 0; }, - getLine: function () { return 0; }, - getColumn: function () { return 0; }, - getIndent: function () { return 0; }, - isAtStartOfLine: function () { return false; }, - writeLine: function () { return writeText(" "); }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { str = ""; typeIsAccessible = true; }, - trackSymbol: function (symbol, declaration, meaning) { - if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { - typeIsAccessible = false; - } - }, - reportInaccessibleThisError: function () { typeIsAccessible = false; }, - reportPrivateInBaseOfClassExpression: function () { typeIsAccessible = false; }, - reportInaccessibleUniqueSymbolError: function () { typeIsAccessible = false; } - }; - } - function typeToString(type, enclosingDeclaration, checker) { - var writer = getTypeAccessiblityWriter(checker); - checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); - return writer.getText(); - } var InferFromReference; (function (InferFromReference) { function inferTypeFromReferences(references, checker, cancellationToken) { @@ -97889,13 +99906,13 @@ var ts; var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; - var isRestParameter = ts.isRestParameter(parameter); + var isRest = ts.isRestParameter(parameter); for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { continue; } - if (isRestParameter) { + if (isRest) { for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); } @@ -97908,7 +99925,7 @@ var ts; return undefined; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRestParameter ? checker.createArrayType(type) : type; + return isRest ? checker.createArrayType(type) : type; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -97965,6 +99982,8 @@ var ts; case 37 /* PlusToken */: usageContext.isNumberOrString = true; break; + // case SyntaxKind.ExclamationToken: + // no inferences here; } } function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { @@ -98230,9 +100249,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -98242,12 +100259,8 @@ var ts; return variations; } function createAction(context, sourceFile, node, replacement) { - // TODO: GH#21246 Should be able to use `replaceNode`, but be sure to preserve comments (see `codeFixCalledES2015Import11.ts`) - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceRange(sourceFile, { pos: node.getStart(), end: node.end }, replacement); }); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), - changes: changes, - }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -98273,15 +100286,171 @@ var ts; if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } - fixes.push({ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), - changes: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }), - }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(changes, ts.Diagnostics.Use_synthetic_default_member)); return fixes; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + var fixIdAddInitializer = "addMissingPropertyInitializer"; + var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); + if (!propertyDeclaration) + return; + var result = [ + getActionForAddMissingUndefinedType(context, propertyDeclaration), + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) + ]; + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + return result; + }, + fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); + if (!propertyDeclaration) + return; + switch (context.fixId) { + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag.file, propertyDeclaration); + break; + case fixIdAddInitializer: + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return; + addInitializer(changes, diag.file, propertyDeclaration, initializer); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function getPropertyDeclaration(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + } + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types)); + } + function getActionForAddMissingInitializer(context, propertyDeclaration) { + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 2 /* String */) { + return ts.createLiteral(""); + } + else if (type.flags & 4 /* Number */) { + return ts.createNumericLiteral("0"); + } + else if (type.flags & 8 /* Boolean */) { + return ts.createFalse(); + } + else if (type.flags & 224 /* Literal */) { + return ts.createLiteral(type.value); + } + else if (type.flags & 131072 /* Union */) { + return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); + } + else if (ts.getObjectFlags(type) & 1 /* Class */) { + var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) + return undefined; + var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; }); + if (constructorDeclaration && constructorDeclaration.parameters.length) + return undefined; + return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "useDefaultImport"; + var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var info = getInfo(sourceFile, start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); }, + }); + function getInfo(sourceFile, pos) { + var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + if (!ts.isIdentifier(name)) + return undefined; // bad input + var parent = name.parent; + if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) { + return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression }; + } + else if (ts.isNamespaceImport(parent)) { + var importNode = parent.parent.parent; + return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; + } + } + function doChange(changes, sourceFile, info) { + changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// +/// +/// +/// /// /// /// @@ -98300,960 +100469,8 @@ var ts; /// /// /// -/* @internal */ -var ts; -(function (ts) { - var refactor; - (function (refactor) { - var annotateWithTypeFromJSDoc; - (function (annotateWithTypeFromJSDoc) { - var refactorName = "Annotate with type from JSDoc"; - var actionName = "annotate"; - var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (ts.isInJavaScriptFile(context.file)) { - return undefined; - } - var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); - if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { - return [{ - name: refactorName, - description: description, - actions: [ - { - description: 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 === 148 /* 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.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions); - 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.replaceNode(sourceFile, decl, functionWithType, ts.textChanges.useNonAdjustedPositions); - return { - edits: changeTracker.getChanges(), - renameFilename: undefined, - renameLocation: undefined - }; - } - function isDeclarationWithType(node) { - return ts.isFunctionLikeDeclaration(node) || - node.kind === 230 /* VariableDeclaration */ || - node.kind === 148 /* Parameter */ || - node.kind === 150 /* PropertySignature */ || - node.kind === 151 /* 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 232 /* FunctionDeclaration */: - return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); - case 154 /* Constructor */: - return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); - case 190 /* FunctionExpression */: - return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); - case 191 /* ArrowFunction */: - return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); - case 153 /* MethodDeclaration */: - return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body); - case 155 /* GetAccessor */: - return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body); - case 156 /* 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 230 /* VariableDeclaration */: - return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer); - case 150 /* PropertySignature */: - return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); - case 151 /* 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 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: - return ts.createTypeReferenceNode("any", ts.emptyArray); - case 279 /* JSDocOptionalType */: - return transformJSDocOptionalType(node); - case 278 /* JSDocNonNullableType */: - return transformJSDocType(node.type); - case 277 /* JSDocNullableType */: - return transformJSDocNullableType(node); - case 281 /* JSDocVariadicType */: - return transformJSDocVariadicType(node); - case 280 /* JSDocFunctionType */: - return transformJSDocFunctionType(node); - case 148 /* Parameter */: - return transformJSDocParameter(node); - case 161 /* 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 === 281 /* 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 === 134 /* NumberKeyword */ ? "n" : "s", - /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* 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; - (function (refactor) { - var convertFunctionToES6Class; - (function (convertFunctionToES6Class) { - var refactorName = "Convert to ES2015 class"; - var actionName = "convert"; - var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (!ts.isInJavaScriptFile(context.file)) { - return undefined; - } - var symbol = getConstructorSymbol(context); - if (!symbol) { - return undefined; - } - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = symbol.valueDeclaration.initializer.symbol; - } - if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { - return [ - { - name: refactorName, - description: description, - actions: [ - { - description: description, - name: actionName - } - ] - } - ]; - } - } - function getEditsForAction(context, action) { - // Somehow wrong action got invoked? - if (actionName !== action) { - return undefined; - } - var sourceFile = context.file; - var ctorSymbol = getConstructorSymbol(context); - var deletedNodes = []; - var deletes = []; - if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { - return undefined; - } - var ctorDeclaration = ctorSymbol.valueDeclaration; - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var precedingNode; - var newClassDeclaration; - switch (ctorDeclaration.kind) { - case 232 /* FunctionDeclaration */: - precedingNode = ctorDeclaration; - deleteNode(ctorDeclaration); - newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); - break; - case 230 /* VariableDeclaration */: - precedingNode = ctorDeclaration.parent.parent; - if (ctorDeclaration.parent.declarations.length === 1) { - deleteNode(precedingNode); - } - else { - deleteNode(ctorDeclaration, /*inList*/ true); - } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - break; - } - if (!newClassDeclaration) { - return undefined; - } - // Because the preceding node could be touched, we need to insert nodes before delete nodes. - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); - for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { - var deleteCallback = deletes_1[_i]; - deleteCallback(); - } - return { - edits: changeTracker.getChanges(), - renameFilename: undefined, - renameLocation: undefined, - }; - 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); - if (inList) { - deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); - } - else { - deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); - } - } - 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, /*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 /* StaticKeyword */)]); - if (memberElement) { - memberElements.push(memberElement); - } - }); - } - 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) { - // both properties and methods are bound as property symbols - if (!(symbol.flags & 4 /* Property */)) { - return; - } - var memberDeclaration = symbol.valueDeclaration; - var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - 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 === 214 /* ExpressionStatement */ - ? assignmentBinaryExpression.parent : assignmentBinaryExpression; - deleteNode(nodeToDelete); - if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, - /*type*/ undefined, /*initializer*/ undefined); - } - switch (assignmentBinaryExpression.right.kind) { - case 190 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - 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 191 /* ArrowFunction */: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 211 /* Block */) { - bodyBlock = arrowFunctionBody; - } - else { - bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); - } - 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(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop); - return prop; - } - } - } - } - function copyComments(sourceNode, targetNode) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - 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); - }); - } - function createClassFromVariableDeclaration(node) { - var initializer = node.initializer; - if (!initializer || initializer.kind !== 190 /* FunctionExpression */) { - return undefined; - } - if (node.name.kind !== 71 /* Identifier */) { - return undefined; - } - var memberElements = createClassElementsFromSymbol(initializer.symbol); - if (initializer.body) { - memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); - } - 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(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); - } - 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 actionName = "Convert to ES6 module"; - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); - refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition; - if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { - return undefined; - } - var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); - return !isAtTriggerLocation(file, node) ? undefined : [ - { - name: actionName, - description: description, - actions: [ - { - description: description, - name: actionName, - }, - ], - }, - ]; - } - function isAtTriggerLocation(sourceFile, node, onSecondTry) { - if (onSecondTry === void 0) { onSecondTry = false; } - switch (node.kind) { - case 185 /* CallExpression */: - return isAtTopLevelRequire(node); - case 183 /* PropertyAccessExpression */: - return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) - || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); - case 231 /* VariableDeclarationList */: - return isVariableDeclarationTriggerLocation(ts.firstOrUndefined(node.declarations)); - case 230 /* VariableDeclaration */: - return isVariableDeclarationTriggerLocation(node); - default: - return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) - || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); - } - function isVariableDeclarationTriggerLocation(decl) { - return !!decl && !!decl.initializer && ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); - } - } - function isAtTopLevelRequire(call) { - if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { - return false; - } - var propAccess = call.parent; - var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; - if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { - return true; - } - if (!ts.isVariableDeclaration(varDecl)) { - return false; - } - var varDeclList = varDecl.parent; - if (varDeclList.kind !== 231 /* VariableDeclarationList */) { - return false; - } - var varStatement = varDeclList.parent; - return varStatement.kind === 212 /* VariableStatement */ && varStatement.parent.kind === 272 /* SourceFile */; - } - function getEditsForAction(context, _actionName) { - ts.Debug.assertEqual(actionName, _actionName); - var file = context.file, program = context.program; - ts.Debug.assert(ts.isSourceFileJavaScript(file)); - var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); - if (moduleExportsChangedToDefault) { - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, file, changes); - } - } - }); - return { edits: edits, renameFilename: undefined, renameLocation: undefined }; - } - function fixImportOfModuleExports(importingFile, exportingFile, changes) { - for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); - if (!imported || imported.resolvedFileName !== exportingFile.fileName) { - continue; - } - var parent = moduleSpecifier.parent; - switch (parent.kind) { - case 252 /* ExternalModuleReference */: { - var importEq = parent.parent; - changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); - break; - } - case 185 /* CallExpression */: { - var call = parent; - if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { - changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); - } - break; - } - } - } - } - /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { - var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; - var exports = collectExportRenames(sourceFile, checker, identifiers); - convertExportsAccesses(sourceFile, exports, changes); - var moduleExportsChangedToDefault = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); - moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; - } - return moduleExportsChangedToDefault; - } - function collectExportRenames(sourceFile, checker, identifiers) { - var res = ts.createMap(); - forEachExportReference(sourceFile, function (node) { - var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; - if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { - // Unconditionally add an underscore in case `text` is a keyword. - res.set(text, makeUniqueName("_" + text, identifiers)); - } - }); - return res; - } - function convertExportsAccesses(sourceFile, exports, changes) { - forEachExportReference(sourceFile, function (node, isAssignmentLhs) { - if (isAssignmentLhs) { - return; - } - var text = node.name.text; - changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); - }); - } - function forEachExportReference(sourceFile, cb) { - sourceFile.forEachChild(function recur(node) { - if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { - var parent = node.parent; - cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); - } - node.forEachChild(recur); - }); - } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { - switch (statement.kind) { - case 212 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); - return false; - case 214 /* ExpressionStatement */: { - var expression = statement.expression; - switch (expression.kind) { - case 185 /* CallExpression */: { - if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { - // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); - } - return false; - } - case 198 /* BinaryExpression */: { - var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); - } - } - } - // falls through - default: - return false; - } - } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { - var declarationList = statement.declarationList; - var foundImport = false; - var newNodes = ts.flatMap(declarationList.declarations, function (decl) { - var name = decl.name, initializer = decl.initializer; - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { - // `const alias = module.exports;` can be removed. - foundImport = true; - return []; - } - if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); - } - else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); - } - else { - // Move it out to its own variable statement. - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); - } - }); - if (foundImport) { - // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - } - } - /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { - switch (name.kind) { - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: { - // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` - var tmp = makeUniqueName(propertyName, identifiers); - return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), - makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), - ]; - } - case 71 /* Identifier */: - // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; - default: - ts.Debug.assertNever(name); - } - } - function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { - if (!ts.isPropertyAccessExpression(left)) { - return false; - } - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { - // `const alias = module.exports;` or `module.exports = alias;` can be removed. - changes.deleteNode(sourceFile, statement); - } - else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); - } - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - return changedToDefaultExport; - } - } - else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { - convertNamedExport(sourceFile, statement, left.name, right, changes, exports); - } - return false; - var _a; - } - /** - * Convert `module.exports = { ... }` to individual exports.. - * We can't always do this if the module has interesting members -- then it will be a default export instead. - */ - function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { - switch (prop.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 269 /* ShorthandPropertyAssignment */: - case 270 /* SpreadAssignment */: - return undefined; - case 268 /* PropertyAssignment */: - return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); - case 153 /* MethodDeclaration */: - return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); - default: - ts.Debug.assertNever(prop); - } - }); - } - function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { - // If "originalKeywordKind" was set, this is e.g. `exports. - var text = propertyName.text; - var rename = exports.get(text); - if (rename !== undefined) { - /* - const _class = 0; - export { _class as class }; - */ - var newNodes = [ - makeConst(/*modifiers*/ undefined, rename, right), - makeExportDeclaration([ts.createExportSpecifier(rename, text)]), - ]; - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - } - else { - changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); - } - } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; - switch (exported.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: { - // `module.exports = function f() {}` --> `export default function f() {}` - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 203 /* ClassExpression */: { - // `module.exports = class C {}` --> `export default class C {}` - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 185 /* CallExpression */: - if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { - return convertReExportAll(exported.arguments[0], checker); - } - // falls through - default: - // `module.exports = 0;` --> `export default 0;` - return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; - } - } - function convertReExportAll(reExported, checker) { - // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` - var moduleSpecifier = reExported.text; - var moduleSymbol = checker.getSymbolAtLocation(reExported); - var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; - return exports.has("export=") - ? [[reExportDefault(moduleSpecifier)], true] - : !exports.has("default") - ? [[reExportStar(moduleSpecifier)], false] - // If there's some non-default export, must include both `export *` and `export default`. - : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; - } - function reExportStar(moduleSpecifier) { - return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); - } - function reExportDefault(moduleSpecifier) { - return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); - } - function convertExportsDotXEquals(name, exported) { - var modifiers = [ts.createToken(84 /* ExportKeyword */)]; - switch (exported.kind) { - case 190 /* FunctionExpression */: { - var expressionName = exported.name; - if (expressionName && expressionName.text !== name) { - // `exports.f = function g() {}` -> `export const f = function g() {}` - return exportConst(); - } - } - // falls through - case 191 /* ArrowFunction */: - // `exports.f = function() {}` --> `export function f() {}` - return functionExpressionToDeclaration(name, modifiers, exported); - case 203 /* ClassExpression */: - // `exports.C = class {}` --> `export class C {}` - return classExpressionToDeclaration(name, modifiers, exported); - default: - return exportConst(); - } - function exportConst() { - // `exports.x = 0;` --> `export const x = 0;` - return makeConst(modifiers, ts.createIdentifier(name), exported); - } - } - /** - * Converts `const <> = require("x");`. - * Returns nodes that will replace the variable declaration for the commonjs import. - * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. - */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { - switch (name.kind) { - case 178 /* ObjectBindingPattern */: { - var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { - return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) - ? undefined - : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); - }); - if (importSpecifiers) { - return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; - } - } - // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 179 /* ArrayBindingPattern */: { - /* - import x from "x"; - const [a, b, c] = x; - */ - var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); - return [ - makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), - makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), - ]; - } - case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); - default: - ts.Debug.assertNever(name); - } - } - /** - * Convert `import x = require("x").` - * Also converts uses like `x.y()` to `y()` and uses a named import. - */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { - var nameSymbol = checker.getSymbolAtLocation(name); - // Maps from module property name to name actually used. (The same if there isn't shadowing.) - var namedBindingsNames = ts.createMap(); - // True if there is some non-property use like `x()` or `f(x)`. - var needDefaultImport = false; - for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { - var use = _a[_i]; - if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { - // This was a use of a different symbol with the same name, due to shadowing. Ignore. - continue; - } - var parent = use.parent; - if (ts.isPropertyAccessExpression(parent)) { - var expression = parent.expression, propertyName = parent.name.text; - ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` - var idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); - } - changes.replaceNode(file, parent, ts.createIdentifier(idName)); - } - else { - needDefaultImport = true; - } - } - var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { - var propertyName = _a[0], idName = _a[1]; - return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); - })); - if (!namedBindings) { - // If it was unused, ensure that we at least import *something*. - needDefaultImport = true; - } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; - } - // Identifiers helpers - function makeUniqueName(name, identifiers) { - while (identifiers.original.has(name) || identifiers.additional.has(name)) { - name = "_" + name; - } - identifiers.additional.set(name, true); - return name; - } - function collectFreeIdentifiers(file) { - var map = ts.createMultiMap(); - file.forEachChild(function recur(node) { - if (ts.isIdentifier(node) && isFreeIdentifier(node)) { - map.add(node.text, node); - } - node.forEachChild(recur); - }); - return map; - } - function isFreeIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 183 /* PropertyAccessExpression */: - return parent.name !== node; - case 180 /* BindingElement */: - return parent.propertyName !== node; - default: - return true; - } - } - // Node helpers - function functionExpressionToDeclaration(name, additionalModifiers, fn) { - return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); - } - function classExpressionToDeclaration(name, additionalModifiers, cls) { - return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); - } - function makeSingleImport(localName, propertyName, moduleSpecifier) { - return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); - } - function makeImport(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); - } - function makeImportSpecifier(propertyName, name) { - return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); - } - function makeConst(modifiers, name, init) { - return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); - } - function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { - return ts.createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); - } - })(refactor = ts.refactor || (ts.refactor = {})); -})(ts || (ts = {})); +/// +/// /// /// /* @internal */ @@ -99478,7 +100695,7 @@ var ts; } else if (ts.isVariableStatement(node)) { var numInitializers = 0; - var lastInitializer = undefined; + var lastInitializer = void 0; for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.initializer) { @@ -99595,7 +100812,7 @@ var ts; switch (node.kind) { case 232 /* FunctionDeclaration */: case 233 /* ClassDeclaration */: - if (node.parent.kind === 272 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { + if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } @@ -99875,12 +101092,12 @@ var ts; var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); - var returnType = undefined; + var returnType; var parameters = []; var callArguments = []; var writes; usagesInScope.forEach(function (usage, name) { - var typeNode = undefined; + var typeNode; 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) {" @@ -100115,7 +101332,7 @@ var ts; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -100130,14 +101347,14 @@ var ts; changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else if (node.parent.kind === 214 /* 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.replaceNode(context.file, node.parent, newVariableStatement, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { var newVariableStatement = ts.createVariableStatement( @@ -100157,7 +101374,7 @@ var ts; } else { var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } } } @@ -100167,7 +101384,7 @@ var ts; return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function getContainingVariableDeclarationIfInList(node, scope) { - var prevNode = undefined; + var prevNode; while (node !== undefined && node !== scope) { if (ts.isVariableDeclaration(node) && node.initializer === prevNode && @@ -100192,16 +101409,16 @@ var ts; ts.Debug.assert(fileName === renameFilename); for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) { var change = textChanges_3[_b]; - var span_15 = change.span, newText = change.newText; + var span = change.span, newText = change.newText; var index = newText.indexOf(functionNameText); if (index !== -1) { - lastPos = span_15.start + delta + index; + lastPos = span.start + delta + index; // If the reference comes first, return immediately. if (!isDeclaredBeforeUse) { return lastPos; } } - delta += newText.length - span_15.length; + delta += newText.length - span.length; } } // If the declaration comes first, return the position of the last occurrence. @@ -100210,7 +101427,7 @@ var ts; return lastPos; } function getFirstDeclaration(type) { - var firstDeclaration = undefined; + var firstDeclaration; var symbol = type.symbol; if (symbol && symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -100332,7 +101549,7 @@ var ts; 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 prevMember; var allProperties = true; for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { var member = members_6[_i]; @@ -100354,7 +101571,7 @@ var ts; } function getNodeToInsertConstantBefore(node, scope) { ts.Debug.assert(!ts.isClassLike(scope)); - var prevScope = undefined; + var prevScope; for (var curr = node; curr !== scope; curr = curr.parent) { if (isScope(curr)) { prevScope = curr; @@ -100362,7 +101579,7 @@ var ts; } for (var curr = (prevScope || node).parent;; curr = curr.parent) { if (isBlockLike(curr)) { - var prevStatement = undefined; + var prevStatement = void 0; for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement.pos > node.pos) { @@ -100427,13 +101644,13 @@ var ts; var visibleDeclarationsInExtractedRange = []; var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID var exposedVariableDeclarations = []; - var firstExposedNonVariableDeclaration = undefined; + var firstExposedNonVariableDeclaration; var expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : undefined; - var expressionDiagnostic = undefined; + var expressionDiagnostic; if (expression === undefined) { var statements = targetRange.range; var start = ts.first(statements).getStart(); @@ -100511,7 +101728,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_10 = function (i) { + var _loop_12 = 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 @@ -100521,7 +101738,7 @@ var ts; constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); } var hasWrite = false; - var readonlyClassPropertyWrite = undefined; + var readonlyClassPropertyWrite; usagesPerScope[i].usages.forEach(function (value) { if (value.usage === 2 /* Write */) { hasWrite = true; @@ -100551,7 +101768,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_10(i); + _loop_12(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { @@ -100819,165 +102036,251 @@ var ts; })(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) { - var refactorName = "Install missing types package"; - var actionName = "install"; - var description = "Install missing types package"; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { - // Then it will be available via `fixCannotFindModule`. - return undefined; - } - var action = getAction(context); - return action && [ - { - name: refactorName, - description: 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 242 /* ImportDeclaration */: - case 252 /* 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 description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); - refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition, program = context.program; - if (!ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { - return undefined; - } - var importInfo = getConvertibleImportAtPosition(file, startPosition); - if (!importInfo) { - return undefined; - } - var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); - if (!(resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) { - return undefined; - } - return [ - { - name: actionName, - description: description, - actions: [ - { - description: 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 241 /* ImportEqualsDeclaration */: - var eq = node; - var moduleReference = eq.moduleReference; - return moduleReference.kind === 252 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression) - ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression } - : undefined; - case 242 /* ImportDeclaration */: - var d = node; - var importClause = d.importClause; - return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* 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 244 /* NamespaceImport */: - case 252 /* 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 = {})); -/// -/// -/// /// -/// -/// +/* @internal */ +var ts; +(function (ts) { + var sourcemaps; + (function (sourcemaps) { + sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; + function decode(host, mapPath, map, program, fallbackCache) { + if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } + var currentDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot || currentDirectory; + var decodedMappings; + var generatedOrderedMappings; + var sourceOrderedMappings; + return { + getOriginalPosition: getOriginalPosition, + getGeneratedPosition: getGeneratedPosition + }; + function getGeneratedPosition(loc) { + var maps = getGeneratedOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { + return loc; + } + return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos + } + function getOriginalPosition(loc) { + var maps = getSourceOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos + } + function getSourceFileLike(fileName, location) { + // Lookup file in program, if provided + var file = program && program.getSourceFile(fileName); + if (!file) { + // Otherwise check the cache (which may hit disk) + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + return fallbackCache.get(path); + } + return file; + } + function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { + var file = getSourceFileLike(fileName, directory); + if (!file) { + return -1; + } + return ts.getPositionOfLineAndCharacter(file, line, character); + } + function getDecodedMappings() { + return decodedMappings || (decodedMappings = calculateDecodedMappings()); + } + function getSourceOrderedMappings() { + return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); + } + function getGeneratedOrderedMappings() { + return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); + } + function calculateDecodedMappings() { + var state = { + encodedText: map.mappings, + currentNameIndex: undefined, + sourceMapNamesLength: map.names ? map.names.length : undefined, + currentEmittedColumn: 0, + currentEmittedLine: 0, + currentSourceColumn: 0, + currentSourceLine: 0, + currentSourceIndex: 0, + positions: [], + decodingIndex: 0, + processPosition: processPosition, + }; + while (!hasCompletedDecoding(state)) { + decodeSinglePosition(state); + if (state.error) { + host.log("Encountered error while decoding sourcemap found at " + mapPath + ": " + state.error); + return []; + } + } + return state.positions; + } + function compareProcessedPositionSourcePositions(a, b) { + return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || + ts.compareValues(a.sourcePosition, b.sourcePosition); + } + function compareProcessedPositionEmittedPositions(a, b) { + return ts.compareValues(a.emittedPosition, b.emittedPosition); + } + function processPosition(position) { + var sourcePath = map.sources[position.sourceIndex]; + return { + emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), + sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), + sourcePath: sourcePath, + }; + } + } + sourcemaps.decode = decode; + function hasCompletedDecoding(state) { + return state.decodingIndex === state.encodedText.length; + } + function decodeSinglePosition(state) { + while (state.decodingIndex < state.encodedText.length) { + var char = state.encodedText.charCodeAt(state.decodingIndex); + if (char === 59 /* semicolon */) { + // New line + state.currentEmittedLine++; + state.currentEmittedColumn = 0; + state.decodingIndex++; + continue; + } + if (char === 44 /* comma */) { + // Next entry is on same line - no action needed + state.decodingIndex++; + continue; + } + // Read the current position + // 1. Column offset from prev read jsColumn + state.currentEmittedColumn += base64VLQFormatDecode(); + // Incorrect emittedColumn dont support this map + if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { + return; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { + return; + } + // 2. Relative sourceIndex + state.currentSourceIndex += base64VLQFormatDecode(); + // Incorrect sourceIndex dont support this map + if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { + return; + } + // Dont support reading mappings that dont have information about original source position + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { + return; + } + // 3. Relative sourceLine 0 based + state.currentSourceLine += base64VLQFormatDecode(); + // Incorrect sourceLine dont support this map + if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { + return; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { + return; + } + // 4. Relative sourceColumn 0 based + state.currentSourceColumn += base64VLQFormatDecode(); + // Incorrect sourceColumn dont support this map + if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { + return; + } + // 5. Check if there is name: + if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { + if (state.currentNameIndex === undefined) { + state.currentNameIndex = 0; + } + state.currentNameIndex += base64VLQFormatDecode(); + // Incorrect nameIndex dont support this map + // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap + // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { + // return; + // } + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { + return; + } + // Entry should be complete + capturePosition(); + return; + } + createErrorIfCondition(/*condition*/ true, "No encoded entry found"); + return; + function capturePosition() { + state.positions.push(state.processPosition({ + emittedColumn: state.currentEmittedColumn, + emittedLine: state.currentEmittedLine, + sourceColumn: state.currentSourceColumn, + sourceIndex: state.currentSourceIndex, + sourceLine: state.currentSourceLine, + nameIndex: state.currentNameIndex + })); + } + function createErrorIfCondition(condition, errormsg) { + if (state.error) { + // An error was already reported + return true; + } + if (condition) { + state.error = errormsg; + } + return condition; + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; state.decodingIndex++) { + if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { + return; + } + // 6 digit number + var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + function base64FormatDecode(char) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + } + function isSourceMappingSegmentEnd(encodedText, pos) { + return (pos === encodedText.length || + encodedText.charCodeAt(pos) === 44 /* comma */ || + encodedText.charCodeAt(pos) === 59 /* semicolon */); + } + })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); +})(ts || (ts = {})); /// /// /// @@ -100999,6 +102302,7 @@ var ts; /// /// /// +/// /// /// /// @@ -101008,10 +102312,11 @@ var ts; /// /// /// +/// var ts; (function (ts) { /** The version of the language service API */ - ts.servicesVersion = "0.7"; + ts.servicesVersion = "0.8"; 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) : @@ -101071,104 +102376,15 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { - ts.scanner.setTextPos(pos); - while (pos < end) { - var token = ts.scanner.scan(); - var textPos = ts.scanner.getTextPos(); - if (textPos <= end) { - if (token === 71 /* Identifier */) { - ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(this) + " to have an Identifier in its trivia"); - } - nodes.push(createNode(token, pos, textPos, this)); - } - pos = textPos; - if (token === 1 /* EndOfFileToken */) { - break; - } - } - return pos; - }; - NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, this); - list._children = []; - var pos = nodes.pos; - for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { - var node = nodes_9[_i]; - if (pos < node.pos) { - pos = this.addSyntheticNodes(list._children, pos, node.pos); - } - list._children.push(node); - pos = node.end; - } - if (pos < nodes.end) { - this.addSyntheticNodes(list._children, pos, nodes.end); - } - return list; - }; - NodeObject.prototype.createChildren = function (sourceFile) { - var _this = this; - if (!ts.isNodeKind(this.kind)) { - this._children = ts.emptyArray; - return; - } - if (ts.isJSDocCommentContainingNode(this)) { - /** 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 = []; - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - var pos = this.pos; - var processNode = function (node) { - pos = _this.addSyntheticNodes(children, pos, node.pos); - children.push(node); - pos = node.end; - }; - var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); - } - 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) { - this.addSyntheticNodes(children, pos, this.end); - } - ts.scanner.setText(undefined); - this._children = children; - }; NodeObject.prototype.getChildCount = function (sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children.length; + return this.getChildren(sourceFile).length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children[index]; + return this.getChildren(sourceFile)[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; + return this._children || (this._children = createChildren(this, sourceFile)); }; NodeObject.prototype.getFirstToken = function (sourceFile) { this.assertHasRealPosition(); @@ -101195,6 +102411,69 @@ var ts; }; return NodeObject; }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified 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 = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 71 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } var TokenOrIdentifierObject = /** @class */ (function () { function TokenOrIdentifierObject(pos, end) { // Set properties in same order as NodeObject @@ -101443,7 +102722,7 @@ var ts; */ function findInheritedJSDocComments(declaration, propertyName, typeChecker) { var foundDocs = false; - return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { + return ts.flatMap(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { if (foundDocs) { return ts.emptyArray; } @@ -101460,20 +102739,6 @@ var ts; 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) { @@ -101530,20 +102795,8 @@ var ts; } function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); - if (name) { - var result_6 = ts.getTextOfIdentifierOrLiteral(name); - if (result_6 !== undefined) { - return result_6; - } - if (name.kind === 146 /* ComputedPropertyName */) { - var expr = name.expression; - if (expr.kind === 183 /* PropertyAccessExpression */) { - return expr.name.text; - } - return ts.getTextOfIdentifierOrLiteral(expr); - } - } - return undefined; + return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) : + name.kind === 146 /* ComputedPropertyName */ && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined); } function visit(node) { switch (node.kind) { @@ -101918,6 +103171,31 @@ var ts; return ThrottledCancellationToken; }()); ts.ThrottledCancellationToken = ThrottledCancellationToken; + /* @internal */ + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } + ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -101931,6 +103209,7 @@ var ts; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } + var sourcemappedFileCache; function log(message) { if (host.log) { host.log(message); @@ -102023,6 +103302,10 @@ var ts; // 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; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourcemappedFileCache = createSourceFileLikeCache(host); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); @@ -102130,18 +103413,25 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return semanticDiagnostics.concat(declarationDiagnostics); } + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program); + } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } + if (options === void 0) { options = ts.defaultPreferences; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), fullPreferences); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName, preferences); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -102152,9 +103442,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { - return undefined; - } - if (ts.isLabelName(node)) { + // Avoid giving quickInfo for the sourceFile as a whole. return undefined; } var typeChecker = program.getTypeChecker(); @@ -102163,6 +103451,11 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 71 /* Identifier */: + if (ts.isLabelName(node)) { + // Type here will be 'any', avoid displaying this. + return undefined; + } + // falls through case 183 /* PropertyAccessExpression */: case 145 /* QualifiedName */: case 99 /* ThisKeyword */: @@ -102170,27 +103463,25 @@ var ts; case 97 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); - if (type) { - return { - 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(typeChecker) : undefined, - tags: type.symbol ? type.symbol.getJsDocTags() : undefined - }; - } + return type && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type.symbol ? type.symbol.getJsDocTags() : undefined + }; } return undefined; } - var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; return { - kind: displayPartsDocumentationsAndKind.symbolKind, + kind: symbolKind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: displayPartsDocumentationsAndKind.displayParts, - documentation: displayPartsDocumentationsAndKind.documentation, - tags: displayPartsDocumentationsAndKind.tags + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags, }; } function getSymbolAtLocationForQuickInfo(node, checker) { @@ -102198,32 +103489,156 @@ var ts; && ts.isPropertyAssignment(node.parent) && node.parent.name === node) { var type = checker.getContextualType(node.parent.parent); - if (type) { - var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); - if (property) { - return property; - } + var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); + if (property) { + return property; } } return checker.getSymbolAtLocation(node); } + var sourceMapCommentRegExp = /^\/\/[@#] sourceMappingURL=(.+)$/gm; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; + } + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + sourceMapCommentRegExp.lastIndex = starts[index]; + var comment = sourceMapCommentRegExp.exec(mappedFile.text); + if (comment) { + return comment[1]; + } + } + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, program, sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function makeGetTargetOfMappedPosition(extract, create) { + return getTargetOfMappedPosition; + function getTargetOfMappedPosition(input) { + var info = extract(input); + if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { + var file = program.getSourceFile(info.fileName); + if (!file) { + var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); + file = sourcemappedFileCache.get(path); + } + if (!file) { + return input; + } + var mapper = getSourceMapper(info.fileName, file); + var newLoc = mapper.getOriginalPosition(info); + if (newLoc === info) + return input; + return getTargetOfMappedPosition(create(newLoc, input)); + } + return input; + } + } + var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + containerKind: info.containerKind, + containerName: info.containerName, + fileName: newLoc.fileName, + kind: info.kind, + name: info.name, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + } + }); }); + function getTargetOfMappedDeclarationFiles(infos) { + return ts.map(infos, getTargetOfMappedDeclarationInfo); + } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position)); } function getDefinitionAndBoundSpan(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + var result = ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + if (!result) + return result; + var mappedDefs = getTargetOfMappedDeclarationFiles(result.definitions); + if (mappedDefs === result.definitions) { + return result; + } + return { + definitions: mappedDefs, + textSpan: result.textSpan + }; } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); + return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position)); } /// Goto implementation + var getTargetOfMappedImplementationLocation = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + fileName: newLoc.fileName, + kind: info.kind, + displayParts: info.displayParts, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + } + }); }); + function getTargetOfMappedImplementationLocations(infos) { + return ts.map(infos, getTargetOfMappedImplementationLocation); + } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return getTargetOfMappedImplementationLocations(ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position)); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -102443,29 +103858,32 @@ var ts; } return []; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); 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, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); }); } - function getCombinedCodeFix(scope, fixId, formatOptions) { + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions) { + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -102479,6 +103897,7 @@ var ts; : Promise.reject("Host does not implement `installPackage`"); default: ts.Debug.fail(); + // TODO: Debug.assertNever(action); will only work if there is more than one type. } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -102562,7 +103981,7 @@ var ts; if (!ts.isInComment(sourceFile, matchPosition)) { continue; } - var descriptor = undefined; + var descriptor = void 0; for (var i = 0; i < descriptors.length; i++) { if (matchArray[i + firstDescriptorCaptureIndex]) { descriptor = descriptors[i]; @@ -102646,7 +104065,7 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } - function getRefactorContext(file, positionOrRange, formatOptions) { + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; return { file: file, @@ -102656,23 +104075,27 @@ var ts; host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, + preferences: preferences, }; } - function getApplicableRefactors(fileName, positionOrRange) { + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); } - function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -103050,24 +104473,23 @@ var ts; return textSpan(node); } if (node.kind === 198 /* BinaryExpression */) { - var binaryExpression = node; + var _a = node, left = _a.left, operatorToken = _a.operatorToken; // 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 (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } - if (binaryExpression.operatorToken.kind === 58 /* EqualsToken */ && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.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 /* CommaToken */) { - return spanInNode(binaryExpression.left); + if (operatorToken.kind === 26 /* CommaToken */) { + return spanInNode(left); } } if (ts.isExpressionNode(node)) { @@ -103095,46 +104517,49 @@ var ts; break; } } - // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 268 /* 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 === 188 /* 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); - } - // initializer of variable/parameter declaration go to previous node - if ((node.parent.kind === 230 /* VariableDeclaration */ || - node.parent.kind === 148 /* Parameter */)) { - var paramOrVarDecl = node.parent; - if (paramOrVarDecl.initializer === node || - paramOrVarDecl.type === node || - ts.isAssignmentOperator(node.kind)) { - return spanInPreviousNode(node); + switch (node.parent.kind) { + case 268 /* PropertyAssignment */: + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + return spanInNode(node.parent.initializer); + } + break; + case 188 /* TypeAssertionExpression */: + // Breakpoint in type assertion goes to its operand + if (node.parent.type === node) { + return spanInNextNode(node.parent.type); + } + break; + case 230 /* VariableDeclaration */: + case 148 /* Parameter */: { + // initializer of variable/parameter declaration go to previous node + var _b = node.parent, initializer = _b.initializer, type = _b.type; + if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; } - } - if (node.parent.kind === 198 /* 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); + case 198 /* BinaryExpression */: { + var left = node.parent.left; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + break; } + default: + // return type of function go to previous token + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } } // Default go to parent to set the breakpoint return spanInNode(node.parent); } } function textSpanFromVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ && - variableDeclaration.parent.declarations[0] === variableDeclaration) { + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) { // First declaration - include let keyword return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); } @@ -103159,7 +104584,7 @@ var ts; variableDeclaration.parent.parent.kind === 220 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ && + if (ts.isVariableDeclarationList(variableDeclaration.parent) && 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 @@ -103717,8 +105142,7 @@ 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(), + category: ts.diagnosticCategoryName(diagnostic), code: diagnostic.code }; } @@ -103768,7 +105192,7 @@ var ts; }; LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { var newLine = ts.getNewLineOrDefaultFromHost(this.host); - return ts.realizeDiagnostics(diagnostics, newLine); + return realizeDiagnostics(diagnostics, newLine); }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; @@ -103806,6 +105230,10 @@ var ts; return _this.realizeDiagnostics(diagnostics); }); }; + LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + }; LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { var _this = this; return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { @@ -103936,16 +105364,16 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = options === undefined ? undefined : JSON.parse(options); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -104102,8 +105530,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { - var ref = refs_2[_i]; + for (var _i = 0, refs_3 = refs; _i < refs_3.length; _i++) { + var ref = refs_3[_i]; result.push({ path: ts.normalizeSlashes(ref.fileName), position: ref.pos, diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index ca9bf106e1e..5fd6d55b4a2 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -59,7 +59,8 @@ 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; + 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.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -389,7 +390,7 @@ declare namespace ts { FirstJSDocNode = 274, LastJSDocNode = 292, FirstJSDocTagNode = 284, - LastJSDocTagNode = 292, + LastJSDocTagNode = 292 } enum NodeFlags { None = 0, @@ -417,7 +418,7 @@ declare namespace ts { ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, ContextFlags = 6387712, - TypeExcludesFlags = 20480, + TypeExcludesFlags = 20480 } enum ModifierFlags { None = 0, @@ -438,6 +439,7 @@ declare namespace ts { NonPublicAccessibilityModifier = 24, TypeScriptModifier = 2270, ExportDefault = 513, + All = 3071 } enum JsxFlags { None = 0, @@ -445,7 +447,7 @@ declare namespace ts { IntrinsicNamedElement = 1, /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - IntrinsicElement = 3, + IntrinsicElement = 3 } interface Node extends TextRange { kind: SyntaxKind; @@ -643,8 +645,9 @@ declare namespace ts { questionToken?: QuestionToken; body?: Block | Expression; } - type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; + /** @deprecated Use SignatureDeclaration */ + type FunctionLike = SignatureDeclaration; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -652,7 +655,7 @@ declare namespace ts { } interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; - parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + parent?: ObjectTypeDeclaration; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { @@ -686,7 +689,7 @@ declare namespace ts { type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + parent?: ObjectTypeDeclaration; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -1078,11 +1081,13 @@ declare namespace ts { kind: SyntaxKind.JsxOpeningElement; parent?: JsxElement; tagName: JsxTagNameExpression; + typeArguments?: NodeArray; attributes: JsxAttributes; } interface JsxSelfClosingElement extends PrimaryExpression { kind: SyntaxKind.JsxSelfClosingElement; tagName: JsxTagNameExpression; + typeArguments?: NodeArray; attributes: JsxAttributes; } interface JsxFragment extends PrimaryExpression { @@ -1261,6 +1266,7 @@ declare namespace ts { variableDeclaration?: VariableDeclaration; block: Block; } + type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; @@ -1553,7 +1559,7 @@ declare namespace ts { PreFinally = 2048, AfterFinally = 4096, Label = 12, - Condition = 96, + Condition = 96 } interface FlowLock { locked?: boolean; @@ -1725,7 +1731,7 @@ declare namespace ts { enum ExitStatus { Success = 0, DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, + DiagnosticsPresent_OutputsGenerated = 2 } interface EmitResult { emitSkipped: boolean; @@ -1750,9 +1756,9 @@ declare namespace ts { /** 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 & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; - } | undefined; + }) | undefined; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ @@ -1801,7 +1807,7 @@ declare namespace ts { */ getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; - isImplementationOfOverload(node: FunctionLike): boolean | undefined; + isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; @@ -1811,7 +1817,7 @@ declare namespace ts { getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; - getJsxIntrinsicTagNames(): Symbol[]; + getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; @@ -1847,7 +1853,7 @@ declare namespace ts { InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, - InReverseMappedType = 33554432, + InReverseMappedType = 33554432 } enum TypeFormatFlags { None = 0, @@ -1870,14 +1876,14 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469291, + NodeBuilderFlagsMask = 9469291 } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8, + UseAliasDefinedOutsideCurrentScope = 8 } /** * @deprecated @@ -1914,7 +1920,7 @@ declare namespace ts { } enum TypePredicateKind { This = 0, - Identifier = 1, + Identifier = 1 } interface TypePredicateBase { kind: TypePredicateKind; @@ -1960,28 +1966,28 @@ declare namespace ts { JSContainer = 67108864, Enum = 384, Variable = 3, - Value = 107455, - Type = 793064, + Value = 67216319, + Type = 67901928, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 107454, - BlockScopedVariableExcludes = 107455, - ParameterExcludes = 107455, + FunctionScopedVariableExcludes = 67216318, + BlockScopedVariableExcludes = 67216319, + ParameterExcludes = 67216319, PropertyExcludes = 0, - EnumMemberExcludes = 900095, - FunctionExcludes = 106927, - ClassExcludes = 899519, - InterfaceExcludes = 792968, - RegularEnumExcludes = 899327, - ConstEnumExcludes = 899967, - ValueModuleExcludes = 106639, + EnumMemberExcludes = 68008959, + FunctionExcludes = 67215791, + ClassExcludes = 68008383, + InterfaceExcludes = 67901832, + RegularEnumExcludes = 68008191, + ConstEnumExcludes = 68008831, + ValueModuleExcludes = 67215503, NamespaceModuleExcludes = 0, - MethodExcludes = 99263, - GetAccessorExcludes = 41919, - SetAccessorExcludes = 74687, - TypeParameterExcludes = 530920, - TypeAliasExcludes = 793064, + MethodExcludes = 67208127, + GetAccessorExcludes = 67150783, + SetAccessorExcludes = 67183551, + TypeParameterExcludes = 67639784, + TypeAliasExcludes = 67901928, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -1989,7 +1995,7 @@ declare namespace ts { HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500, + ClassMember = 106500 } interface Symbol { flags: SymbolFlags; @@ -2016,7 +2022,7 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default", + Default = "default" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2091,7 +2097,7 @@ declare namespace ts { Instantiable = 7897088, StructuredOrInstantiable = 8355840, Narrowable = 142575359, - NotUnionOrUnit = 134283777, + NotUnionOrUnit = 134283777 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2132,7 +2138,7 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, - ClassOrInterface = 3, + ClassOrInterface = 3 } interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2189,31 +2195,46 @@ declare namespace ts { indexType: Type; constraint?: Type; } + type TypeVariable = TypeParameter | IndexedAccessType; interface IndexType extends InstantiableType { type: InstantiableType | UnionOrIntersectionType; } - interface ConditionalType extends InstantiableType { + interface ConditionalRoot { + node: ConditionalTypeNode; checkType: Type; extendsType: Type; trueType: Type; falseType: Type; + isDistributive: boolean; + inferTypeParameters: TypeParameter[]; + outerTypeParameters?: TypeParameter[]; + instantiations?: Map; + aliasSymbol: Symbol; + aliasTypeArguments: Type[]; + } + interface ConditionalType extends InstantiableType { + root: ConditionalRoot; + checkType: Type; + extendsType: Type; + resolvedTrueType?: Type; + resolvedFalseType?: Type; } interface SubstitutionType extends InstantiableType { - typeParameter: TypeParameter; + typeVariable: TypeVariable; substitute: Type; } enum SignatureKind { Call = 0, - Construct = 1, + Construct = 1 } interface Signature { - declaration: SignatureDeclaration; + declaration?: SignatureDeclaration; typeParameters?: TypeParameter[]; parameters: Symbol[]; } enum IndexKind { String = 0, - Number = 1, + Number = 1 } interface IndexInfo { type: Type; @@ -2222,41 +2243,14 @@ declare namespace ts { } enum InferencePriority { NakedTypeVariable = 1, - MappedType = 2, - ReturnType = 4, - NoConstraints = 8, - AlwaysStrict = 16, + HomomorphicMappedType = 2, + MappedTypeConstraint = 4, + ReturnType = 8, + LiteralKeyof = 16, + NoConstraints = 32, + AlwaysStrict = 64, + PriorityImpliesCombination = 28 } - interface InferenceInfo { - typeParameter: TypeParameter; - candidates: Type[]; - contraCandidates: Type[]; - inferredType: Type; - priority: InferencePriority; - topLevel: boolean; - isFixed: boolean; - } - enum InferenceFlags { - None = 0, - InferUnionTypes = 1, - NoDefault = 2, - AnyDefault = 4, - } - /** - * 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, - } - type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2292,11 +2286,12 @@ declare namespace ts { enum DiagnosticCategory { Warning = 0, Error = 1, - Message = 2, + Suggestion = 2, + Message = 3 } enum ModuleResolutionKind { Classic = 1, - NodeJs = 2, + NodeJs = 2 } interface PluginImport { name: string; @@ -2312,6 +2307,7 @@ declare namespace ts { charset?: string; checkJs?: boolean; declaration?: boolean; + declarationMap?: boolean; emitDeclarationOnly?: boolean; declarationDir?: string; disableSizeLimit?: boolean; @@ -2390,17 +2386,17 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6, + ESNext = 6 } enum JsxEmit { None = 0, Preserve = 1, React = 2, - ReactNative = 3, + ReactNative = 3 } enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1, + LineFeed = 1 } interface LineAndCharacter { /** 0-based. */ @@ -2414,7 +2410,7 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, - JSON = 6, + JSON = 6 } enum ScriptTarget { ES3 = 0, @@ -2424,11 +2420,11 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, - Latest = 6, + Latest = 6 } enum LanguageVariant { Standard = 0, - JSX = 1, + JSX = 1 } /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { @@ -2442,7 +2438,7 @@ declare namespace ts { } enum WatchDirectoryFlags { None = 0, - Recursive = 1, + Recursive = 1 } interface ExpandResult { fileNames: string[]; @@ -2512,7 +2508,7 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", - Json = ".json", + Json = ".json" } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; @@ -2582,7 +2578,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216, + NoAsciiEscaping = 16777216 } interface EmitHelper { readonly name: string; @@ -2595,7 +2591,7 @@ declare namespace ts { Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4, + Unspecified = 4 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2762,6 +2758,7 @@ declare namespace ts { newLine?: NewLineKind; omitTrailingSemicolon?: boolean; } + /** @deprecated See comment on SymbolWriter */ interface SymbolTracker { trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError?(): void; @@ -2812,9 +2809,9 @@ declare namespace ts { SingleElement = 524288, Modifiers = 131328, HeritageClauses = 256, - SingleLineTypeLiteralMembers = 448, - MultiLineTypeLiteralMembers = 65, - TupleTypeElements = 336, + SingleLineTypeLiteralMembers = 384, + MultiLineTypeLiteralMembers = 16449, + TupleTypeElements = 272, UnionTypeConstituents = 260, IntersectionTypeConstituents = 264, ObjectBindingPatternElements = 262576, @@ -2830,12 +2827,12 @@ declare namespace ts { VariableDeclarationList = 272, SingleLineFunctionBodyStatements = 384, MultiLineFunctionBodyStatements = 1, - ClassHeritageClauses = 256, + ClassHeritageClauses = 0, ClassMembers = 65, InterfaceMembers = 65, EnumMembers = 81, CaseBlockClauses = 65, - NamedImportsOrExportsElements = 432, + NamedImportsOrExportsElements = 262576, JsxElementOrFragmentChildren = 131072, JsxElementAttributes = 131328, CaseOrDefaultClauseStatements = 81985, @@ -2845,11 +2842,11 @@ declare namespace ts { TypeArguments = 26896, TypeParameters = 26896, Parameters = 1296, - IndexSignatureParameters = 4432, + IndexSignatureParameters = 4432 } } declare namespace ts { - const versionMajorMinor = "2.8"; + const versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ const version: string; } @@ -2863,15 +2860,10 @@ declare namespace ts { enum FileWatcherEventKind { Created = 0, Changed = 1, - Deleted = 2, + Deleted = 2 } type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; - interface WatchedFile { - fileName: string; - callback: FileWatcherCallback; - mtime?: Date; - } interface System { args: string[]; newLine: string; @@ -2906,6 +2898,8 @@ declare namespace ts { setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; clearScreen?(): void; + base64decode?(input: string): string; + base64encode?(input: string): string; } interface FileWatcher { close(): void; @@ -2932,8 +2926,8 @@ declare namespace ts { reScanTemplateToken(): SyntaxKind; scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): SyntaxKind; - scanJsxToken(): SyntaxKind; + reScanJsxToken(): JsxTokenSyntaxKind; + scanJsxToken(): JsxTokenSyntaxKind; scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; @@ -2947,7 +2941,7 @@ declare namespace ts { tryScan(callback: () => T): T; } function tokenToString(t: SyntaxKind): string | undefined; - function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; + function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, 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. */ @@ -3066,7 +3060,7 @@ declare namespace ts { * 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; + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -3104,9 +3098,9 @@ 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; + function getJSDocTags(node: Node): ReadonlyArray; /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ - function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3260,6 +3254,7 @@ declare namespace ts { function isJSDocVariadicType(node: Node): node is JSDocVariadicType; function isJSDoc(node: Node): node is JSDoc; function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocClassTag(node: Node): node is JSDocClassTag; function isJSDocParameterTag(node: Node): node is JSDocParameterTag; function isJSDocReturnTag(node: Node): node is JSDocReturnTag; function isJSDocTypeTag(node: Node): node is JSDocTypeTag; @@ -3283,7 +3278,7 @@ declare namespace ts { function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node): node is FunctionLike; + function isFunctionLike(node: Node): node is SignatureDeclaration; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; @@ -3301,7 +3296,8 @@ declare namespace ts { function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; function isTemplateLiteral(node: Node): node is TemplateLiteral; function isAssertionExpression(node: Node): node is AssertionExpression; - function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; 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. */ @@ -3398,6 +3394,8 @@ declare namespace ts { function createLoopVariable(): Identifier; /** Create a unique name based on the supplied text. */ function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; /** Create a unique name generated for a node. */ function getGeneratedNameForNode(node: Node): Identifier; function createToken(token: TKind): Token; @@ -3406,6 +3404,8 @@ declare namespace ts { function createNull(): NullLiteral & Token; function createTrue(): BooleanLiteral & Token; function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; @@ -3606,7 +3606,7 @@ declare namespace ts { function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; @@ -3628,10 +3628,10 @@ declare namespace ts { function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; - function createJsxSelfClosingElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; - function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; - function createJsxOpeningElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; - function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; + function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; @@ -3660,7 +3660,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; 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; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ @@ -4332,10 +4332,17 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; } + interface UserPreferences { + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + } interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): Diagnostic[]; getSemanticDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): Diagnostic[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. @@ -4348,7 +4355,7 @@ declare namespace ts { getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, name: string, options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined): CompletionEntryDetails; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | 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; @@ -4378,8 +4385,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; - getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4389,9 +4396,9 @@ declare namespace ts { 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; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings): ReadonlyArray; + getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -4401,9 +4408,12 @@ declare namespace ts { fileName: string; } type OrganizeImportsScope = CombinedCodeFixScope; - interface GetCompletionsAtPositionOptions { - includeExternalModuleExports: boolean; - includeInsertTextCompletions: boolean; + /** @deprecated Use UserPreferences */ + interface GetCompletionsAtPositionOptions extends UserPreferences { + /** @deprecated Use includeCompletionsForModuleExports */ + includeExternalModuleExports?: boolean; + /** @deprecated Use includeCompletionsWithInsertText */ + includeInsertTextCompletions?: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4484,6 +4494,7 @@ declare namespace ts { * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + fixAllDescription?: string; } interface CombinedCodeActions { changes: ReadonlyArray; @@ -4569,7 +4580,7 @@ declare namespace ts { none = "none", definition = "definition", reference = "reference", - writtenReference = "writtenReference", + writtenReference = "writtenReference" } interface HighlightSpan { fileName?: string; @@ -4591,7 +4602,7 @@ declare namespace ts { enum IndentStyle { None = 0, Block = 1, - Smart = 2, + Smart = 2 } interface EditorOptions { BaseIndentSize?: number; @@ -4686,7 +4697,7 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21, + regularExpressionLiteral = 21 } interface SymbolDisplayPart { text: string; @@ -4746,7 +4757,7 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { - /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isGlobalCompletionScope`. */ + /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */ isGlobalCompletion: boolean; isMemberCompletion: boolean; /** @@ -4797,7 +4808,7 @@ declare namespace ts { enum OutputFileType { JavaScript = 0, SourceMap = 1, - Declaration = 2, + Declaration = 2 } enum EndOfLineState { None = 0, @@ -4806,7 +4817,7 @@ declare namespace ts { InDoubleQuoteStringLiteral = 3, InTemplateHeadOrNoSubstitutionTemplate = 4, InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, + InTemplateSubstitutionPosition = 6 } enum TokenClass { Punctuation = 0, @@ -4817,7 +4828,7 @@ declare namespace ts { Identifier = 5, NumberLiteral = 6, StringLiteral = 7, - RegExpLiteral = 8, + RegExpLiteral = 8 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -4916,7 +4927,7 @@ declare namespace ts { /** * */ - jsxAttribute = "JSX attribute", + jsxAttribute = "JSX attribute" } enum ScriptElementKindModifier { none = "", @@ -4927,7 +4938,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional", + optionalModifier = "optional" } enum ClassificationTypeNames { comment = "comment", @@ -4952,7 +4963,7 @@ declare namespace ts { jsxSelfClosingTagName = "jsx self closing tag name", jsxAttribute = "jsx attribute", jsxText = "jsx text", - jsxAttributeStringLiteralValue = "jsx attribute string literal value", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" } enum ClassificationType { comment = 1, @@ -4978,7 +4989,7 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24, + jsxAttributeStringLiteralValue = 24 } } declare namespace ts { @@ -5072,7 +5083,7 @@ declare namespace ts { } declare namespace ts { /** The version of the language service API */ - const servicesVersion = "0.7"; + const servicesVersion = "0.8"; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 71de0f4e0b6..06d660a8873 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -41,7 +41,7 @@ var ts; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; })(Comparison = ts.Comparison || (ts.Comparison = {})); - // token > SyntaxKind.Identifer => token is a keyword + // token > SyntaxKind.Identifier => 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) { @@ -474,6 +474,7 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -500,6 +501,7 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["OptimisticUnique"] = 5] = "OptimisticUnique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; // Flags GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; @@ -729,32 +731,32 @@ var ts; SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // 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"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "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["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "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["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -949,11 +951,15 @@ var ts; var InferencePriority; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; - InferencePriority[InferencePriority["NoConstraints"] = 8] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 16] = "AlwaysStrict"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + /* @internal */ var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; @@ -970,6 +976,7 @@ var ts; * 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. */ + /* @internal */ var Ternary; (function (Ternary) { Ternary[Ternary["False"] = 0] = "False"; @@ -990,13 +997,23 @@ var ts; SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + // F.prototype = { ... } + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; - DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + /* @internal */ + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; @@ -1391,9 +1408,9 @@ var ts; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; @@ -1409,12 +1426,12 @@ var ts; ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; @@ -1426,6 +1443,68 @@ var ts; ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); + /* @internal */ + var PragmaKindFlags; + (function (PragmaKindFlags) { + PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; + /** + * Triple slash comment of the form + * /// + */ + PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; + /** + * Single line comment of the form + * // @pragma-name argval1 argval2 + * or + * /// @pragma-name argval1 argval2 + */ + PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; + /** + * Multiline non-jsdoc pragma of the form + * /* @pragma-name argval1 argval2 * / + */ + PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; + PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; + PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; + })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); + /** + * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas` + */ + /* @internal */ + function _contextuallyTypePragmas(args) { + return args; + } + // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't + // fancy effectively defining it twice, once in value-space and once in type-space + /* @internal */ + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + }); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1526,7 +1605,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.8"; + ts.versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1546,6 +1625,10 @@ var ts; /* @internal */ (function (ts) { ts.emptyArray = []; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -2087,22 +2170,6 @@ var ts; }; } ts.singleIterator = singleIterator; - /** - * 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++) { - if (!f(array[i], i)) { - return [array.slice(0, i), array.slice(i)]; - } - } - return [array.slice(0), []]; - } - return undefined; - } - ts.span = span; /** * Maps contiguous spans of values with the same key. * @@ -2363,7 +2430,6 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2522,7 +2588,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return elementAt(array, 0); + return array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -2534,7 +2600,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return elementAt(array, -1); + return array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -2752,19 +2818,21 @@ var ts; } ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } var result = createMap(); 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); + result.set(makeKey(value), makeValue(value)); } return result; } ts.arrayToMap = arrayToMap; function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } 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; + result[makeKey(value)] = makeValue(value); } return result; } @@ -2773,6 +2841,20 @@ var ts; return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } ts.arrayToSet = arrayToSet; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -2830,15 +2912,6 @@ var ts; } } } - function group(values, getGroupId) { - var groupIdToGroup = createMultiMap(); - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - groupIdToGroup.add(getGroupId(value), value); - } - return arrayFrom(groupIdToGroup.values()); - } - ts.group = group; /** * Tests whether a value is an array. */ @@ -2958,7 +3031,6 @@ var ts; return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.formatStringFromArgs = formatStringFromArgs; - ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } @@ -3390,6 +3462,10 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAreDeclarationMapsEnabled(options) { + return !!(options.declaration && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined @@ -3809,7 +3885,6 @@ 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); }); @@ -3842,7 +3917,7 @@ var ts; } } }; - for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + for (var _i = 0, _b = sort(files, compareStringsCaseSensitive); _i < _b.length; _i++) { var current = _b[_i]; _loop_1(current); } @@ -3852,7 +3927,7 @@ var ts; return; } } - for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -3884,7 +3959,7 @@ var ts; // 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); })) { + if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -4289,7 +4364,7 @@ var ts; ts.matchedText = matchedText; /** Return the object corresponding to the best pattern to match `candidate`. */ function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; + var matchedValue; // use length of prefix as betterness criteria var longestMatchPrefixLength = -1; for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { @@ -4382,6 +4457,38 @@ var ts; return t === undefined ? undefined : [t]; } ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(ts || (ts = {})); /// var ts; @@ -4393,7 +4500,7 @@ var ts; */ /* @internal */ function setStackTraceLimit() { - if (Error.stackTraceLimit < 100) { + if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. Error.stackTraceLimit = 100; } } @@ -4404,6 +4511,314 @@ var ts; FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + /* @internal */ + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + function getPriorityValues(highPriorityValue) { + var mediumPriorityValue = highPriorityValue * 2; + var lowPriorityValue = mediumPriorityValue * 4; + return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; + } + function pollingInterval(watchPriority) { + return pollingIntervalsForPriority[watchPriority]; + } + var pollingIntervalsForPriority = getPriorityValues(250); + /* @internal */ + function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { + return host.watchFile(fileName, callback, pollingInterval(watchPriority)); + } + ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; + /* @internal */ + ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + function createPollingIntervalBasedLevels(levels) { + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + var _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + /* @internal */ + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + /* @internal */ + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + // Remove from watchedFiles + ts.unorderedRemoveItem(watchedFiles, file); + // Do not update polling interval queue since that will happen as part of polling + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + // Set the next polling index and timeout + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + // Always poll complete list of changedFilesInLastPoll + pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length); + // Finally do the actual polling of the queue + pollPollingIntervalQueue(queue); + // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue + // as pollPollingIntervalQueue wont schedule for next poll + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + // Max visit would be all elements of the queue + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + // Changed files go to changedFilesInLastPoll queue + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + // Restart unchangedPollCount for unchanged file and move to low polling interval queue + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from nextDefinedValueIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + /** + * Returns true if file status changed + */ + /*@internal*/ + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + var eventKind = oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + watchedFile.callback(watchedFile.fileName, eventKind); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + /** + * Watch the directory recursively using host provided method to watch child directories + * that means if this is recursive watcher, watch the children directories as well + * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) + */ + /*@internal*/ + function createRecursiveDirectoryWatcher(host) { + return createDirectoryWatcher; + /** + * Create the directory watcher for the dirPath. + */ + function createDirectoryWatcher(dirName, callback) { + var watcher = host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callback(fileName); + // Iterate through existing children and update the watches if needed + updateChildWatches(result, callback); + }); + var result = { + close: function () { + watcher.close(); + result.childWatches.forEach(ts.closeFileWatcher); + result = undefined; + }, + dirName: dirName, + childWatches: ts.emptyArray + }; + updateChildWatches(result, callback); + return result; + } + function updateChildWatches(watcher, callback) { + // Iterate through existing children and update the watches if needed + if (watcher) { + watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + } + } + /** + * Watch the directories in the parentDir + */ + function watchChildDirectories(parentDir, existingChildWatches, callback) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(ts.getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + /** + * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list + */ + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(ts.getNormalizedAbsolutePath(childName, parentDir), callback); + addChildDirectoryWatcher(result); + } + /** + * Add child directory watcher to the new ChildDirectoryWatcher list + */ + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -4436,82 +4851,110 @@ var ts; catch (_a) { _crypto = undefined; } - var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } - function createMD5HashUsingNativeCrypto(data) { - var hash = _crypto.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - } - function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - // One file can have multiple watchers - var fileWatcherCallbacks = ts.createMultiMap(); - return { addFile: addFile, removeFile: removeFile }; - function reduceDirWatcherRefCountForFile(fileName) { - var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers.get(dirName); - if (watcher) { - watcher.referenceCount -= 1; - if (watcher.referenceCount <= 0) { - watcher.close(); - dirWatchers.delete(dirName); - } - } - } - function addDirWatcher(dirPath) { - var watcher = dirWatchers.get(dirPath); - if (watcher) { - watcher.referenceCount += 1; - return; - } - watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); - watcher.referenceCount = 1; - dirWatchers.set(dirPath, watcher); - return; - } - function addFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.add(filePath, callback); - } - function addFile(fileName, callback) { - addFileWatcherCallback(fileName, callback); - addDirWatcher(ts.getDirectoryPath(fileName)); - return { fileName: fileName, callback: callback }; - } - function removeFile(watchedFile) { - removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback); - reduceDirWatcherRefCountForFile(watchedFile.fileName); - } - function removeFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.remove(filePath, callback); - } - function fileEventHandler(eventName, relativeFileName, baseDirPath) { - // 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) { - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); - } - } - } - } - } - var watchedFileSet = createWatchedFileSet(); + var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch ( /*ignore*/_a) { /*ignore*/ } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: function (path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + // Could not enable source maps. + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + base64decode: Buffer.from ? function (input) { + return Buffer.from(input, "base64").toString("utf8"); + } : function (input) { + return new Buffer(input, "base64").toString("utf8"); + }, + base64encode: Buffer.from ? function (input) { + return Buffer.from(input).toString("base64"); + } : function (input) { + return new Buffer(input).toString("base64"); + } + }; + return nodeSystem; function isFileSystemCaseSensitive() { // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { @@ -4527,46 +4970,187 @@ var ts; return ch === up ? ch.toLowerCase() : up; }); } - var platform = _os.platform(); - var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + // Use polling interval based on priority when create watch using host.watchFile + return fsWatchFile; + case "DynamicPriorityPolling": + // Use polling interval but change the interval depending on file changes and their default polling interval + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + // Use notifications from FS to watch with falling back to fs.watchFile + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + // Use notifications from FS to watch with falling back to dynamic watch file + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + // Use notifications from FS to watch with falling back to fs.watchFile + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + // Default to do not use polling interval as it is before this experiment branch + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + // 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 fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + filePathComparer: useCaseSensitiveFileNames ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive, + directoryExists: directoryExists, + getAccessileSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + // 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, dirName); + // Some applications save a working file via rename operations + var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } function fsWatchFile(fileName, callback, pollingInterval) { _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; 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) { + // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears) + // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + // Already deleted file, no need to callback again + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + // If there is no change in modified time, ignore the event + else if (+curr.mtime === +prev.mtime) { return; } + else { + // File changed + eventKind = FileWatcherEventKind.Changed; + } callback(fileName, eventKind); } } - function fsWatchDirectory(directoryName, callback, recursive) { + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + // Change + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return 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 ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { var options; - /** Watcher for the directory depending on whether it is missing or present */ - var watcher = !directoryExists(directoryName) ? - watchMissingDirectory() : - watchPresentDirectory(); + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); return { close: function () { - // Close the watcher (either existing directory watcher or missing directory watcher) + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) watcher.close(); + watcher = undefined; } }; /** - * Watch the directory that is currently present - * and when the watched directory is deleted, switch to missing directory watcher + * Invoke the callback with rename and update the watcher if not closed + * @param createWatcher */ - function watchPresentDirectory() { + function invokeCallbackAndUpdateWatcher(createWatcher) { + // Call the callback for current directory + callback("rename", ""); + // If watcher is not closed, update it + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { // 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) { @@ -4577,34 +5161,56 @@ var ts; 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; + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + return watchPresentFileSystemEntryWithFsWatchFile(); + } } /** - * Watch the directory that is missing - * and switch to existing directory when the directory is created + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point */ - function watchMissingDirectory() { - return fsWatchFile(directoryName, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { - watcher.close(); - watcher = watchPresentDirectory(); - // Call the callback for current directory + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + // Call the callback for current file or directory // For now it could be callback for the inner directory creation, // but just return current directory, better than current no-op - callback("rename", ""); + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); } - }); + }, pollingInterval); } } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -4685,11 +5291,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); @@ -4711,110 +5312,27 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } - var nodeSystem = { - clearScreen: function () { - process.stdout.write("\x1Bc"); - }, - args: process.argv.slice(2), - newLine: _os.EOL, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - write: function (s) { - process.stdout.write(s); - }, - readFile: readFile, - writeFile: writeFile, - watchFile: function (fileName, callback, pollingInterval) { - if (useNonPollingWatchers) { - var watchedFile_1 = watchedFileSet.addFile(fileName, callback); - return { - close: function () { return watchedFileSet.removeFile(watchedFile_1); } - }; - } - else { - 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) - 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, - directoryExists: directoryExists, - createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { - _fs.mkdirSync(directoryName); - } - }, - getExecutingFilePath: function () { - return __filename; - }, - getCurrentDirectory: function () { - return process.cwd(); - }, - getDirectories: getDirectories, - getEnvironmentVariable: function (name) { - return process.env[name] || ""; - }, - readDirectory: readDirectory, - getModifiedTime: function (path) { - try { - return _fs.statSync(path).mtime; - } - catch (e) { - return undefined; - } - }, - createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, - getMemoryUsage: function () { - if (global.gc) { - global.gc(); - } - return process.memoryUsage().heapUsed; - }, - getFileSize: function (path) { - try { - var stat = _fs.statSync(path); - if (stat.isFile()) { - return stat.size; - } - } - catch (_a) { } - return 0; - }, - exit: function (exitCode) { - process.exit(exitCode); - }, - realpath: function (path) { - try { - return _fs.realpathSync(path); - } - catch (_a) { - return path; - } - }, - debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), - tryEnableSourceMapsForHost: function () { - try { - require("source-map-support").install(); - } - catch (_a) { - // Could not enable source maps. - } - }, - setTimeout: setTimeout, - clearTimeout: clearTimeout - }; - return nodeSystem; + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -4883,6 +5401,7 @@ var ts; return sys; })(); if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ : 0 /* None */; @@ -5481,6 +6000,7 @@ var ts; Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), 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}'."), @@ -5552,7 +6072,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), 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."), @@ -5592,6 +6112,8 @@ var ts; 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."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), 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."), @@ -5725,7 +6247,7 @@ var ts; Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), - Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), @@ -5769,6 +6291,8 @@ var ts; Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused."), 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."), @@ -5828,6 +6352,7 @@ var ts; 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."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), 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."), @@ -5848,14 +6373,20 @@ var ts; 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"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), 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}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), 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}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{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"), @@ -5892,6 +6423,33 @@ var ts; Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_this_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_this_to_all_unresolved_variables_matching_a_member_name_95037", "Add 'this.' to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), }; })(ts || (ts = {})); /// @@ -7684,6 +8242,13 @@ var ts; return token = 26 /* CommaToken */; case 46 /* dot */: return token = 23 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 13 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { @@ -8020,9 +8585,9 @@ var ts; return false; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; - function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { @@ -8056,18 +8621,15 @@ var ts; ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } - if (nodeIsMissing(node)) { - return ""; - } - var text = sourceFile.text; - return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; - function getTextOfNodeFromSourceText(sourceText, node) { + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8162,8 +8724,7 @@ var ts; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 237 /* ModuleDeclaration */ && - (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { @@ -8194,21 +8755,22 @@ var ts; } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(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 272 /* SourceFile */: return ts.isExternalModule(node.parent); case 238 /* ModuleBlock */: - return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } - ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -8276,6 +8838,10 @@ var ts; } } ts.isAnyImportSyntax = isAnyImportSyntax; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -8339,6 +8905,11 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, startNode.pos); + return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -8686,6 +9257,10 @@ var ts; return false; } ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 231 /* VariableDeclarationList */ && node.parent.parent.kind === 212 /* VariableStatement */; @@ -9123,6 +9698,10 @@ var ts; return isInJavaScriptFile(file); } ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isSourceFileNotJavaScript(file) { + return !isInJavaScriptFile(file); + } + ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { return node && !!(node.flags & 65536 /* JavaScriptFile */); } @@ -9139,7 +9718,7 @@ var ts; (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { if (callExpression.kind !== 185 /* CallExpression */) { return false; } @@ -9151,7 +9730,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 /* StringLiteral */ || arg.kind === 13 /* NoSubstitutionTemplateLiteral */; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -9163,17 +9742,117 @@ var ts; } 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. + * Given the symbol of a declaration, find the symbol of its Javascript container-like initializer, + * if it has one. Otherwise just return the original symbol. + * + * Container-like initializer behave like namespaces, so the binder needs to add contained symbols + * to their exports. An example is a function with assignments to `this` inside. */ - function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 230 /* VariableDeclaration */) { - var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 190 /* FunctionExpression */ || declaration.initializer.kind === 203 /* ClassExpression */); + function getJSInitializerSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return symbol; + } + var declaration = symbol.valueDeclaration; + var e = getDeclaredJavascriptInitializer(declaration) || getAssignedJavascriptInitializer(declaration); + return e && e.symbol ? e.symbol : symbol; + } + ts.getJSInitializerSymbol = getJSInitializerSymbol; + /** Get the declaration initializer, when the initializer is container-like (See getJavascriptInitializer) */ + function getDeclaredJavascriptInitializer(node) { + if (node && ts.isVariableDeclaration(node) && node.initializer) { + return getJavascriptInitializer(node.initializer, /*isPrototypeAssignment*/ false) || + ts.isIdentifier(node.name) && getDefaultedJavascriptInitializer(node.name, node.initializer, /*isPrototypeAssignment*/ false); + } + } + ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + /** + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * We treat the right hand side of assignments with container-like initalizers as declarations. + */ + function getAssignedJavascriptInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + } + ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + /** + * Recognized Javascript container-like initializers are: + * 1. (function() {})() -- IIFEs + * 2. function() { } -- Function expressions + * 3. class { } -- Class expressions + * 4. {} -- Empty object literals + * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` + * + * This function returns the provided initializer, or undefined if it is not valid. + */ + function getJavascriptInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 190 /* FunctionExpression */ || e.kind === 191 /* ArrowFunction */ ? initializer : undefined; + } + if (initializer.kind === 190 /* FunctionExpression */ || initializer.kind === 203 /* ClassExpression */) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getJavascriptInitializer = getJavascriptInitializer; + /** + * A defaulted Javascript initializer matches the pattern + * `Lhs = Lhs || JavascriptInitializer` + * or `var Lhs = Lhs || JavascriptInitializer` + * + * The second Lhs is required to be the same as the first except that it may be prefixed with + * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. + */ + function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ + function getOuterNameOfJsInitializer(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + /** + * Is the 'declared' name the same as the one in the initializer? + * @return true for identical entity names, as well as ones where the initializer is prefixed with + * 'window', 'self' or 'global'. For example: + * + * var my = my || {} + * var min = window.min || {} + * my.app = self.my.app || class { } + */ + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 99 /* ThisKeyword */ || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); } return false; } - ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; function getRightMostAssignedExpression(node) { while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) { node = node.right; @@ -9192,69 +9871,78 @@ var ts; /// 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 */; - } - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || expr.left.kind !== 183 /* PropertyAccessExpression */) { + if (!isInJavaScriptFile(expr) || + expr.operatorToken.kind !== 58 /* EqualsToken */ || + !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } var lhs = expr.left; - if (lhs.expression.kind === 71 /* Identifier */) { - var lhsId = lhs.expression; - if (lhsId.escapedText === "exports") { - // exports.name = expr - return 1 /* ExportsProperty */; - } - else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { - // module.exports = expr - return 2 /* ModuleExports */; - } - else { - // F.x = expr - return 5 /* Property */; - } - } - else if (lhs.expression.kind === 99 /* ThisKeyword */) { + if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (lhs.expression.kind === 183 /* 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 */) { - // module.exports.name = expr - var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { - return 1 /* ExportsProperty */; - } - if (innerPropertyAccess.name.escapedText === "prototype") { - return 3 /* PrototypeProperty */; - } + else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + // module.exports = expr + return 2 /* ModuleExports */; + } + else if (isEntityNameExpression(lhs.expression)) { + if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(expr.right)) { + // F.prototype = { ... } + return 6 /* Prototype */; } + else if (isPrototypeAccess(lhs.expression)) { + // F.G....prototype.x = expr + return 3 /* PrototypeProperty */; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + // exports.name = expr OR module.exports.name = expr + return 1 /* ExportsProperty */; + } + // F.G...x = expr + return 5 /* Property */; } return 0 /* None */; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && expr.parent && expr.parent.kind === 214 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function importFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + return node.parent; + case 252 /* ExternalModuleReference */: + return node.parent.parent; + case 185 /* CallExpression */: + return node.parent; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(node)); + } + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; function getExternalModuleName(node) { - if (node.kind === 242 /* ImportDeclaration */) { - return node.moduleSpecifier; - } - if (node.kind === 241 /* ImportEqualsDeclaration */) { - var reference = node.moduleReference; - if (reference.kind === 252 /* ExternalModuleReference */) { - return reference.expression; - } - } - if (node.kind === 248 /* ExportDeclaration */) { - return node.moduleSpecifier; - } - if (isModuleWithStringLiteralName(node)) { - return node.name; + switch (node.kind) { + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + return node.moduleSpecifier; + case 241 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 252 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + default: + return ts.Debug.assertNever(node); } } ts.getExternalModuleName = getExternalModuleName; @@ -9304,6 +9992,14 @@ var ts; node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 54 /* BarBarToken */ && + node.expression.right.right; + } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { case 212 /* VariableStatement */: @@ -9343,7 +10039,8 @@ var ts; (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node) { + if (parent && parent.parent && parent.parent.parent && + (getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || @@ -9382,7 +10079,8 @@ var ts; ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { var host = getJSDocHost(node); - var decl = getSourceOfAssignment(host) || + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || @@ -9407,7 +10105,7 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined; + return node.dotDotDotToken !== undefined || node.type && node.type.kind === 281 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9492,6 +10190,10 @@ var ts; return false; } ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -9506,6 +10208,13 @@ var ts; return walkUp(node, 189 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 189 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 183 /* PropertyAccessExpression */ && node.kind !== 184 /* ElementAccessExpression */) { @@ -9524,16 +10233,9 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - // True if the given identifier, string literal, or number literal is the name of a declaration node + // True if `name` is the name of a declaration node function isDeclarationName(name) { - switch (name.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - return ts.isDeclaration(name.parent) && name.parent.name === name; - default: - return false; - } + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; // See GH#16030 @@ -9626,6 +10328,13 @@ var ts; return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; @@ -9660,38 +10369,6 @@ var ts; return undefined; } ts.getAncestor = getAncestor; - function getFileReferenceFromReferencePath(comment, commentRange) { - var simpleReferenceRegEx = /^\/\/\/\s*= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode) + return "\\x00"; + } + // Otherwise, keep printing a literal \0 for the null character + return "\\0"; + } return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { @@ -10468,49 +11151,38 @@ 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, checkJSDoc) { - if (ts.hasType(node)) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocType(node); - } + function getEffectiveTypeAnnotationNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; /** * 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 (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocReturnType(node); - } + function getEffectiveReturnTypeNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; /** * 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 (checkJSDoc || isInJavaScriptFile(node)) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; - } + function getEffectiveTypeParameterDeclarations(node) { + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getJSDocTypeParameterDeclarations(node) { + var templateTag = ts.getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** * 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) { + function getEffectiveSetAccessorTypeAnnotationNode(node) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); + return parameter && getEffectiveTypeAnnotationNode(parameter); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -10614,7 +11286,7 @@ var ts; } return currentDetachedCommentInfo; function isPinnedCommentLocal(comment) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } ts.emitDetachedComments = emitDetachedComments; @@ -10815,10 +11487,17 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 183 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node) || (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node); @@ -10855,7 +11534,7 @@ var ts; var length = input.length; for (var i = 0; i < length; i++) { var charCode = input.charCodeAt(i); - // handel utf8 + // handle utf8 if (charCode < 0x80) { output.push(charCode); } @@ -10912,6 +11591,78 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11231,6 +11982,7 @@ var ts; map.delete(key); onDeleteValue(existingValue, key); } + // If present notify about existing values else if (onExistingValue) { onExistingValue(existingValue, valueInNewMap, key); } @@ -11292,6 +12044,42 @@ var ts; return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + /** Add a value to a set, and return true if it wasn't already present. */ + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11327,27 +12115,20 @@ var ts; } ts.textSpanContainsTextSpan = textSpanContainsTextSpan; function textSpanOverlapsWith(span, other) { - var overlapStart = Math.max(span.start, other.start); - var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); - return overlapStart < overlapEnd; + return textSpanOverlap(span, other) !== undefined; } ts.textSpanOverlapsWith = textSpanOverlapsWith; function textSpanOverlap(span1, span2) { - var overlapStart = Math.max(span1.start, span2.start); - var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (overlapStart < overlapEnd) { - return createTextSpanFromBounds(overlapStart, overlapEnd); - } - return undefined; + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; } ts.textSpanOverlap = textSpanOverlap; function textSpanIntersectsWithTextSpan(span, other) { - return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); } ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; function textSpanIntersectsWith(span, start, length) { - var end = start + length; - return start <= textSpanEnd(span) && end >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); } ts.textSpanIntersectsWith = textSpanIntersectsWith; function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { @@ -11361,12 +12142,9 @@ var ts; } ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; function textSpanIntersection(span1, span2) { - var intersectStart = Math.max(span1.start, span2.start); - var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (intersectStart <= intersectEnd) { - return createTextSpanFromBounds(intersectStart, intersectEnd); - } - return undefined; + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; } ts.textSpanIntersection = textSpanIntersection; function createTextSpan(start, length) { @@ -11379,6 +12157,13 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; + /* @internal */ + function createTextRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos); + return { pos: pos, end: end }; + } + ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11631,6 +12416,7 @@ var ts; return false; } try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } catch (e) { @@ -11757,6 +12543,11 @@ var ts; return declaration.name || nameForNamelessJSDocTypedef(declaration); } ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + /** @internal */ + function isNamedDeclaration(node) { + return !!node.name; // A 'name' property should always be a DeclarationName. + } + ts.isNamedDeclaration = isNamedDeclaration; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -11813,7 +12604,7 @@ var ts; 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; + return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; /** @@ -11823,33 +12614,33 @@ var ts; * for example on a variable declaration whose initializer is a function expression. */ function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 287 /* JSDocParameterTag */); + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } ts.hasJSDocParameterTags = hasJSDocParameterTags; /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 286 /* JSDocClassTag */); + return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 288 /* JSDocReturnTag */); + return getFirstJSDocTag(node, ts.isJSDocReturnTag); } ts.getJSDocReturnTag = getJSDocReturnTag; /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 290 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); } 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, 289 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -11868,12 +12659,9 @@ var ts; * tag directly on the node would be returned. */ function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 289 /* JSDocTypeTag */); - if (!tag && node.kind === 148 /* Parameter */) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); } return tag && tag.typeExpression && tag.typeExpression.type; } @@ -11900,14 +12688,12 @@ var ts; } 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; }); + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); } /** 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; }); + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); @@ -12533,6 +13319,10 @@ var ts; return node.kind === 285 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 286 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { return node.kind === 287 /* JSDocParameterTag */; } @@ -12654,6 +13444,16 @@ var ts; return false; } ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { return isModifierKind(node.kind); } @@ -12958,7 +13758,7 @@ var ts; case 97 /* SuperKeyword */: case 207 /* NonNullExpression */: case 208 /* MetaProperty */: - case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression + case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: return false; @@ -13043,7 +13843,6 @@ var ts; || isPartiallyEmittedExpression(node); } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; - // Statement function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { case 218 /* ForStatement */: @@ -13317,6 +14116,45 @@ var ts; return !!node.type; } ts.hasType = hasType; + /* True if the node could have a type node a `.type` */ + /* @internal */ + function couldHaveType(node) { + switch (node.kind) { + case 148 /* Parameter */: + case 150 /* PropertySignature */: + case 151 /* PropertyDeclaration */: + case 152 /* MethodSignature */: + case 153 /* MethodDeclaration */: + case 154 /* Constructor */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + case 157 /* CallSignature */: + case 158 /* ConstructSignature */: + case 159 /* IndexSignature */: + case 160 /* TypePredicate */: + case 162 /* FunctionType */: + case 163 /* ConstructorType */: + case 172 /* ParenthesizedType */: + case 174 /* TypeOperator */: + case 176 /* MappedType */: + case 188 /* TypeAssertionExpression */: + case 190 /* FunctionExpression */: + case 191 /* ArrowFunction */: + case 206 /* AsExpression */: + case 230 /* VariableDeclaration */: + case 232 /* FunctionDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 274 /* JSDocTypeExpression */: + case 277 /* JSDocNullableType */: + case 278 /* JSDocNonNullableType */: + case 279 /* JSDocOptionalType */: + case 280 /* JSDocFunctionType */: + case 281 /* JSDocVariadicType */: + return true; + } + return false; + } + ts.couldHaveType = couldHaveType; /** True if has initializer node attached to it. */ /* @internal */ function hasInitializer(node) { @@ -13349,6 +14187,31 @@ var ts; return node.kind === 161 /* TypeReference */ || node.kind === 205 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; } @@ -13406,6 +14269,13 @@ var ts; } } } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; /** * 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, @@ -13774,6 +14644,7 @@ var ts; case 254 /* JsxSelfClosingElement */: case 255 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); case 261 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); @@ -14099,7 +14970,9 @@ var ts; sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); - processReferenceComments(sourceFile); + // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); ts.Debug.assert(token() === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); @@ -14112,6 +14985,9 @@ var ts; fixupParentReferences(sourceFile); } return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } } function addJSDocComment(node) { var comments = ts.getJSDocCommentRanges(node, sourceFile.text); @@ -14262,9 +15138,7 @@ var ts; return inContext(16384 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), 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. @@ -14276,9 +15150,14 @@ var ts; // node we finish so that it can't be reused incrementally. parseErrorBeforeNextFinishedNode = true; } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); + parseErrorAtPosition(scanner.getTextPos(), length, message); } function getNodePos() { return scanner.getStartPos(); @@ -14560,25 +15439,26 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76 /* ConstKeyword */) { - // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; + switch (token()) { + case 76 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 83 /* EnumKeyword */; + case 84 /* ExportKeyword */: + nextToken(); + if (token() === 79 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); + case 79 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 115 /* StaticKeyword */: + case 125 /* GetKeyword */: + case 136 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === 84 /* ExportKeyword */) { - nextToken(); - if (token() === 79 /* DefaultKeyword */) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - } - if (token() === 79 /* DefaultKeyword */) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === 115 /* StaticKeyword */) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); @@ -15303,9 +16183,20 @@ var ts; nextToken(); return finishNode(node); } - function parseJSDocAllType() { + function parseJSDocAllType(postFixEquals) { var result = createNode(275 /* JSDocAllType */); + if (postFixEquals) { + return createJSDocPostfixType(279 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(278 /* JSDocNonNullableType */); nextToken(); + result.type = parseNonArrayType(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { @@ -15353,14 +16244,21 @@ var ts; parameter.name = parseIdentifierName(); parseExpected(56 /* ColonToken */); } - parameter.type = parseType(); + parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocNodeWithType(kind) { - var result = createNode(kind); - nextToken(); - result.type = parseNonArrayType(); - return finishNode(result); + function parseJSDocType() { + var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + var type = parseType(); + if (dotdotdot) { + var variadic = createNode(281 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 58 /* EqualsToken */) { + return createJSDocPostfixType(279 /* JSDocOptionalType */, type); + } + return type; } function parseTypeQuery() { var node = createNode(164 /* TypeQuery */); @@ -15767,13 +16665,15 @@ var ts; // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 39 /* AsteriskToken */: - return parseJSDocAllType(); + return parseJSDocAllType(/*postfixEquals*/ false); + case 61 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); case 55 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); case 89 /* FunctionKeyword */: return parseJSDocFunctionType(); case 51 /* ExclamationToken */: - return parseJSDocNodeWithType(278 /* JSDocNonNullableType */); + return parseJSDocNonNullableType(); case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -15855,13 +16755,6 @@ var ts; var type = parseNonArrayType(); 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(279 /* JSDocOptionalType */, type); - break; case 51 /* ExclamationToken */: type = createJSDocPostfixType(278 /* JSDocNonNullableType */, type); break; @@ -15923,12 +16816,6 @@ var ts; return parseTypeOperator(operator); case 126 /* InferKeyword */: return parseInferType(); - case 24 /* DotDotDotToken */: { - var result = createNode(281 /* JSDocVariadicType */); - nextToken(); - result.type = parsePostfixTypeOrHigher(); - return finishNode(result); - } } return parsePostfixTypeOrHigher(); } @@ -16542,7 +17429,7 @@ var ts; // 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 newPrecedence = ts.getBinaryOperatorPrecedence(token()); // 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 @@ -16597,50 +17484,7 @@ var ts; if (inDisallowInContext() && token() === 92 /* InKeyword */) { return false; } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54 /* BarBarToken */: - return 1; - case 53 /* AmpersandAmpersandToken */: - return 2; - case 49 /* BarToken */: - return 3; - case 50 /* CaretToken */: - return 4; - case 48 /* AmpersandToken */: - return 5; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 6; - 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 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 8; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 9; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 10; - case 40 /* AsteriskAsteriskToken */: - return 11; - } - // -1 is lower than all other precedences. Returning it will cause binary expression - // parsing to stop. - return -1; + return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { var node = createNode(198 /* BinaryExpression */, left.pos); @@ -16716,7 +17560,7 @@ var ts; if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); return token() === 40 /* AsteriskAsteriskToken */ ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } /** @@ -16733,12 +17577,13 @@ var ts; var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40 /* AsteriskAsteriskToken */) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; if (simpleUnaryExpression.kind === 188 /* 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); + parseErrorAt(pos, end, 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 { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; @@ -16990,7 +17835,7 @@ var ts; 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)); + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } @@ -17034,8 +17879,21 @@ var ts; currentToken = scanner.scanJsxToken(); return finishNode(node); } - function parseJsxChild() { - switch (token()) { + function parseJsxChild(openingTag, token) { + switch (token) { + case 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)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 28 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; case 10 /* JsxText */: case 11 /* JsxTextAllWhiteSpaces */: return parseJsxText(); @@ -17043,8 +17901,9 @@ var ts; return parseJsxExpression(/*inExpressionContext*/ false); case 27 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); } - ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTag) { var list = []; @@ -17052,30 +17911,10 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28 /* LessThanSlashToken */) { - // Closing tag + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; - } - 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 /* ConflictMarkerTrivia */) { - break; - } - var child = parseJsxChild(); - if (child) { - list.push(child); - } + list.push(child); } parsingContext = saveParsingContext; return createNodeArray(list, listPos); @@ -17089,11 +17928,13 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(27 /* LessThanToken */); if (token() === 29 /* GreaterThanToken */) { - parseExpected(29 /* GreaterThanToken */); + // See below for explanation of scanJsxText var node_1 = createNode(258 /* JsxOpeningFragment */, fullStart); + scanJsxText(); return finishNode(node_1); } var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; if (token() === 29 /* GreaterThanToken */) { @@ -17115,6 +17956,7 @@ var ts; node = createNode(254 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; + node.typeArguments = typeArguments; node.attributes = attributes; return finishNode(node); } @@ -17137,7 +17979,9 @@ var ts; } function parseJsxExpression(inExpressionContext) { var node = createNode(263 /* JsxExpression */); - parseExpected(17 /* OpenBraceToken */); + if (!parseExpected(17 /* OpenBraceToken */)) { + return undefined; + } if (token() !== 18 /* CloseBraceToken */) { node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); @@ -17195,8 +18039,7 @@ var ts; var node = createNode(259 /* 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); + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { parseExpected(29 /* GreaterThanToken */); @@ -17332,7 +18175,7 @@ var ts; case 48 /* AmpersandToken */: // foo & case 49 /* BarToken */: // foo | case 18 /* CloseBraceToken */: // foo } - case 1 /* EndOfFileToken */:// 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. @@ -17601,7 +18444,7 @@ var ts; parseExpected(88 /* ForKeyword */); var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); parseExpected(19 /* OpenParenToken */); - var initializer = undefined; + var initializer; if (token() !== 25 /* SemicolonToken */) { if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); @@ -18244,18 +19087,6 @@ var ts; node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } function isClassMemberStart() { var idToken; if (token() === 57 /* AtToken */) { @@ -18270,7 +19101,7 @@ var ts; // 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)) { + if (ts.isClassMemberModifier(idToken)) { return true; } nextToken(); @@ -18302,7 +19133,7 @@ var ts; case 51 /* ExclamationToken */: // Non-null assertion on property name 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. + case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -18617,7 +19448,7 @@ var ts; // import ModuleSpecifier; if (identifier || // import id token() === 39 /* AsteriskToken */ || // import * - token() === 17 /* OpenBraceToken */) { + token() === 17 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); parseExpected(142 /* FromKeyword */); } @@ -18731,8 +19562,7 @@ var ts; node.name = identifierName; } if (kind === 246 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - // Report error identifier expected - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } @@ -18767,87 +19597,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function processReferenceComments(sourceFile) { - 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 /* SingleLineCommentTrivia */) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*= pos_2); pos_2 = child.end; - }); + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); ts.Debug.assert(pos_2 <= node.end); } } @@ -19806,6 +20560,12 @@ var ts; // Adjust the pos or end (or both) of the intersecting element accordingly. adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } @@ -19870,15 +20630,15 @@ var ts; var lastNodeEntirelyBeforePosition; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } } return bestResult; - function getLastChild(node) { + function getLastDescendant(node) { while (true) { - var lastChild = getLastChildWorker(node); + var lastChild = ts.getLastChild(node); if (lastChild) { node = lastChild; } @@ -19887,15 +20647,6 @@ var ts; } } } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } function visit(child) { if (ts.nodeIsMissing(child)) { // Missing nodes are effectively invisible to us. We never even consider them @@ -20060,6 +20811,209 @@ var ts; function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + /*@internal*/ + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var pragmas = []; + // 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 (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + /*@internal*/ + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to + // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { + var _b = _a.arguments, name = _b.name, path = _b.path; + return ({ name: name, path: path }); + }); + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + // TODO: It's probably fine to issue this diagnostic on all instances of the pragma + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + // _last_ of either nocheck or check in a file is the "winner" + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; // Accessed directly + default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; // Missing required argument, don't parse + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; // Split on spaces and match up positionally with definition + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; // Missing required argument, fail to parse it + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } })(ts || (ts = {})); /// /// @@ -20153,7 +21107,6 @@ var ts; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; - ContainerFlags[ContainerFlags["IsInferenceContainer"] = 256] = "IsInferenceContainer"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -20169,8 +21122,8 @@ var ts; var languageVersion; var parent; var container; + var thisParentContainer; // Container one level up var blockScopeContainer; - var inferenceContainer; var lastContainer; var seenThisKeyword; // state used by control flow analysis @@ -20225,8 +21178,8 @@ var ts; languageVersion = undefined; parent = undefined; container = undefined; + thisParentContainer = undefined; blockScopeContainer = undefined; - inferenceContainer = undefined; lastContainer = undefined; seenThisKeyword = false; currentFlow = undefined; @@ -20257,19 +21210,14 @@ var ts; function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = [node]; - } - else { - symbol.declarations.push(node); - } + symbol.declarations = ts.append(symbol.declarations, node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 107455 /* Value */) { + if (symbolFlags & 67216319 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 237 /* ModuleDeclaration */)) { @@ -20299,7 +21247,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } - return ts.getEscapedTextOfIdentifierOrLiteral(name); + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { case 154 /* Constructor */: @@ -20329,7 +21277,7 @@ var ts; case 148 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 280 /* JSDocFunctionType */); + ts.Debug.assert(node.parent.kind === 280 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -20339,7 +21287,7 @@ var ts; } } function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? 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. @@ -20402,7 +21350,7 @@ var ts; symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } else { - if (node.name) { + if (ts.isNamedDeclaration(node)) { node.name.parent = node; } // Report errors every position with duplicate declaration @@ -20440,7 +21388,12 @@ var ts; } } addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { @@ -20472,7 +21425,7 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. var isJSDocTypedefInJSDocNamespace = ts.isJSDocTypedefTag(node) && node.name && node.name.kind === 71 /* Identifier */ && node.name.isInJSDocNamespace; if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67216319 /* 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; @@ -20491,11 +21444,12 @@ var ts; // and block-container. Then after we pop out of processing the children, we restore // these saved values. var saveContainer = container; + var saveThisParentContainer = thisParentContainer; var savedBlockScopeContainer = blockScopeContainer; // 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 + // may contain locals, we eagerly 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). // @@ -20510,6 +21464,9 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 191 /* ArrowFunction */) { + thisParentContainer = container; + } container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { container.locals = ts.createSymbolTable(); @@ -20575,17 +21532,11 @@ var ts; bindChildren(node); node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; } - else if (containerFlags & 256 /* IsInferenceContainer */) { - var saveInferenceContainer = inferenceContainer; - inferenceContainer = node; - node.locals = undefined; - bindChildren(node); - inferenceContainer = saveInferenceContainer; - } else { bindChildren(node); } container = saveContainer; + thisParentContainer = saveThisParentContainer; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { @@ -20605,12 +21556,17 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } - function bindEach(nodes) { + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 232 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 232 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } if (nodes === undefined) { return; } if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); + ts.forEach(nodes, bindFunction); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -20618,7 +21574,7 @@ var ts; var nodeArrayFlags = 0 /* None */; for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { var node = nodes_2[_i]; - bind(node); + bindFunction(node); nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; } nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; @@ -20717,6 +21673,15 @@ var ts; case 291 /* JSDocTypedefTag */: bindJSDocTypedefTag(node); break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 272 /* SourceFile */: + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + case 211 /* Block */: + case 238 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; default: bindEachChild(node); break; @@ -21379,8 +22344,6 @@ var ts; case 235 /* TypeAliasDeclaration */: case 176 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 170 /* ConditionalType */: - return 256 /* IsInferenceContainer */; case 272 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; case 153 /* MethodDeclaration */: @@ -21529,7 +22492,7 @@ var ts; 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)) { + if (ts.isModuleAugmentationExternal(node)) { declareModuleSymbol(node); } else { @@ -21543,10 +22506,8 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } else { @@ -21565,7 +22526,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -21613,8 +22574,8 @@ var ts; continue; } 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)); + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -21653,7 +22614,7 @@ var ts; } } function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* 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. @@ -21699,8 +22660,8 @@ var ts; 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)); + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -21712,8 +22673,8 @@ var ts; 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.idText(identifier))); + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -21876,7 +22837,7 @@ 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); + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, 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'"; @@ -21893,7 +22854,7 @@ var ts; while (parentNode && parentNode.kind !== 291 /* JSDocTypedefTag */) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); break; } // falls through @@ -21920,13 +22881,16 @@ var ts; bindModuleExportsAssignment(node); break; case 3 /* PrototypeProperty */: - bindPrototypePropertyAssignment(node); + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); break; case 4 /* ThisProperty */: bindThisPropertyAssignment(node); break; case 5 /* Property */: - bindStaticPropertyAssignment(node); + bindSpecialPropertyAssignment(node); break; case 0 /* None */: // Nothing to do @@ -21951,7 +22915,7 @@ var ts; seenThisKeyword = true; return; case 160 /* TypePredicate */: - return checkTypePredicate(node); + break; // Binding the children will handle everything case 147 /* TypeParameter */: return bindTypeParameter(node); case 148 /* Parameter */: @@ -21968,7 +22932,7 @@ var ts; case 269 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 271 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); case 157 /* CallSignature */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: @@ -21979,15 +22943,15 @@ var ts; // 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 */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); case 232 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 154 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 155 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); case 156 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); case 162 /* FunctionType */: case 280 /* JSDocFunctionType */: case 163 /* ConstructorType */: @@ -22013,9 +22977,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 234 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); case 235 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); case 236 /* EnumDeclaration */: return bindEnumDeclaration(node); case 237 /* ModuleDeclaration */: @@ -22063,7 +23027,7 @@ var ts; case 291 /* JSDocTypedefTag */: { var fullName = node.fullName; if (!fullName || fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); } break; } @@ -22075,16 +23039,6 @@ var ts; function bindAnonymousTypeWorker(node) { return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71 /* Identifier */) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 173 /* ThisType */) { - seenThisKeyword = true; - } - bind(type); - } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -22159,7 +23113,18 @@ var ts; // 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 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, function (id, original) { + if (!original) { + return undefined; + } + var s = ts.getJSInitializerSymbol(original); + addDeclarationToSymbol(s, id, 1536 /* Module */ | 67108864 /* JSContainer */); + return s; + }); + if (symbol) { + declareSymbol(symbol.exports, symbol, lhs, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + } } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' @@ -22178,14 +23143,24 @@ var ts; } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - switch (container.kind) { + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { case 232 /* FunctionDeclaration */: case 190 /* 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 */); + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = getJSInitializerSymbolFromName(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } break; case 154 /* Constructor */: case 151 /* PropertyDeclaration */: @@ -22194,111 +23169,145 @@ var ts; case 156 /* 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 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; + case 272 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); } } 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 === 183 /* PropertyAccessExpression */) && - node.parent.parent.kind === 272 /* SourceFile */) { - bindStaticPropertyAssignment(node); + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 272 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + 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, /*isPrototypeProperty*/ true); + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); } /** - * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function or class, or not declared. + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; */ function bindStaticPropertyAssignment(node) { - // Look up the function in the local scope, since static assignments should - // follow the function declaration - var leftSideOfAssignment = node.kind === 183 /* PropertyAccessExpression */ ? node : node.left; - var target = leftSideOfAssignment.expression; - 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 === 198 /* BinaryExpression */) { - leftSideOfAssignment.parent = node; - } - if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, 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); - } - } + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function lookupSymbolForName(name) { - return lookupSymbolForNameWorker(container, name); + function getJSInitializerSymbolFromName(name, lookupContainer) { + return ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(name, lookupContainer)); } - 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 === 198 /* BinaryExpression */ || propertyAccess.parent.kind === 214 /* ExpressionStatement */); - var isLegalPosition; - if (propertyAccess.parent.kind === 198 /* BinaryExpression */) { - var initializerKind = propertyAccess.parent.right.kind; - isLegalPosition = (initializerKind === 203 /* ClassExpression */ || initializerKind === 190 /* FunctionExpression */) && - propertyAccess.parent.parent.parent.kind === 272 /* SourceFile */; + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var symbol = getJSInitializerSymbolFromName(name); + var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) + ? propertyAccess.parent.parent.parent.kind === 272 /* SourceFile */ && + !!ts.getJavascriptInitializer(propertyAccess.parent.right, ts.isPrototypeAccess(propertyAccess.parent.left)) + : propertyAccess.parent.parent.kind === 272 /* SourceFile */; + if (!isPrototypeProperty && (!symbol || !(symbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; + var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + forEachIdentifierInEntityName(propertyAccess.expression, function (id, original) { + if (original) { + // Note: add declaration to original symbol, not the special-syntax's symbol, so that namespaces work for type lookup + addDeclarationToSymbol(original, id, flags_1); + return original; + } + else { + return symbol = declareSymbol(symbol ? symbol.exports : container.locals, symbol, id, flags_1, excludeFlags_1); + } + }); } - else { - isLegalPosition = propertyAccess.parent.parent.kind === 272 /* 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 */ | 1024 /* NamespaceModule */))) { + if (!symbol || !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */ | 4096 /* ObjectLiteral */))) { 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())); + (symbol.members || (symbol.members = ts.createSymbolTable())) : + (symbol.exports || (symbol.exports = ts.createSymbolTable())); // Declare the method/property - declareSymbol(symbolTable, targetSymbol, propertyAccess, 4 /* Property */, 0 /* PropertyExcludes */); + var symbolFlags = 4 /* Property */ | (isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); + var symbolExcludes = 0 /* PropertyExcludes */ & ~(isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); + declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(node.expression)); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e)); + } + else { + var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); + ts.Debug.assert(!!s && !!s.exports); + return action(e.name, s.exports.get(e.name.escapedText)); + } } function bindCallExpression(node) { // 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)) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { setCommonJsModuleIndicator(node); } } function bindClassLikeDeclaration(node) { if (node.kind === 233 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; @@ -22331,8 +23340,8 @@ var ts; } function bindEnumDeclaration(node) { return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) - : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); } function bindVariableDeclarationOrBindingElement(node) { if (inStrictMode) { @@ -22352,10 +23361,10 @@ var ts; // 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 */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); } } } @@ -22369,7 +23378,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -22387,10 +23396,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -22417,20 +23426,31 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + function getInferTypeContainer(node) { + while (node) { + var parent_2 = node.parent; + if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) { + return parent_2; + } + node = parent_2; + } + return undefined; + } function bindTypeParameter(node) { if (node.parent.kind === 171 /* InferType */) { - if (inferenceContainer) { - if (!inferenceContainer.locals) { - inferenceContainer.locals = ts.createSymbolTable(); + var container_1 = getInferTypeContainer(node.parent); + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); } - declareSymbol(inferenceContainer.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } } // reachability checks @@ -22490,7 +23510,7 @@ var ts; } function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { return isExportsOrModuleExportsOrAlias(sourceFile, node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); } function lookupSymbolForNameWorker(container, name) { var local = container.locals && container.locals.get(name); @@ -23757,8 +24777,11 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createMap(); - var moduleNameToDirectoryMap = ts.createMap(); + return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + /*@internal*/ + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); @@ -23842,7 +24865,7 @@ var ts; } } } - ts.createModuleResolutionCache = createModuleResolutionCache; + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -23853,7 +24876,7 @@ var ts; var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } } else { @@ -24043,7 +25066,7 @@ var ts; 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; + var matchedPattern; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); @@ -24319,7 +25342,7 @@ var ts; var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = readJson(packageJsonPath, host); - if (subModuleName === "") { + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); if (typeof path === "string") { subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); @@ -24415,7 +25438,7 @@ var ts; } else { var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { + if (rest !== "") { // If "rest" is empty, we just did this search above. 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; @@ -24445,7 +25468,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -24492,6 +25515,7 @@ var ts; return "@types/" + getMangledNameForScopedPackage(packageName); } ts.getTypesPackageName = getTypesPackageName; + /* @internal */ function getMangledNameForScopedPackage(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); @@ -24501,6 +25525,7 @@ var ts; } return packageName; } + ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); @@ -24517,12 +25542,13 @@ var ts; typesPackageName; } ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { var result = cache && cache.get(containingDirectory); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } + failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } @@ -24543,7 +25569,7 @@ var ts; if (!ts.isExternalModuleNameRelative(moduleName)) { // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -24828,7 +25854,7 @@ var ts; node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (node) { node = ts.getParseTreeNode(node, ts.isParameter); return node ? isOptionalParameter(node) : false; @@ -24867,7 +25893,7 @@ var ts; resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, - getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, @@ -24879,13 +25905,13 @@ var ts; node = ts.getParseTreeNode(node, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, + getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; }, }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); - var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -24954,6 +25980,7 @@ var ts; var anyArrayType; var autoArrayType; var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; // 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 @@ -24970,11 +25997,9 @@ var ts; var deferredGlobalAsyncIteratorType; var deferredGlobalAsyncIterableIteratorType; var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; var deferredNodes; var deferredUnusedIdentifierNodes; + var seenDeferredUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -24999,6 +26024,19 @@ var ts; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); + // Suggestion diagnostics must have a file. Keyed by source file name. + var suggestionDiagnostics = ts.createMultiMap(); + function addSuggestionDiagnostic(diag) { + suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + function addErrorOrSuggestionDiagnostic(isError, diag) { + if (isError) { + diagnostics.add(diag); + } + else { + addSuggestionDiagnostic(diag); + } + } var TypeFacts; (function (TypeFacts) { TypeFacts[TypeFacts["None"] = 0] = "None"; @@ -25024,8 +26062,7 @@ var ts; 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["All"] = 4194303] = "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. @@ -25055,10 +26092,10 @@ var ts; 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["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); @@ -25090,12 +26127,6 @@ var ts; var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - /** Things we lazy load from the JSX namespace */ - var jsxTypes = ts.createUnderscoreEscapedMap(); var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var definitelyAssignableRelation = ts.createMap(); @@ -25151,6 +26182,7 @@ var ts; TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType"; TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject"; TypeIncludes[TypeIncludes["Union"] = 2048] = "Union"; + TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard"; })(TypeIncludes || (TypeIncludes = {})); var MembersOrExportsResolutionKind; (function (MembersOrExportsResolutionKind) { @@ -25298,7 +26330,23 @@ var ts; }; } } - function getJsxNamespace() { + function getJsxNamespace(location) { + if (location) { + var file = ts.getSourceFileOfNode(location); + if (file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + var jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + } if (!_jsxNamespace) { _jsxNamespace = "React"; if (compilerOptions.jsxFactory) { @@ -25337,35 +26385,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 107455 /* BlockScopedVariableExcludes */; + result |= 67216319 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 107454 /* FunctionScopedVariableExcludes */; + result |= 67216318 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; + result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 106927 /* FunctionExcludes */; + result |= 67215791 /* FunctionExcludes */; if (flags & 32 /* Class */) - result |= 899519 /* ClassExcludes */; + result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 792968 /* InterfaceExcludes */; + result |= 67901832 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) - result |= 899327 /* RegularEnumExcludes */; + result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) - result |= 899967 /* ConstEnumExcludes */; + result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 106639 /* ValueModuleExcludes */; + result |= 67215503 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 99263 /* MethodExcludes */; + result |= 67208127 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 41919 /* GetAccessorExcludes */; + result |= 67150783 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 74687 /* SetAccessorExcludes */; + result |= 67183551 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 530920 /* TypeParameterExcludes */; + result |= 67639784 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 793064 /* TypeAliasExcludes */; + result |= 67901928 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -25394,7 +26442,7 @@ var ts; } function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - source.flags & 67108864 /* JSContainer */ || target.flags & 67108864 /* JSContainer */) { + (source.flags | 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 @@ -25418,6 +26466,13 @@ var ts; target.exports = ts.createSymbolTable(); mergeSymbolTable(target.exports, source.exports); } + if ((source.flags | target.flags) & 67108864 /* JSContainer */) { + var sourceInitializer = ts.getJSInitializerSymbol(source); + var targetInitializer = ts.getJSInitializerSymbol(target); + if (sourceInitializer !== source || targetInitializer !== target) { + mergeSymbol(targetInitializer, sourceInitializer); + } + } recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { @@ -25430,10 +26485,12 @@ var ts; ? 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)); + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + error(errorNode, message_2, symbolToString(source)); }); } } @@ -25554,8 +26611,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -25691,7 +26748,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -25700,7 +26757,7 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + if (meaning & 67216319 /* 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 @@ -25708,7 +26765,7 @@ var ts; useResult = lastLocation.kind === 148 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 148 /* Parameter */); + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } else if (location.kind === 170 /* ConditionalType */) { @@ -25780,7 +26837,7 @@ var ts; 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 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -25790,7 +26847,7 @@ var ts; case 233 /* ClassDeclaration */: case 203 /* ClassExpression */: case 234 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064 /* Type */)) { + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -25817,7 +26874,7 @@ var ts; // 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 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -25837,7 +26894,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 234 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -25959,14 +27016,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // 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 */) { + if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 240 /* 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)); @@ -25982,7 +27039,7 @@ var ts; case 234 /* InterfaceDeclaration */: case 236 /* EnumDeclaration */: case 235 /* TypeAliasDeclaration */: - case 237 /* ModuleDeclaration */:// For `namespace N { N; }` + case 237 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -26059,8 +27116,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~1920 /* Namespace */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + if (meaning === namespaceMeaning) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -26079,12 +27137,12 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67216319 /* 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 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* 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; @@ -26093,15 +27151,15 @@ var ts; return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - 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 (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* 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 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* 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; @@ -26162,14 +27220,18 @@ var ts; ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */)); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { 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, "default" /* Default */, dontResolveAlias)) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); + if (defaultExportSymbol && defaultExportSymbol.valueDeclaration && isSyntacticDefault(defaultExportSymbol.valueDeclaration)) { 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 @@ -26206,7 +27268,7 @@ var ts; if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && hasSyntheticDefault) { + else if (hasSyntheticDefault) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -26239,7 +27301,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -26294,7 +27356,15 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + var moduleName = getFullyQualifiedName(moduleSymbol); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } return symbol; } @@ -26312,7 +27382,7 @@ var ts; resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(node.expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { @@ -26325,7 +27395,7 @@ var ts; case 246 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 250 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 247 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 240 /* NamespaceExportDeclaration */: @@ -26336,7 +27406,7 @@ var ts; * 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 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } return symbol && (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */; } function resolveSymbol(symbol, dontResolveAlias) { @@ -26368,7 +27438,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -26416,7 +27486,7 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 241 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -26429,39 +27499,43 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === namespaceMeaning ? 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 === 145 /* QualifiedName */ || name.kind === 183 /* PropertyAccessExpression */) { - var left = void 0; - if (name.kind === 145 /* QualifiedName */) { - left = name.left; - } - else if (name.kind === 183 /* PropertyAccessExpression */) { - 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 left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); + var namespace = resolveEntityName(left, namespaceMeaning, 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); + if (ts.isInJavaScriptFile(name)) { + var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + if (initializer) { + namespace = getSymbolOfNode(initializer); + } + if (namespace.valueDeclaration && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { @@ -26505,6 +27579,9 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); } @@ -26526,10 +27603,8 @@ var ts; 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.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + else { + addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); } // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. return undefined; @@ -26552,6 +27627,12 @@ var ts; } return undefined; } + function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) { + var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; + var errorInfo = packageId && ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)); + return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } // 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) { @@ -26727,7 +27808,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); + return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -26827,13 +27908,21 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // 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 */; + return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { + if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { return undefined; } - var visitedSymbolTables = []; + var id = "" + getSymbolId(symbol); + var visitedSymbolTables; + if (visitedSymbolTablesMap.has(id)) { + visitedSymbolTables = visitedSymbolTablesMap.get(id); + } + else { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) @@ -26850,7 +27939,7 @@ var ts; // 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); + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap); } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && @@ -26868,7 +27957,8 @@ var ts; // Check if symbol is any of the alias return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 /* Alias */ - && symbolFromSymbolTable.escapedName !== "export=" + && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ + && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.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))) { @@ -26931,11 +28021,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } /** @@ -27044,7 +28134,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 146 /* ComputedPropertyName */) { // Typeof value - meaning = 107455 /* Value */ | 1048576 /* ExportValue */; + meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 145 /* QualifiedName */ || entityName.kind === 183 /* PropertyAccessExpression */ || entityName.parent.kind === 241 /* ImportEqualsDeclaration */) { @@ -27054,7 +28144,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 793064 /* Type */; + meaning = 67901928 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -27105,6 +28195,7 @@ var ts; } } function typeToString(type, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; } if (writer === void 0) { writer = ts.createTextWriter(""); } var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); @@ -27187,7 +28278,8 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined + symbolStack: undefined, + inferTypeParameters: undefined }; } function typeToTypeNodeHelper(type, context) { @@ -27211,12 +28303,12 @@ var ts; } if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67901928 /* 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 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { @@ -27230,6 +28322,9 @@ var ts; } if (type.flags & 1024 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeQueryNode(symbolToName(type.symbol, context, 67216319 /* Value */, /*expectsIdentifier*/ false)); + } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } @@ -27271,7 +28366,10 @@ var ts; return typeReferenceToTypeNode(type); } if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - var name = type.symbol ? symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); + if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + } + var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -27311,13 +28409,16 @@ var ts; } if (type.flags & 2097152 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); + var saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); - var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); - var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); + context.inferTypeParameters = saveInferTypeParameters; + var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); + var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 4194304 /* Substitution */) { - return typeToTypeNodeHelper(type.typeParameter, context); + return typeToTypeNodeHelper(type.typeVariable, context); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { @@ -27336,14 +28437,14 @@ var ts; if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 203 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); + return createTypeQueryNodeFromSymbol(symbol, 67216319 /* 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) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var entityName = symbolToName(typeAlias, context, 67901928 /* Type */, /*expectsIdentifier*/ false); return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { @@ -27420,7 +28521,7 @@ var ts; } function symbolToTypeReferenceName(symbol) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display - var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); return entityName; } function typeReferenceToTypeNode(type) { @@ -27448,7 +28549,8 @@ var ts; } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 203 /* ClassExpression */) { + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } else { @@ -27482,7 +28584,7 @@ var ts; } } } - var entityName = undefined; + var entityName = void 0; var nameIdentifier = symbolToTypeReferenceName(type.symbol); if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); @@ -27557,12 +28659,12 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } } - var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { @@ -27659,7 +28761,7 @@ var ts; if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); + var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); @@ -27893,9 +28995,6 @@ var ts; node.parent.kind === 238 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } - function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; - } function isDefaultBindingContext(location) { return location.kind === 272 /* SourceFile */ || ts.isAmbientModule(location); } @@ -27936,8 +29035,8 @@ var ts; return "(Anonymous function)"; } } - if (symbol.syntheticLiteralTypeOrigin) { - var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (symbol.nameType && symbol.nameType.flags & 32 /* StringLiteral */) { + var stringValue = symbol.nameType.value; if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; } @@ -28034,10 +29133,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 247 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 250 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -28058,7 +29157,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -28244,8 +29343,7 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var propType = getTypeOfPropertyOfType(parentType, text); - var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); + var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -28328,7 +29426,8 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); // Use type from type annotation if one is present var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); if (declaredType) { @@ -28395,12 +29494,19 @@ var ts; return undefined; } function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments + var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); + if (specialDeclaration) { + return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + } var types = []; + var constructorTypes; var definedInConstructor = false; var definedInMethod = false; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; + var declarationInConstructor = false; var expression = declaration.kind === 198 /* BinaryExpression */ ? declaration : declaration.kind === 183 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 198 /* BinaryExpression */) : undefined; @@ -28408,7 +29514,13 @@ var ts; return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 154 /* Constructor */) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + declarationInConstructor = thisContainer.kind === 154 /* Constructor */ || + thisContainer.kind === 232 /* FunctionDeclaration */ || + (thisContainer.kind === 190 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + if (declarationInConstructor) { definedInConstructor = true; } else { @@ -28430,11 +29542,34 @@ var ts; } 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_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); + var anyedType = type_2; + if (isEmptyArrayLiteralType(type_2)) { + anyedType = anyArrayType; + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + } + types.push(anyedType); + if (declarationInConstructor) { + (constructorTypes || (constructorTypes = [])).push(anyedType); + } } } - var type = jsDocType || getUnionType(types, 2 /* Subtype */); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + var type = jsDocType; + if (!type) { + // use only the constructor types unless only null | undefined (including widening variants) were assigned there + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~12288 /* Nullable */); }) === neverType) { + if (noImplicitAny) { + reportImplicitAnyError(symbol.valueDeclaration, anyType); + } + return anyType; + } + return widened; } // 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 @@ -28455,12 +29590,12 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var hasComputedProperties = false; + var objectFlags = 128 /* ObjectLiteral */; 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; + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; return; } if (e.dotDotDotToken) { @@ -28475,12 +29610,11 @@ var ts; members.set(symbol.escapedName, symbol); }); var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 33554432 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; } - if (hasComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } return result; } // Return the type implied by an array binding pattern @@ -28677,6 +29811,7 @@ var ts; if (getter && getter.body) { type = getReturnTypeFromBody(getter); } + // Otherwise, fall back to 'any'. else { if (noImplicitAny) { if (setter) { @@ -28741,7 +29876,7 @@ var ts; // 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 */ + links.type = targetSymbol.flags & 67216319 /* Value */ ? getTypeOfSymbol(targetSymbol) : unknownType; } @@ -29121,7 +30256,7 @@ 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 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -29485,7 +30620,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 107455 /* Value */) { + if (symbolFlags & 67216319 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; @@ -29548,8 +30683,18 @@ var ts; error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } + var symbolLinks_1 = getSymbolLinks(lateSymbol); + if (!symbolLinks_1.nameType) { + // Retain link to name type so that it can be reused later + symbolLinks_1.nameType = type; + } addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); - lateSymbol.parent = parent; + if (lateSymbol.parent) { + ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + lateSymbol.parent = parent; + } return links.resolvedSymbol = lateSymbol; } } @@ -29751,7 +30896,7 @@ var ts; } return [signature]; } - var result = undefined; + var result; for (var i = 0; i < signatureLists.length; i++) { // 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); @@ -29768,7 +30913,7 @@ var ts; // 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; + var result; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; @@ -29899,7 +31044,7 @@ var ts; else { // Combinations of function, class, enum and module var members = emptySymbols; - var stringIndexInfo = undefined; + var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); } @@ -29998,13 +31143,12 @@ var ts; // 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 templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { - var propName = ts.escapeLeadingUnderscores(t.value); + var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); @@ -30021,7 +31165,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } - prop.syntheticLiteralTypeOrigin = t; + prop.nameType = t; members.set(propName, prop); } else if (t.flags & (1 /* Any */ | 2 /* String */)) { @@ -30206,7 +31350,7 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getDefaultConstraintOfConditionalType(type) { - return getUnionType([type.trueType, type.falseType]); + return getUnionType([getInferredTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); } function getConstraintOfDistributiveConditionalType(type) { // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained @@ -30214,13 +31358,11 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (isDistributiveConditionalType(type)) { + if (type.root.isDistributive) { var constraint = getConstraintOfType(type.checkType); if (constraint) { - var target = type.target || type; - var mapper = createTypeMapper([target.checkType], [constraint]); - var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper; - return instantiateType(target, combinedMapper); + var mapper = createTypeMapper([type.root.checkType], [constraint]); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); } } return undefined; @@ -30228,17 +31370,27 @@ var ts; function getConstraintOfConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } - function getBaseConstraintOfType(type) { + function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { if (type.flags & (7372800 /* InstantiableNonPrimitive */ | 393216 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 524288 /* Index */) { + } + function getBaseConstraintOfType(type) { + var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); + if (!constraint && type.flags & 524288 /* Index */) { return stringType; } - return undefined; + return constraint; + } + /** + * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` + * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable) + */ + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; } function hasNonCircularBaseConstraint(type) { return getResolvedBaseConstraint(type) !== circularConstraintType; @@ -30278,8 +31430,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -30302,7 +31454,8 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 2097152 /* Conditional */) { - return getBaseConstraint(getConstraintOfConditionalType(t)); + var constraint = getConstraintOfConditionalType(t); + return constraint && getBaseConstraint(constraint); } if (t.flags & 4194304 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -30413,7 +31566,7 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; + var commonType; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; if (prop.declarations) { @@ -30553,23 +31706,13 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 279 /* JSDocOptionalType */) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 279 /* JSDocOptionalType */; - } - } - } - } + return ts.isInJavaScriptFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 279 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 279 /* JSDocOptionalType */; + })); } function tryFindAmbientModule(moduleName, withAugmentations) { if (ts.isExternalModuleNameRelative(moduleName)) { @@ -30670,11 +31813,15 @@ var ts; var parameters = []; var hasLiteralTypes = false; var minArgumentCount = 0; - var thisParameter = undefined; + var thisParameter = void 0; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJavaScriptFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(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. @@ -30683,7 +31830,7 @@ var ts; var paramSymbol = param.symbol; // 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); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -30699,8 +31846,8 @@ var ts; // 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) || - isUntypedSignatureInJSFile; + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -30725,18 +31872,21 @@ var ts; } return links.resolvedSignature; } + /** + * A JS function gets a synthetic rest parameter if it references `arguments` AND: + * 1. It has no parameters but at least one `@param` with a type that starts with `...` + * OR + * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` + */ function maybeAddJsSyntheticRestParameter(declaration, parameters) { - // JS functions get a free rest parameter if: - // a) The last parameter has `...` preceding its type - // b) It references `arguments` somewhere + if (!containsArgumentsReference(declaration)) { + return false; + } var lastParam = ts.lastOrUndefined(declaration.parameters); - var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag); var lastParamVariadicType = 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; @@ -30802,32 +31952,18 @@ var ts; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; - switch (node.kind) { - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 280 /* 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) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); + if (!ts.isFunctionLike(node)) + continue; + // 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) { + continue; + } } + result.push(getSignatureFromDeclaration(node)); } return result; } @@ -30923,7 +32059,10 @@ var ts; return instantiation; } function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(signature.typeParameters, typeArguments); } function getErasedSignature(signature) { return signature.typeParameters ? @@ -31197,6 +32336,7 @@ var ts; if (ts.isEntityNameExpression(expr)) { return expr; } + // fall through; } return undefined; } @@ -31219,24 +32359,23 @@ var ts; var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 32768 /* TypeParameter */ ? getConstrainedTypeParameter(res, node) : res : + res.flags & 32768 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : unknownType; } - if (!(symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67216319 /* 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 assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + var referenceType = valueType.symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType || assignedType) { + return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -31252,24 +32391,33 @@ var ts; return getInferredClassType(symbol); } } - function getSubstitutionType(typeParameter, substitute) { + function getSubstitutionType(typeVariable, substitute) { var result = createType(4194304 /* Substitution */); - result.typeParameter = typeParameter; + result.typeVariable = typeVariable; result.substitute = substitute; return result; } - function getConstrainedTypeParameter(typeParameter, node) { + function isUnaryTupleTypeNode(node) { + return node.kind === 167 /* TupleType */ && node.elementTypes.length === 1; + } + function getImpliedConstraint(typeVariable, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + undefined; + } + function getConstrainedTypeVariable(typeVariable, node) { var constraints; while (ts.isPartOfTypeNode(node)) { var parent = node.parent; if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) { - if (getTypeFromTypeNode(parent.checkType) === typeParameter) { - constraints = ts.append(constraints, getTypeFromTypeNode(parent.extendsType)); + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + if (constraint) { + constraints = ts.append(constraints, constraint); } } node = parent; } - return constraints ? getSubstitutionType(typeParameter, getIntersectionType(ts.append(constraints, typeParameter))) : typeParameter; + return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { return node.flags & 1048576 /* JSDoc */ && node.kind === 161 /* TypeReference */; @@ -31337,10 +32485,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 793064 /* Type */; + var meaning = 67901928 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 107455 /* Value */; + meaning |= 67216319 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -31395,10 +32543,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -31449,18 +32597,9 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67901928 /* 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 /* 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. */ @@ -31572,6 +32711,8 @@ var ts; } else if (flags & 1 /* Any */) { includes |= 1 /* Any */; + if (type === wildcardType) + includes |= 4096 /* Wildcard */; } else if (!strictNullChecks && flags & 12288 /* Nullable */) { if (flags & 4096 /* Undefined */) @@ -31692,7 +32833,7 @@ var ts; var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); if (includes & 1 /* Any */) { - return anyType; + return includes & 4096 /* Wildcard */ ? wildcardType : anyType; } switch (unionReduction) { case 1 /* Literal */: @@ -31785,6 +32926,8 @@ var ts; } else if (flags & 1 /* Any */) { includes |= 1 /* Any */; + if (type === wildcardType) + includes |= 4096 /* Wildcard */; } else if (flags & 16384 /* Never */) { includes |= 8 /* Never */; @@ -31835,7 +32978,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return anyType; + return includes & 4096 /* Wildcard */ ? wildcardType : anyType; } if (includes & 1024 /* EmptyObject */ && !(includes & 512 /* ObjectType */)) { typeSet.push(emptyObjectType); @@ -31877,19 +33020,29 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? - neverType : - getLiteralType(ts.symbolName(prop)); + var links = getSymbolLinks(getLateBoundSymbol(prop)); + if (!links.nameType) { + if (links.target && links.target !== unknownSymbol && links.target !== resolvingSymbol && links.target.escapedName === prop.escapedName) { + links.nameType = getLiteralTypeFromPropertyName(links.target); + } + else { + links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? + neverType : + getLiteralType(ts.symbolName(prop)); + } + } + return links.nameType; } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) : - ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : - type === wildcardType ? wildcardType : - type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : - getLiteralTypeFromPropertyNames(type); + return type.flags & 262144 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) : + maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : + getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); @@ -31952,6 +33105,9 @@ var ts; } return indexInfo.type; } + if (indexType.flags & 16384 /* Never */) { + return neverType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (getIndexTypeOfType(objectType, 1 /* Number */)) { @@ -32050,10 +33206,13 @@ var ts; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper; + var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } // 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 @@ -32092,7 +33251,13 @@ var ts; function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + var objectType = getTypeFromTypeNode(node.objectType); + var indexType = getTypeFromTypeNode(node.indexType); + var resolved = getIndexedAccessType(objectType, indexType, node); + links.resolvedType = resolved.flags & 1048576 /* IndexedAccess */ && + resolved.objectType === objectType && + resolved.indexType === indexType ? + getConstrainedTypeVariable(resolved, node) : resolved; } return links.resolvedType; } @@ -32110,76 +33275,74 @@ var ts; } return links.resolvedType; } - function getActualTypeParameter(type) { - return type.flags & 4194304 /* Substitution */ ? type.typeParameter : type; + function getActualTypeVariable(type) { + return type.flags & 4194304 /* Substitution */ ? type.typeVariable : type; } - function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) { - var type = createType(2097152 /* Conditional */); - type.checkType = checkType; - type.extendsType = extendsType; - type.trueType = trueType; - type.falseType = falseType; - type.inferTypeParameters = inferTypeParameters; - type.target = target; - type.mapper = mapper; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - return type; - } - function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) { - // Instantiate extends type without instantiating any 'infer T' type parameters - var extendsType = instantiateType(baseExtendsType, mapper); - // Return falseType for a definitely false extends check. We check an instantations of the two - // types with type parameters mapped to the wildcard type, the most permissive instantiations - // possible (the wildcard type is assignable to and from all types). If those are not related, - // then no instatiations will be and we can just return the false branch type. - if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) { - return instantiateType(baseFalseType, mapper); + function getConditionalType(root, mapper) { + var checkType = instantiateType(root.checkType, mapper); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; } - // The check could be true for some instantiation + // If this is a distributive conditional type and the check type is generic we need to defer + // resolution of the conditional type such that a later instantiation will properly distribute + // over union types. + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */); var combinedMapper; - if (inferTypeParameters) { - var inferences = ts.map(inferTypeParameters, createInferenceInfo); - // We don't want inferences from constraints as they may cause us to eagerly resolve the - // conditional type instead of deferring resolution. Also, we always want strict function - // types rules (i.e. proper contravariance) for inferences. - inferTypes(inferences, checkType, extendsType, 8 /* NoConstraints */ | 16 /* AlwaysStrict */); - // We infer 'never' when there are no candidates for a type parameter - var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; }); - var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes); - combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + } + combinedMapper = combineTypeMappers(mapper, context); } - // Return union of trueType and falseType for any and never since they match anything - if (checkType.flags & 1 /* Any */ || (checkType.flags & 16384 /* Never */ && !(extendsType.flags & 16384 /* Never */))) { - return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]); - } - // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType; - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type - // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { - return instantiateType(baseTrueType, combinedMapper || mapper); + if (!isDeferred) { + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + } + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // Return falseType for a definitely false extends check. We check an instantations of the two + // types with type parameters mapped to the wildcard type, the most permissive instantiations + // possible (the wildcard type is assignable to and from all types). If those are not related, + // then no instatiations will be and we can just return the false branch type. + if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + return instantiateType(root.falseType, mapper); + } + // Return trueType for a definitely true extends check. The definitely assignable relation excludes + // type variable constraints from consideration. Without the definitely assignable relation, the type + // type Foo = T extends { x: string } ? string : number + // would immediately resolve to 'string' instead of being deferred. + if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + return instantiateType(root.trueType, combinedMapper || mapper); + } } // Return a deferred type for a check that is neither definitely true nor definitely false - var erasedCheckType = getActualTypeParameter(checkType); - var trueType = instantiateType(baseTrueType, mapper); - var falseType = instantiateType(baseFalseType, mapper); - // We compute the cache key from the ids of the four constituent types, plus an indicator of whether the - // type is distributive (i.e. whether the original declaration has a type parameter as the check type). - var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 /* TypeParameter */ ? 1 : 0; - var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive; - var cached = conditionalTypes.get(id); - if (cached) { - return cached; - } - var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper)); - conditionalTypes.set(id, result); + var erasedCheckType = getActualTypeVariable(checkType); + var result = createType(2097152 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); return result; } - function isDistributiveConditionalType(type) { - return !!((type.target || type).checkType.flags & 32768 /* TypeParameter */); + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + } + function getInferredTrueTypeFromConditionalType(type) { + return type.combinedMapper ? + type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper)) : + getTrueTypeFromConditionalType(type); } function getInferTypeParameters(node) { var result; @@ -32195,7 +33358,28 @@ var ts; function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), /*target*/ undefined, /*mapper*/ undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var checkType = getTypeFromTypeNode(node.checkType); + var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); }); + var root = { + node: node, + checkType: checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + trueType: getTypeFromTypeNode(node.trueType), + falseType: getTypeFromTypeNode(node.falseType), + isDistributive: !!(checkType.flags & 32768 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters: outerTypeParameters, + instantiations: undefined, + aliasSymbol: getAliasSymbolForTypeNode(node), + aliasTypeArguments: aliasTypeArguments + }; + links.resolvedType = getConditionalType(root, /*mapper*/ undefined); + if (outerTypeParameters) { + root.instantiations = ts.createMap(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } } return links.resolvedType; } @@ -32451,9 +33635,10 @@ var ts; return getTypeFromIntersectionTypeNode(node); case 277 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); + case 279 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); case 172 /* ParenthesizedType */: case 278 /* JSDocNonNullableType */: - case 279 /* JSDocOptionalType */: case 274 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); case 281 /* JSDocVariadicType */: @@ -32540,14 +33725,18 @@ var ts; return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { - return !!mapper.signature; + return !!mapper.typeParameters; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { + if (!mapper1) + return mapper2; + if (!mapper2) + return mapper1; return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { @@ -32673,8 +33862,8 @@ var ts; // between the node and the type parameter declaration, if the node contains actual references to the // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_1 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 211 /* Block */ ? "quit" : n === container_1; })) { + var container_2 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 211 /* Block */ ? "quit" : n === container_2; })) { return ts.forEachChild(node, containsReference); } } @@ -32729,22 +33918,35 @@ var ts; return result; } function getConditionalTypeInstantiation(type, mapper) { - var target = type.target || type; - var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + var root = type.root; + if (root.outerTypeParameters) { + // We are instantiating a conditional 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 typeArguments = ts.map(root.outerTypeParameters, mapper); + var id = getTypeListId(typeArguments); + var result = root.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + result = instantiateConditionalType(root, newMapper); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateConditionalType(root, mapper) { // Check if we have a conditional type where the check type is a naked type parameter. If so, // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). - if (isDistributiveConditionalType(target)) { - var checkType_1 = target.checkType; - var instantiatedType = combinedMapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072 /* Union */) { - return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); }); + if (root.isDistributive) { + var checkType_1 = root.checkType; + var instantiatedType = mapper(checkType_1); + if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 /* Union */ | 16384 /* Never */)) { + return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } - return instantiateConditionalType(target, combinedMapper); - } - function instantiateConditionalType(type, mapper) { - return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments); + return getConditionalType(root, mapper); } function instantiateType(type, mapper) { if (type && mapper && mapper !== identityMapper) { @@ -32785,10 +33987,10 @@ var ts; return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } if (type.flags & 2097152 /* Conditional */) { - return getConditionalTypeInstantiation(type, mapper); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } if (type.flags & 4194304 /* Substitution */) { - return mapper(type.typeParameter); + return instantiateType(type.typeVariable, mapper); } } return type; @@ -32855,7 +34057,8 @@ var ts; return node.body.kind === 211 /* Block */ ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { if (type.flags & 65536 /* Object */) { @@ -33329,10 +34532,10 @@ var ts; target = target.regularType; } if (source.flags & 4194304 /* Substitution */) { - source = relation === definitelyAssignableRelation ? source.typeParameter : source.substitute; + source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } if (target.flags & 4194304 /* Substitution */) { - target = target.typeParameter; + target = target.typeVariable; } // 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) @@ -33458,11 +34661,11 @@ var ts; } } if (flags & 2097152 /* Conditional */) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { - if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { return result; } } @@ -33850,20 +35053,14 @@ var ts; } } else if (source.flags & 2097152 /* Conditional */) { - if (relation !== definitelyAssignableRelation) { - var constraint = getConstraintOfDistributiveConditionalType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } if (target.flags & 2097152 /* Conditional */) { - if (isTypeIdenticalTo(source.checkType, target.checkType) && - isTypeIdenticalTo(source.extendsType, target.extendsType)) { - if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { - result &= isRelatedTo(source.falseType, target.falseType, reportErrors); + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { + if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -33871,9 +35068,21 @@ var ts; } } } - else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else if (relation !== definitelyAssignableRelation) { + var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + if (distributiveConstraint) { + if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } } else { @@ -34219,6 +35428,11 @@ var ts; if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { continue; } + // Skip over symbol-named members + var nameType = getLiteralTypeFromPropertyName(prop); + if (nameType !== undefined && !(isRelatedTo(nameType, stringType) || isRelatedTo(nameType, numberType))) { + continue; + } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -34738,8 +35952,18 @@ var ts; ts.Debug.assert(strictNullChecks); return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]); } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; + } + // Use NonNullable global type alias if available to improve quick info/declaration emit + if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { + return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); + } + return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior + } function getNonNullableType(type) { - return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; + return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; } /** * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module @@ -34841,6 +36065,10 @@ var ts; } var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name); result.type = undefinedType; + var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name)); + if (associatedKeyType.flags & 32 /* StringLiteral */) { + result.nameType = associatedKeyType; + } undefinedProperties.set(name, result); return result; } @@ -34943,6 +36171,7 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 198 /* BinaryExpression */: case 151 /* PropertyDeclaration */: case 150 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; @@ -35004,9 +36233,10 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(signature, flags, compareTypes, baseInferences) { - var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { + var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); var context = mapper; + context.typeParameters = typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -35125,7 +36355,7 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return getTypeFromInference(inference) || emptyObjectType; + return getTypeFromInference(inference); } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -35140,21 +36370,38 @@ var ts; } return undefined; } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with different arity are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && getTypeReferenceArity(source) !== getTypeReferenceArity(target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : - undefined; + emptyObjectType; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; var contravariant = false; + var propagationType; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { return; } + if (source === wildcardType) { + // We are inferring from an 'any' type. We want to infer this type for every type parameter + // referenced in the target type, so we record it as the propagation type and infer from the + // target to itself. Then, as we find candidates we substitute the propagation type. + var savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + 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. @@ -35224,14 +36471,15 @@ var ts; inference.priority = priority; } if (priority === inference.priority) { + var candidate = propagationType || source; if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, source); + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, source); + inference.candidates = ts.append(inference.candidates, candidate); } } - if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -35261,7 +36509,10 @@ var ts; else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; + var savePriority = priority; + priority |= 16 /* LiteralKeyof */; inferFromTypes(empty, target.type); + priority = savePriority; contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { @@ -35271,8 +36522,8 @@ var ts; else if (source.flags & 2097152 /* Conditional */ && target.flags & 2097152 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(source.trueType, target.trueType); - inferFromTypes(source.falseType, target.falseType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else if (target.flags & 393216 /* UnionOrIntersection */) { var targetTypes = target.types; @@ -35308,7 +36559,7 @@ var ts; } } else { - if (!(priority && 8 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) { + if (!(priority & 32 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) { source = getApparentType(source); } if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) { @@ -35339,7 +36590,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 16 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -35378,7 +36629,7 @@ var ts; var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 2 /* MappedType */; + priority |= 2 /* HomomorphicMappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -35388,14 +36639,16 @@ var ts; 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. + var savePriority = priority; + priority |= 4 /* MappedTypeConstraint */; inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); return; } } - // 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)) { + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0 /* Call */); inferFromSignatures(source, target, 1 /* Construct */); @@ -35493,62 +36746,73 @@ var ts; } return candidates; } + function getContravariantInference(inference) { + return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, context, signature) { + // 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 occurrences 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 widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + 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 = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } 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(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 = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? - getUnionType(baseCandidates, 2 /* Subtype */) : - getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unwidenedType); - // If we have inferred 'never' but have contravariant candidates. To get a more specific type we - // infer from the contravariant candidates instead. - if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { - inferredType = getCommonSubtype(inference.contraCandidates); + var signature = context.signature; + if (signature) { + if (inference.candidates) { + inferredType = getCovariantInference(inference, context, signature); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getContravariantInference(inference); + } } - } - else if (inference.contraCandidates) { - // We only have contravariant inferences, infer the best common subtype of those - inferredType = getCommonSubtype(inference.contraCandidates); - } - else if (context.flags & 2 /* NoDefault */) { - // We use silentNeverType as the wildcard that signals no inferences. - 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 if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getContravariantInference(inference); + } + else if (context.flags & 2 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + // 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 /* AnyDefault */)); + } } } + else { + inferredType = getTypeFromInference(inference); + } inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -35573,7 +36837,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -35593,7 +36857,7 @@ var ts; function getFlowCacheKey(node) { if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } if (node.kind === 99 /* ThisKeyword */) { return "0"; @@ -35812,8 +37076,8 @@ var ts; } if (flags & 65536 /* Object */) { return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : - strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (2048 /* Void */ | 4096 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -35825,7 +37089,7 @@ var ts; return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } if (flags & 134217728 /* NonPrimitive */) { - return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & 7897088 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); @@ -35833,7 +37097,7 @@ var ts; if (flags & 393216 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 8388607 /* All */; + return 4194303 /* All */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); @@ -35847,7 +37111,7 @@ var ts; } function getTypeOfDestructuredProperty(type, name) { var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType; @@ -36031,6 +37295,9 @@ 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, noReductions) { + if (type.flags & 16384 /* Never */) { + return type; + } if (!(type.flags & 131072 /* Union */)) { return mapper(type); } @@ -36869,29 +38136,28 @@ var ts; !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } - function isApparentTypePosition(node) { + function isConstraintPosition(node) { var parent = node.parent; return parent.kind === 183 /* PropertyAccessExpression */ || parent.kind === 185 /* CallExpression */ && parent.expression === node || parent.kind === 184 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 207 /* NonNullExpression */ || parent.kind === 180 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 7372800 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getApparentTypeForLocation(type, node) { + function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getApparentType); + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + return mapType(getWidenedType(type), getBaseConstraintOrType); } return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -36963,7 +38229,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -37527,47 +38793,47 @@ var ts; // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter) { var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = func.parameters.indexOf(parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(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)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = func.parameters.indexOf(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)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } - 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. @@ -37613,7 +38879,7 @@ var ts; var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { + if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function return undefined; } var contextualReturnType = getContextualReturnType(func); @@ -37691,9 +38957,11 @@ var ts; 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. + // expression has no contextual type, the right operand is contextually typed by the type of the left operand, + // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right ? getTypeOfExpression(left, /*cache*/ true) : type; + return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? + getTypeOfExpression(left, /*cache*/ true) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; @@ -37716,6 +38984,7 @@ var ts; case 2 /* ModuleExports */: case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: + case 6 /* Prototype */: return false; default: ts.Debug.assertNever(kind); @@ -37781,7 +39050,7 @@ var ts; function getContextualTypeForChildJsxExpression(node) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // 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(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; } function getContextualTypeForJsxExpression(node) { @@ -37933,15 +39202,9 @@ var ts; return anyType; } var isJs = ts.isInJavaScriptFile(node); - return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } - function getJsxSignaturesParameterTypes(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false); - } - function getJsxSignaturesParameterTypesJs(valueType) { - return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true); - } - function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + function getJsxSignaturesParameterTypes(valueType, isJs, context) { // 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 (valueType.flags & 2 /* String */) { return anyType; @@ -37951,7 +39214,7 @@ var ts; // For example: // var CustomTag: "h1" = "h1"; // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = valueType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -37977,21 +39240,24 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */); + if (context.typeArguments) { + signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + } + return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); } - function getJsxPropsTypeFromCallSignature(sig) { + function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignature(sig); - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { propsType = intersectTypes(intrinsicAttribs, propsType); } return propsType; } - function getJsxPropsTypeFromClassType(hostClassType, isJs) { + function getJsxPropsTypeFromClassType(hostClassType, isJs, context) { if (isTypeAny(hostClassType)) { return hostClassType; } - var propsName = getJsxElementPropertiesName(); + var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context)); if (propsName === undefined) { // There is no type ElementAttributesProperty, return 'any' return anyType; @@ -38013,14 +39279,14 @@ var ts; else { // Normal case -- add in IntrinsicClassElements and IntrinsicElements var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); if (intrinsicClassAttribs !== unknownType) { var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); apparentAttributesType = intersectTypes(typeParams ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) : intrinsicClassAttribs, apparentAttributesType); } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== unknownType) { apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); } @@ -38028,18 +39294,12 @@ var ts; } } } - function getJsxPropsTypeFromConstructSignatureJs(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true); - } - function getJsxPropsTypeFromConstructSignature(sig) { - return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false); - } - function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + function getJsxPropsTypeFromConstructSignature(sig, isJs, context) { var hostClassType = getReturnTypeOfSignature(sig); if (hostClassType) { - return getJsxPropsTypeFromClassType(hostClassType, isJs); + return getJsxPropsTypeFromClassType(hostClassType, isJs, context); } - return getJsxPropsTypeFromCallSignature(sig); + return getJsxPropsTypeFromCallSignature(sig, context); } // 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. @@ -38088,7 +39348,16 @@ var ts; // union type of return types from these signatures function getContextualSignature(node) { ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); + var type; + if (ts.isInJavaScriptFile(node)) { + var jsdoc = ts.getJSDocType(node); + if (jsdoc) { + type = getTypeFromTypeNode(jsdoc); + } + } + if (!type) { + type = getContextualTypeForFunctionLikeDeclaration(node); + } if (!type) { return undefined; } @@ -38281,19 +39550,29 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createSymbolTable(); + var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; var propagatedFlags = 8388608 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 178 /* ObjectBindingPattern */ || contextualType.pattern.kind === 182 /* ObjectLiteralExpression */); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node); + var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - var isInJSFile = ts.isInJavaScriptFile(node); + if (isInJSFile && node.properties.length === 0) { + // an empty JS object literal that nonetheless has members is a JS namespace + var symbol = getSymbolOfNode(node); + if (symbol.exports) { + propertiesTable = symbol.exports; + symbol.exports.forEach(function (symbol) { return propertiesArray.push(getMergedSymbol(symbol)); }); + return createObjectLiteralType(); + } + } + propertiesTable = ts.createSymbolTable(); var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; @@ -38329,9 +39608,13 @@ var ts; } typeFlags |= type.flags; var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; - var prop = nameType && isTypeUsableAsLateBoundName(nameType) + var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType); + var prop = hasLateBoundName ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); + if (hasLateBoundName) { + prop.nameType = nameType; + } 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. @@ -38455,7 +39738,7 @@ var ts; } function checkJsxSelfClosingElement(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxElement(node, checkMode) { // Check attributes @@ -38467,14 +39750,16 @@ var ts; else { checkExpression(node.closingElement.tagName); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } function checkJsxFragment(node, checkMode) { checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); - if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { - error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) { + error(node, compilerOptions.jsxFactory + ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory + : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } - return getJsxGlobalElementType() || anyType; + return getJsxElementTypeAt(node) || anyType; } /** * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers @@ -38519,7 +39804,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -38586,7 +39871,10 @@ var ts; if (hasSpreadAnyType) { return anyType; } - return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + if (typeToIntersect && spread !== emptyObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -38624,12 +39912,11 @@ var ts; function checkJsxAttributes(node, checkMode) { return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; + function getJsxType(name, location) { + var namespace = getJsxNamespaceAt(location); + var exports = namespace && getExportsOfSymbol(namespace); + var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType; } /** * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic @@ -38640,11 +39927,11 @@ var ts; function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); if (intrinsicElementsType !== unknownType) { // Property case if (!ts.isIdentifier(node.tagName)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); if (intrinsicProp) { links.jsxFlags |= 1 /* IntrinsicNamedElement */; @@ -38693,20 +39980,66 @@ var ts; } // Instantiate in context of source type var instantiatedSignatures = []; + var candidateForTypeArgumentError; + var hasTypeArgumentError = !!node.typeArguments; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); + if (typeArgumentInstantiated) { + hasTypeArgumentError = false; + instantiatedSignatures.push(typeArgumentInstantiated); + } + else { + if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + candidateForTypeArgumentError = signature; + } + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } } else { instantiatedSignatures.push(signature); } } + if (node.typeArguments && hasTypeArgumentError) { + if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); + } + // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine + else if (node.typeArguments.length !== 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); + } + } return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } + function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (!node.typeArguments) { + return; + } + if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + return; + } + var args = checkTypeArguments(signature, node.typeArguments, reportErrors); + if (!args) { + return; + } + return getSignatureInstantiation(signature, args, isJavascript); + } + function getJsxNamespaceAt(location) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + return candidate; + } + } + // JSX global fallback + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + } /** * 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. @@ -38714,11 +40047,9 @@ var ts; * @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) { - // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -38728,6 +40059,8 @@ var ts; if (propertiesOfJsxElementAttribPropInterface.length === 0) { return ""; } + // Element Attributes has one property, so the element attributes type will be the type of the corresponding + // property of the class instance type else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } @@ -38743,19 +40076,11 @@ var ts; /// 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; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } - function getJsxElementChildrenPropertyName() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - return _jsxElementChildrenPropertyName; + function getJsxElementChildrenPropertyName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } function getApparentTypeOfJsxPropsType(propsType) { if (!propsType) { @@ -38784,7 +40109,7 @@ var ts; function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); @@ -38794,7 +40119,7 @@ var ts; paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { paramType = intersectTypes(intrinsicAttributes, paramType); } @@ -38819,7 +40144,7 @@ var ts; 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(); + var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; @@ -38853,7 +40178,7 @@ var ts; result = allMatchingAttributesType; } // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); if (intrinsicAttributes !== unknownType) { result = intersectTypes(intrinsicAttributes, result); } @@ -38896,7 +40221,7 @@ var ts; // For example: // var CustomTag: "h1" = "h1"; // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); @@ -38926,7 +40251,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -38957,7 +40282,7 @@ var ts; * @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) { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -38997,32 +40322,26 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.escapedText); return prop || unknownSymbol; } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; + function getJsxElementClassTypeAt(location) { + var type = getJsxType(JsxNames.ElementClass, location); + if (type === unknownType) + return undefined; + return type; } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } + function getJsxStatelessElementTypeAt(location) { + var jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); } - return deferredJsxStatelessElementType; } /** * Returns all the properties of the Jsx.IntrinsicElements interface */ - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); + function getJsxIntrinsicTagNamesAt(location) { + var intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; } function checkJsxPreconditions(errorNode) { @@ -39030,7 +40349,7 @@ var ts; if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); } - if (getJsxGlobalElementType() === undefined) { + if (getJsxElementTypeAt(errorNode) === undefined) { if (noImplicitAny) { error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); } @@ -39045,9 +40364,9 @@ var ts; // 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 reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* 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 @@ -39121,7 +40440,7 @@ var ts; // 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) || getPropertiesOfType(sourceAttributesType).length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement)))); } else { // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties @@ -39166,7 +40485,9 @@ var ts; return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); + return !!(symbol.flags & 8192 /* Method */ || + ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */ || + ts.isInJavaScriptFile(symbol.valueDeclaration) && ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(symbol.valueDeclaration))); } /** * Check whether the requested property access is valid. @@ -39328,7 +40649,7 @@ var ts; return unknownType; } } - propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); + propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -39439,7 +40760,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455 /* Value */); + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 67216319 /* Value */); return suggestion && ts.symbolName(suggestion); } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { @@ -39454,6 +40775,10 @@ var ts; }); return result && ts.symbolName(result); } + function getSuggestionForNonexistentModule(name, targetModule) { + var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + return suggestion && ts.symbolName(suggestion); + } /** * 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. @@ -39478,7 +40803,8 @@ var ts; for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; var candidateName = ts.symbolName(candidate); - if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + if (candidateName.charCodeAt(0) === 34 /* doubleQuote */ + || !(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { continue; } var candidateNameLowerCase = candidateName.toLowerCase(); @@ -39572,15 +40898,23 @@ var ts; return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } - function isValidMethodAccess(method, type) { + function isValidMethodAccess(method, actualThisType) { var propType = getTypeOfFuncClassEnumModule(method); var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { - var thisType = getThisTypeOfSignature(sig); - return !thisType || isTypeAssignableTo(type, thisType); + var signatureThisType = getThisTypeOfSignature(sig); + return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType)); }); } + function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) { + if (!sig.typeParameters) { + return signatureThisType; + } + var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */); + inferTypes(context.inferences, actualThisType, signatureThisType); + return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type === unknownType || isTypeAny(type)) { return true; @@ -39831,13 +41165,7 @@ var ts; typeArguments = node.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 || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { + if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { 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. @@ -39853,6 +41181,14 @@ var ts; var hasEnoughArguments = argCount >= signature.minArgumentCount; return callIsIncomplete || hasEnoughArguments; } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + // 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); + return !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { if (type.flags & 65536 /* Object */) { @@ -39866,13 +41202,13 @@ var ts; } // 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 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, 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 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -39923,7 +41259,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); @@ -40354,6 +41690,17 @@ var ts; return arg; } } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { var isTaggedTemplate = node.kind === 187 /* TaggedTemplateExpression */; var isDecorator = node.kind === 149 /* Decorator */; @@ -40470,21 +41817,13 @@ var ts; 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; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); - } - var paramCount = min < max ? min + "-" + max : min; - diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { - var sig = signatures_6[_a]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -40556,7 +41895,7 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : + createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : undefined; while (true) { candidate = originalCandidate; @@ -40980,19 +42319,49 @@ var ts; return false; } function getJavaScriptClassType(symbol) { - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + var initializer = ts.getDeclaredJavascriptInitializer(symbol.valueDeclaration); + if (initializer) { + symbol = getSymbolOfNode(initializer); } + var inferred; if (isJavaScriptConstructor(symbol.valueDeclaration)) { - return getInferredClassType(symbol); + inferred = getInferredClassType(symbol); } - if (symbol.flags & 3 /* Variable */) { - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { - return getInferredClassType(valueType.symbol); + var assigned = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + inferred = getInferredClassType(valueType.symbol); + } + return assigned && inferred ? + getIntersectionType([inferred, assigned]) : + assigned || inferred; + } + function getAssignedClassType(symbol) { + var decl = symbol.valueDeclaration; + var assignmentSymbol = decl && decl.parent && + (ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); + if (assignmentSymbol) { + var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); + if (prototype) { + return checkExpression(prototype); } } } + function getAssignedJavascriptPrototype(node) { + if (!node.parent) { + return false; + } + var parent = node.parent; + while (parent && parent.kind === 183 /* PropertyAccessExpression */) { + parent = parent.parent; + } + return parent && ts.isBinaryExpression(parent) && + ts.isPrototypeAccess(parent.left) && + parent.operatorToken.kind === 58 /* EqualsToken */ && + ts.isObjectLiteralExpression(parent.right) && + parent.right; + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -41070,7 +42439,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -41123,13 +42492,13 @@ var ts; return type; } function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ 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 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (!resolvedRequire) { // project does not contain symbol named 'require' - assume commonjs require return true; @@ -41320,7 +42689,7 @@ var ts; } else { var types = checkAndAggregateReturnExpressionTypes(func, checkMode); - if (functionFlags & 1 /* Generator */) { + if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { var iterableIteratorAny = functionFlags & 2 /* Async */ @@ -41389,25 +42758,21 @@ var ts; } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); + var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0; ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - // A yield* expression effectively yields everything that its operand yields - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); - } - 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); - } - ts.pushIfUnique(aggregatedTypes, type); - } + ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode)); }); return aggregatedTypes; } + function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { + var errorNode = node.expression || node; + var expressionType = node.expression ? checkExpressionCached(node.expression, checkMode) : undefinedWideningType; + // A `yield*` expression effectively yields everything that its operand yields + var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.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); + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; @@ -41431,7 +42796,7 @@ var ts; } return true; } - /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ function checkAndAggregateReturnExpressionTypes(func, checkMode) { var functionFlags = ts.getFunctionFlags(func); var aggregatedTypes = []; @@ -41460,7 +42825,9 @@ var ts; if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -41531,7 +42898,6 @@ var ts; ts.Debug.assert(node.kind !== 153 /* 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 @@ -41586,7 +42952,7 @@ var ts; ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : // Async function getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function - if ((functionFlags & 1 /* Generator */) === 0) { + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } @@ -41610,11 +42976,11 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function 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); } - else { + else { // Normal function checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } @@ -42070,6 +43436,9 @@ var ts; return (target.flags & 12288 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + return checkExpression(node.right, checkMode); + } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { @@ -42279,52 +43648,35 @@ var ts; error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); } } - 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) { - // 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 */); - } - // Generator functions prior to ES2015 require the __values helper - if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && - languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256 /* Values */); - } + var func = ts.getContainingFunction(node); + var functionFlags = func ? ts.getFunctionFlags(func) : 0 /* Normal */; + if (!(functionFlags & 1 /* Generator */)) { + // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. + return anyType; + } + if (node.asteriskToken) { + // 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 & 1 /* Generator */) { - var expressionType = checkExpressionCached(node.expression); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - 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 /* Async */) !== 0) || anyType; - if (nodeIsYieldStar) { - 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, - /*headMessage*/ undefined); - } - else { - 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, - /*headMessage*/ undefined); - } - } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); } } + var isAsync = (functionFlags & 2 /* Async */) !== 0; + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + // 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), isAsync) || anyType; + checkTypeAssignableTo(yieldedType, signatureElementType, node.expression || node, /*headMessage*/ undefined); + } // Both yield and yield* expressions have type 'any' return anyType; } @@ -42385,10 +43737,27 @@ var ts; return node.kind === 188 /* TypeAssertionExpression */ || node.kind === 206 /* AsExpression */; } function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); - return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + var inJs = ts.isInJavaScriptFile(declaration); + var initializer = inJs && ts.getDeclaredJavascriptInitializer(declaration) || declaration.initializer; + var type = getTypeOfExpression(initializer, /*cache*/ true); + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (inJs) { + if (widened.flags & 12288 /* Nullable */) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyType); + } + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyArrayType); + } + return anyArrayType; + } + } + return widened; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { @@ -42469,7 +43838,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 === 185 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true) && !isSymbolOrSymbolForCall(node)) { + if (node.kind === 185 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -42771,6 +44140,7 @@ var ts; if (node.kind === 159 /* IndexSignature */) { checkGrammarIndexSignature(node); } + // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled else if (node.kind === 162 /* FunctionType */ || node.kind === 232 /* FunctionDeclaration */ || node.kind === 163 /* ConstructorType */ || node.kind === 157 /* CallSignature */ || node.kind === 154 /* Constructor */ || node.kind === 158 /* ConstructSignature */) { @@ -43589,7 +44959,7 @@ var ts; case 230 /* VariableDeclaration */: case 180 /* BindingElement */: case 232 /* FunctionDeclaration */: - case 246 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 + case 246 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -43816,7 +45186,7 @@ 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 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; if (promiseConstructorType === unknownType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -43839,7 +45209,7 @@ var ts; } // 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 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; @@ -43893,7 +45263,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -44041,7 +45411,20 @@ var ts; 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 === 145 /* QualifiedName */ ? node.name.right : node.name)); + var decl = ts.getHostSignatureFromJSDoc(node); + // don't issue an error for invalid hosts -- just functions -- + // and give a better error message when the host function mentions `arguments` + // but the tag doesn't have an array type + if (decl) { + if (!containsArgumentsReference(decl)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + } + else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && + node.typeExpression && node.typeExpression.type && + !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + } + } } } function checkJSDocAugmentsTag(node) { @@ -44050,7 +45433,7 @@ var ts; error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } - var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 285 /* JSDocAugmentsTag */); + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); 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); @@ -44113,7 +45496,7 @@ var ts; var body = node.kind === 152 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - if ((functionFlags & 1 /* Generator */) === 0) { + if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ ? checkAsyncFunctionReturnType(node) // Async function : getTypeFromTypeNode(returnTypeNode)); // normal function @@ -44136,6 +45519,8 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { if (deferredUnusedIdentifierNodes) { + // TODO: GH#22580 + // Debug.assert(addToSeen(seenDeferredUnusedIdentifiers, getNodeId(node)), "Deferring unused identifier check twice"); deferredUnusedIdentifierNodes.push(node); } } @@ -44229,14 +45614,14 @@ var ts; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); + diagnostics.add(ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 /* Identifier */ && ts.idText(node).charCodeAt(0) === 95 /* _ */; + return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { @@ -44295,18 +45680,60 @@ var ts; } function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports_1 = ts.createMap(); node.locals.forEach(function (local) { - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration, ts.symbolName(local)); + if (local.isReferenced || local.exportSymbol) + return; + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + var importClause = importClauseFromImported(declaration); + var key = String(getNodeId(importClause)); + var group_1 = unusedImports_1.get(key); + if (group_1) { + group_1[1].push(declaration); } + else { + unusedImports_1.set(key, [importClause, [declaration]]); + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local)); } } }); + unusedImports_1.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name)); + } + } + else if (unuseds.length === 1) { + error(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)); + } + else { + error(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)); + } + }); } } + function isImportedDeclaration(node) { + return node.kind === 243 /* ImportClause */ || node.kind === 246 /* ImportSpecifier */ || node.kind === 244 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 243 /* ImportClause */ ? decl : decl.kind === 244 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function forEachImportedDeclaration(importClause, cb) { + var defaultName = importClause.name, namedBindings = importClause.namedBindings; + return (defaultName && cb(importClause)) || + namedBindings && (namedBindings.kind === 244 /* NamespaceImport */ ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); + } function checkBlock(node) { // Grammar checking for SyntaxKind.Block if (node.kind === 211 /* Block */) { @@ -44326,7 +45753,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -44360,12 +45787,12 @@ var ts; return true; } function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { + if (languageVersion <= 1 /* ES5 */ && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_this")) { potentialThisCollisions.push(node); } } function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + if (languageVersion <= 1 /* ES5 */ && !compilerOptions.noEmit && needCollisionCheckForIdentifier(node, name, "_newTarget")) { potentialNewTargetCollisions.push(node); } } @@ -44399,6 +45826,9 @@ var ts; }); } function checkCollisionWithCapturedSuperVariable(node, name) { + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } @@ -44420,7 +45850,7 @@ var ts; } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { // No need to check for require or exports for ES6 modules and later - if (modulekind >= ts.ModuleKind.ES2015) { + if (modulekind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { return; } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { @@ -44438,7 +45868,7 @@ var ts; } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } // Uninstantiated modules shouldnt do this check @@ -44488,7 +45918,7 @@ var ts; var symbol = getSymbolOfNode(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!ts.isIdentifier(node.name)) - throw ts.Debug.fail(); + return ts.Debug.fail(); var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && @@ -44537,7 +45967,7 @@ var ts; 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); + var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -44656,7 +46086,8 @@ var ts; // 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 !== 219 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); + var initializer = ts.isInJavaScriptFile(node) && ts.getDeclaredJavascriptInitializer(node) || node.initializer; + checkTypeAssignableTo(checkExpressionCached(initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } } @@ -45191,7 +46622,7 @@ var ts; var isGenerator = functionFlags & 1 /* Generator */; if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (isGenerator) { + 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 types of generators when return type tracking is added @@ -45209,7 +46640,7 @@ var ts; } } else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2 /* Async */) { + if (functionFlags & 2 /* Async */) { // Async function 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) { @@ -45295,8 +46726,7 @@ var ts; return "quit"; } if (current.kind === 226 /* 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)); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } }); @@ -45651,7 +47081,7 @@ var ts; var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && baseProp) { var rootChain = function () { return ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); }; if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { issuedMemberError = true; } @@ -46166,7 +47596,6 @@ var ts; // - 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); @@ -46271,7 +47700,11 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { + if (ts.nodeIsMissing(moduleName)) { + // Should be a parse error. + return false; + } + if (!ts.isStringLiteral(moduleName)) { error(moduleName, ts.Diagnostics.String_literal_expected); return false; } @@ -46282,7 +47715,7 @@ var ts; ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { // 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)) { @@ -46306,8 +47739,8 @@ var ts; // 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) | + var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | + (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 250 /* ExportSpecifier */ ? @@ -46318,7 +47751,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 250 /* ExportSpecifier */ - && !(target.flags & 107455 /* Value */) + && !(target.flags & 67216319 /* Value */) && !(node.flags & 2097152 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -46369,14 +47802,14 @@ var ts; if (node.moduleReference.kind !== 252 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 107455 /* Value */) { + if (target.flags & 67216319 /* 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 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67216319 /* 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 /* Type */) { + if (target.flags & 67901928 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -46436,7 +47869,7 @@ var ts; 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 */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* 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.idText(exportedName)); @@ -46712,8 +48145,14 @@ var ts; function checkJSDocVariadicType(node) { checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); - // Only legal location is in the *last* parameter tag. + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } @@ -46738,22 +48177,26 @@ var ts; 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); + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { /* - Only return an array type if the corresponding parameter is marked as a rest parameter. + Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: /** @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)) { + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var symbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { return createArrayType(type); } } } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } return addOptionality(type); } // Function and class expression bodies are checked after all statements in the enclosing body. This is @@ -46822,6 +48265,7 @@ var ts; checkUnusedIdentifiers(); } deferredNodes = undefined; + seenDeferredUnusedIdentifiers.clear(); deferredUnusedIdentifierNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); @@ -46924,7 +48368,7 @@ var ts; // (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(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); } break; case 190 /* FunctionExpression */: @@ -47065,7 +48509,7 @@ var ts; } if (entityName.parent.kind === 247 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } if (entityName.kind !== 183 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import @@ -47080,10 +48524,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 205 /* ExpressionWithTypeArguments */) { - meaning = 793064 /* Type */; + meaning = 67901928 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455 /* Value */; + meaning |= 67216319 /* Value */; } } else { @@ -47113,7 +48557,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 183 /* PropertyAccessExpression */ || entityName.kind === 145 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -47130,7 +48574,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 161 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 161 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 260 /* JsxAttribute */) { @@ -47206,7 +48650,7 @@ var ts; // 3). Dynamic import call or require in javascript if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 242 /* ImportDeclaration */ || node.parent.kind === 248 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } // falls through @@ -47231,7 +48675,7 @@ var ts; // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. if (location && location.kind === 269 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 107455 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -47239,7 +48683,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 4194304 /* InWithStatement */) { @@ -47424,13 +48868,13 @@ var ts; // 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 /* Value */) + ? !!(moduleSymbol.flags & 67216319 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 107455 /* Value */); + return s && !!(s.flags & 67216319 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -47480,7 +48924,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // 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 */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -47493,7 +48937,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -47589,7 +49033,7 @@ var ts; } // 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 */ && + return target.flags & 67216319 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -47602,7 +49046,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 107455 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -47614,6 +49058,8 @@ var ts; } function isImplementationOfOverload(node) { if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload @@ -47687,9 +49133,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // 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); + var valueSymbol = resolveEntityName(typeName, 67216319 /* 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); + var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -47739,7 +49185,11 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { + declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(119 /* AnyKeyword */); + } // 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 /* TypeLiteral */ | 131072 /* Signature */)) @@ -47749,18 +49199,26 @@ var ts; type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 131072 /* AddUndefined */) { + if (addUndefined) { type = getOptionalType(type); } - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { + signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(119 /* AnyKeyword */); + } var signature = getSignatureFromDeclaration(signatureDeclaration); - typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { + expr = ts.getParseTreeNode(expr, ts.isExpression); + if (!expr) { + return ts.createToken(119 /* AnyKeyword */); + } var type = getWidenedType(getRegularTypeOfExpression(expr)); - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -47779,7 +49237,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -47800,9 +49258,12 @@ var ts; } return false; } - function writeLiteralConstValue(node, writer) { + function literalTypeToNode(type) { + return ts.createLiteral(type.value); + } + function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); + return literalTypeToNode(type); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -47845,9 +49306,10 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -47869,8 +49331,7 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } }; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -47882,8 +49343,8 @@ var ts; // 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 === 183 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) - ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793064 /* Type */ | 1920 /* Namespace */; + ? 67216319 /* Value */ | 1048576 /* ExportValue */ + : 67901928 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -47947,7 +49408,7 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 237 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); if (!moduleSymbol) { return undefined; @@ -48048,7 +49509,7 @@ var ts; 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 */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -48687,6 +50148,7 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; @@ -49079,8 +50541,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } } @@ -49232,8 +50694,8 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { 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), /*length*/ 0, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } } @@ -49283,7 +50745,7 @@ var ts; case 243 /* ImportClause */: // For default import case 241 /* ImportEqualsDeclaration */: case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */:// For rename import `x as y` + case 246 /* ImportSpecifier */: // For rename import `x as y` return true; case 71 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. @@ -49329,14 +50791,14 @@ var ts; * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. */ function createNodeArray(elements, hasTrailingComma) { - if (elements) { + if (!elements || elements === ts.emptyArray) { + elements = []; + } + else { if (ts.isNodeArray(elements)) { return elements; } } - else { - elements = []; - } var array = elements; array.pos = -1; array.end = -1; @@ -49367,7 +50829,7 @@ var ts; return clone; } ts.getSynthesizedClone = getSynthesizedClone; - function createLiteral(value) { + function createLiteral(value, isSingleQuote) { if (typeof value === "number") { return createNumericLiteral(value + ""); } @@ -49375,7 +50837,10 @@ var ts; return value ? createTrue() : createFalse(); } if (ts.isString(value)) { - return createStringLiteral(value); + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; } return createLiteralFromNode(value); } @@ -49448,6 +50913,15 @@ var ts; return name; } ts.createUniqueName = createUniqueName; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 5 /* OptimisticUnique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateFlags = 4 /* Node */; @@ -49486,6 +50960,49 @@ var ts; return createSynthesizedNode(86 /* FalseKeyword */); } ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(84 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(124 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(79 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(76 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(114 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(112 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(113 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(117 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(115 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(132 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(120 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { var node = createSynthesizedNode(145 /* QualifiedName */); @@ -49501,9 +51018,15 @@ var ts; : node; } ts.updateQualifiedName = updateQualifiedName; + function parenthesizeForComputedName(expression) { + return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || + expression.kind === 296 /* CommaListExpression */ ? + createParen(expression) : + expression; + } function createComputedPropertyName(expression) { var node = createSynthesizedNode(146 /* ComputedPropertyName */); - node.expression = expression; + node.expression = parenthesizeForComputedName(expression); return node; } ts.createComputedPropertyName = createComputedPropertyName; @@ -51134,31 +52657,35 @@ var ts; : node; } ts.updateJsxElement = updateJsxElement; - function createJsxSelfClosingElement(tagName, attributes) { + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(254 /* JsxSelfClosingElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxSelfClosingElement = createJsxSelfClosingElement; - function updateJsxSelfClosingElement(node, tagName, attributes) { + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxSelfClosingElement(tagName, attributes), node) + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; - function createJsxOpeningElement(tagName, attributes) { + function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(255 /* JsxOpeningElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxOpeningElement = createJsxOpeningElement; - function updateJsxOpeningElement(node, tagName, attributes) { + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxOpeningElement(tagName, attributes), node) + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxOpeningElement = updateJsxOpeningElement; @@ -51300,7 +52827,7 @@ var ts; var node = createSynthesizedNode(268 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; - node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; + node.initializer = ts.parenthesizeExpressionForList(initializer); return node; } ts.createPropertyAssignment = createPropertyAssignment; @@ -51353,8 +52880,11 @@ var ts; } ts.updateEnumMember = updateEnumMember; // Top-level nodes - function updateSourceFileNode(node, statements) { - if (node.statements !== statements) { + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences)) { var updated = createSynthesizedNode(272 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); @@ -51362,18 +52892,15 @@ var ts; updated.fileName = node.fileName; updated.path = node.path; updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; - if (node.referencedFiles !== undefined) - updated.referencedFiles = node.referencedFiles; - if (node.typeReferenceDirectives !== undefined) - updated.typeReferenceDirectives = node.typeReferenceDirectives; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; - if (node.isDeclarationFile !== undefined) - updated.isDeclarationFile = node.isDeclarationFile; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; if (node.hasNoDefaultLib !== undefined) @@ -51410,6 +52937,12 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; + if (node.pragmas !== undefined) + updated.pragmas = node.pragmas; + if (node.localJsxFactory !== undefined) + updated.localJsxFactory = node.localJsxFactory; + if (node.localJsxNamespace !== undefined) + updated.localJsxNamespace = node.localJsxNamespace; return updateNode(updated, node); } return node; @@ -51953,7 +53486,8 @@ var ts; requestEmitHelper: ts.noop, resumeLexicalEnvironment: ts.noop, startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, }; function createTypeCheck(value, tag) { return tag === "undefined" @@ -52086,7 +53620,7 @@ var ts; var valuesHelper = { name: "typescript:values", scoped: false, - text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };\n " + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" }; function createValuesHelper(context, expression, location) { context.requestEmitHelper(valuesHelper); @@ -52097,7 +53631,7 @@ var ts; var readHelper = { name: "typescript:read", scoped: false, - text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };\n " + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" }; function createReadHelper(context, iteratorRecord, count, location) { context.requestEmitHelper(readHelper); @@ -52158,7 +53692,7 @@ var ts; } ts.restoreEnclosingLabel = restoreEnclosingLabel; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { - var target = skipParentheses(node); + var target = ts.skipParentheses(node); switch (target.kind) { case 71 /* Identifier */: return cacheIdentifiers; @@ -52987,7 +54521,7 @@ var ts; do { previousNode = node; if (kinds & 1 /* Parentheses */) { - node = skipParentheses(node); + node = ts.skipParentheses(node); } if (kinds & 2 /* Assertions */) { node = skipAssertions(node); @@ -52999,13 +54533,6 @@ var ts; return node; } ts.skipOuterExpressions = skipOuterExpressions; - function skipParentheses(node) { - while (node.kind === 189 /* ParenthesizedExpression */) { - node = node.expression; - } - return node; - } - ts.skipParentheses = skipParentheses; function skipAssertions(node) { while (ts.isAssertionExpression(node) || node.kind === 207 /* NonNullExpression */) { node = node.expression; @@ -53767,9 +55294,9 @@ var ts; case 253 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 254 /* JsxSelfClosingElement */: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 255 /* JsxOpeningElement */: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 256 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 257 /* JsxFragment */: @@ -54337,9 +55864,10 @@ var ts; var Debug; (function (Debug) { var isDebugInfoEnabled = false; - 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; + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; 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; @@ -54444,7 +55972,7 @@ var ts; var uniqueExports = ts.createMap(); var exportedNames; var hasExportDefault = false; - var exportEquals = undefined; + var exportEquals; var hasExportStarsToExportValues = false; var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -55361,8 +56889,7 @@ var ts; case 210 /* SemicolonClassElement */: return node; default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { @@ -55533,8 +57060,7 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitSourceFile(node) { @@ -56048,7 +57574,7 @@ var ts; ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); 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))); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); } /** * Gets all property declarations with initializers on either the static or instance side of a class. @@ -56662,10 +58188,8 @@ var ts; case 86 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: - ts.Debug.failBadSyntaxKind(node.literal); - break; + return ts.Debug.failBadSyntaxKind(node.literal); } - break; case 134 /* NumberKeyword */: return ts.createIdentifier("Number"); case 138 /* SymbolKeyword */: @@ -56686,8 +58210,7 @@ var ts; case 173 /* ThisType */: break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } @@ -56711,6 +58234,8 @@ var ts; // One of the individual is global object, return immediately return serializedIndividual; } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object else if (serializedUnion) { // Different types if (!ts.isIdentifier(serializedUnion) || @@ -56874,7 +58399,7 @@ var ts; function visitPropertyNameOfClassElement(member) { var name = member.name; var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); - if (expr) { + if (expr) { // expr only exists if `name` is a computed property name // 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])); @@ -58496,12 +60021,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: "\n const _super = name => super[name];\n " + text: "\n const _super = name => super[name];" }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - 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 " + 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);" }; })(ts || (ts = {})); /// @@ -59082,7 +60607,7 @@ var ts; var awaitHelper = { name: "typescript:await", scoped: false, - text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" }; function createAwaitHelper(context, expression) { context.requestEmitHelper(awaitHelper); @@ -59091,7 +60616,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -59108,7 +60633,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -59119,7 +60644,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -59186,8 +60711,7 @@ var ts; case 257 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxElement(node, isChild) { @@ -59225,14 +60749,14 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } return element; } function visitJsxOpeningFragment(node, children, isChild, location) { - var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -59264,7 +60788,7 @@ var ts; return visitJsxExpression(node); } else { - ts.Debug.failBadSyntaxKind(node); + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxText(node) { @@ -60424,6 +61948,7 @@ var ts; if (statement.kind === 223 /* ReturnStatement */) { return true; } + // An if-statement with two covered branches is covered. else if (statement.kind === 215 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { @@ -60431,6 +61956,7 @@ var ts; isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } + // A block is covered if it has a last statement which is covered. else if (statement.kind === 211 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { @@ -60629,11 +62155,11 @@ var ts; 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 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter)) - ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */)); + ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); statements.push(statement); } /** @@ -60738,8 +62264,7 @@ var ts; 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; + return ts.Debug.failBadSyntaxKind(node); } var captureNewTargetStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -61382,26 +62907,23 @@ var ts; statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); } } - var bodyLocation; - var statementsLocation; if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); } else { var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); } else { statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); } } - // 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 createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { // The following ES6 code: @@ -61980,18 +63502,15 @@ var ts; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { - var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = transformFunctionBody(node); - if (node.kind === 155 /* GetAccessor */) { - updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); - } - else { - updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); - } + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 155 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { - updated = ts.visitEachChild(node, visitor, context); + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; @@ -62457,14 +63976,14 @@ var ts; */ 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)); + var span = _a[_i]; + expressions.push(ts.visitNode(span.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)); + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); } } } @@ -63177,8 +64696,7 @@ var ts; case 190 /* FunctionExpression */: return visitFunctionExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } /** @@ -65222,6 +66740,7 @@ var ts; withBlockStack.pop(); } break; + // default: do nothing } } } @@ -66738,7 +68257,7 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" }; function createExportStarHelper(context, module) { var compilerOptions = context.getCompilerOptions(); @@ -66756,13 +68275,13 @@ var ts; var importStarHelper = { name: "typescript:commonjsimportstar", scoped: false, - text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" }; // emit helper for `import Name from "foo"` var importDefaultHelper = { name: "typescript:commonjsimportdefault", scoped: false, - text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" }; })(ts || (ts = {})); /// @@ -67100,12 +68619,12 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_1 = dependencyGroups_1[_i]; + var group_2 = dependencyGroups_1[_i]; // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -68317,6 +69836,1435 @@ var ts; } ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + 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 === 233 /* 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 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 === 233 /* 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; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */) { + 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; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || + (node.kind === 148 /* 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 /* 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 === 233 /* ClassDeclaration */ || node.kind === 148 /* 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 : + 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; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 156 /* 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(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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_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; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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 /* 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: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: + case 152 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + 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 === 233 /* 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 : + 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 232 /* 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 : + 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; + break; + default: + ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 154 /* 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 158 /* ConstructSignature */: + case 163 /* ConstructorType */: + // 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: + case 152 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + 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 === 233 /* 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 : + 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 232 /* FunctionDeclaration */: + case 162 /* FunctionType */: + 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 : + 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; + default: + ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + 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 233 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 234 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 158 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 157 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 153 /* MethodDeclaration */: + case 152 /* 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 === 233 /* 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 232 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 235 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 233 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + 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 { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJavaScript(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var enclosingDeclaration; + var necessaryTypeRefernces; + var possibleImports; + var importDeclarationMap; + var suppressNewDiagnosticContexts; + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + }; + var errorNameNode; + var currentSourceFile; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + var host = context.getEmitHost(); + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeRefernces.set(ref, true); + } + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!possibleImports) { + possibleImports = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(possibleImports, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(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) { + context.addDiagnostic(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 transformRoot(node) { + if (node.kind === 272 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + return node; + } + if (node.kind === 273 /* Bundle */) { + isBundledEmit = true; + var refs_1 = ts.createMap(); + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + return; // Omit declaration files from bundle results, too + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + possibleImports = undefined; + suppressNewDiagnosticContexts = false; + importDeclarationMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + collectReferences(sourceFile, refs_1); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, updated, /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs_1.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + possibleImports = undefined; + importDeclarationMap = ts.createMap(); + necessaryTypeRefernces = undefined; + var refs = collectReferences(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + refs.forEach(referenceVisitor); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + if (ts.isExternalModule(node) && !resultHasExternalModuleIndicator) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences()); + return updated; + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeRefernces ? ts.map(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getNodeId(elem), elem); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 71 /* Identifier */) { + return name; + } + else { + if (name.kind === 179 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 204 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 148 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + if (node.kind === 156 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 148 /* Parameter */ + || node.kind === 151 /* PropertyDeclaration */ + || node.kind === 150 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 237 /* ModuleDeclaration */: + case 234 /* InterfaceDeclaration */: + case 233 /* ClassDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 236 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 230 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 241 /* ImportEqualsDeclaration */: + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + case 247 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.forEach(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237 /* ModuleDeclaration */; + if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 252 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 244 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function filterCandidateImports(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + var unconsideredImports = []; + while (ts.length(possibleImports)) { + var i = possibleImports.shift(); + if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope + unconsideredImports.push(i); + continue; + } + // Eagerly transform import equals - if they're not visible, we'll get nothing, if they are, we'll immediately add them since it's complete + if (i.kind === 241 /* ImportEqualsDeclaration */) { + var result_3 = transformImportEqualsDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result_3); + continue; + } + // Import declarations, on the other hand, can be partially painted by multiple aliases; so we can see many indeterminate states + // until we've marked all possible visibility + var result = transformImportDeclaration(i); + importDeclarationMap.set("" + ts.getNodeId(i), result); + } + // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not + // be considered in the child scope + possibleImports = unconsideredImports; + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.mapDefined(statements, function (statement) { + if (ts.isImportDeclaration(statement) || ts.isImportEqualsDeclaration(statement)) { + var key = "" + ts.getNodeId(statement); + if (importDeclarationMap.has(key)) { + var result = importDeclarationMap.get(key); + importDeclarationMap.delete(key); + return result; + } + else { + return undefined; + } + } + else { + return statement; + } + }); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, input.modifiers, input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 165 /* TypeLiteral */ || input.kind === 176 /* MappedType */) && input.parent.kind !== 235 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 205 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 161 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 158 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 154 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 153 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(152 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 155 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 156 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 151 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 150 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 152 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 157 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 159 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + } + case 230 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 147 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 170 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 162 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 163 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 153 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 248 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 247 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + if (input.expression.kind === 71 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + case 241 /* ImportEqualsDeclaration */: + case 242 /* ImportDeclaration */: { + // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later + // to reduce the likelihood we need to rewrite it + possibleImports = possibleImports || []; + ts.pushIfUnique(possibleImports, input); + return input; + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var previousNeedsDeclare; + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var oldPossibleImports; + switch (input.kind) { + case 235 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 234 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 232 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + return cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + } + case 237 /* ModuleDeclaration */: { + previousNeedsDeclare = needsDeclare; + needsDeclare = false; + oldPossibleImports = possibleImports; + possibleImports = undefined; + var inner = input.body; + if (inner && inner.kind === 238 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input); + needsDeclare = false; + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + } + } + case 233 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 71 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 85 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 212 /* VariableStatement */: { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return cleanup(ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes))); + } + case 236 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(returnValue) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (input.kind === 237 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + possibleImports = ts.concatenate(oldPossibleImports, possibleImports); + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (returnValue) { + if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) { + // Exported top-level member indicates moduleness + resultHasExternalModuleIndicator = true; + } + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 204 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function ensureModifiers(node) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 272 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((isBundledEmit && parentIsFile ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_6 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_6(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 234 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 155 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 230 /* VariableDeclaration */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: + case 148 /* Parameter */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 237 /* ModuleDeclaration */: + case 241 /* ImportEqualsDeclaration */: + case 234 /* InterfaceDeclaration */: + case 233 /* ClassDeclaration */: + case 235 /* TypeAliasDeclaration */: + case 236 /* EnumDeclaration */: + case 212 /* VariableStatement */: + case 242 /* ImportDeclaration */: + case 248 /* ExportDeclaration */: + case 247 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 158 /* ConstructSignature */: + case 154 /* Constructor */: + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: + case 152 /* MethodSignature */: + case 157 /* CallSignature */: + case 159 /* IndexSignature */: + case 230 /* VariableDeclaration */: + case 147 /* TypeParameter */: + case 205 /* ExpressionWithTypeArguments */: + case 161 /* TypeReference */: + case 170 /* ConditionalType */: + case 162 /* FunctionType */: + case 163 /* ConstructorType */: + return true; + } + return false; + } +})(ts || (ts = {})); /// /// /// @@ -68330,6 +71278,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -68411,6 +71360,7 @@ var ts; var onSubstituteNode = function (_, node) { return node; }; var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; var state = 0 /* Uninitialized */; + var diagnostics = []; // The transformation context is provided to each transformer as part of transformer // initialization. var context = { @@ -68440,6 +71390,9 @@ var ts; 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; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); } }; // Ensure the parse tree is clean before applying transformations @@ -68462,7 +71415,8 @@ var ts; transformed: transformed, substituteNode: substituteNode, emitNodeWithNotification: emitNodeWithNotification, - dispose: dispose + dispose: dispose, + diagnostics: diagnostics }; function transformRoot(node) { return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; @@ -68665,8 +71619,8 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); + function createSourceMapWriter(host, writer, compilerOptions) { + if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSource; var currentSourceText; @@ -68679,11 +71633,11 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; + var sourceMapDataList; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, - getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitNodeWithSourceMap: emitNodeWithSourceMap, @@ -68704,13 +71658,14 @@ var ts; * @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) { + function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { if (disabled) { return; } if (sourceMapData) { reset(); } + sourceMapDataList = outputSourceMapDataList; currentSource = undefined; currentSourceText = undefined; // Current source map file and its index in the sources list @@ -68740,7 +71695,7 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 272 /* SourceFile */) { + if (sourceFileOrBundle.kind === 272 /* SourceFile */) { // emitting single module file // 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)); @@ -68768,6 +71723,10 @@ var ts; if (disabled) { return; } + // Record source map data for the test harness. + if (sourceMapDataList) { + sourceMapDataList.push(sourceMapData); + } currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -68775,6 +71734,7 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + sourceMapDataList = undefined; } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -68993,7 +71953,7 @@ var ts; } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(getText()); + var base64SourceMapText = ts.base64encode(ts.sys, getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; } else { @@ -69247,7 +72207,15 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -69275,6 +72243,8 @@ var ts; forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -69372,6 +72342,8 @@ var ts; } } function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (emitPos) emitPos(commentPos); ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); @@ -69389,1828 +72361,8 @@ var ts; } ts.createCommentWriter = createCommentWriter; })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var declarationDiagnostics = ts.createDiagnosticCollection(); - ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); - return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); - function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) { - var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false); - } - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 273 /* Bundle */; - var newLine = host.getNewLine(); - var compilerOptions = host.getCompilerOptions(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer; - createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var resultHasExternalModuleIndicator; - var currentText; - var currentLineMap; - var currentIdentifiers; - var isCurrentFileExternalModule; - var reportedDeclarationError = false; - var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; - var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - 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; - } - emittedReferencedFiles.push(referencedFile); - } - }); - } - resultHasExternalModuleIndicator = false; - if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - needsDeclare = true; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - needsDeclare = false; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - 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 === 242 /* ImportDeclaration */); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - increaseIndent(); - } - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - decreaseIndent(); - } - } - }); - setWriter(oldWriter); - allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - if (!isBundledEmit && ts.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 {};"); - writeLine(); - } - }); - if (usedTypeDirectiveReferences) { - ts.forEachKey(usedTypeDirectiveReferences, function (directive) { - referencesOutput += "/// " + newLine; - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput, - }; - function hasInternalAnnotation(range) { - var comment = currentText.substring(range.pos, range.end); - return ts.stringContains(comment, "@internal"); - } - function stripInternal(node) { - if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); - if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { - return; - } - emitNode(node); - } - } - function createAndSetNewTextWriterWithSymbolWriter() { - 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; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeProperty = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsynchronousModuleElements(nodes) { - var oldWriter = writer; - ts.forEach(nodes, function (declaration) { - var nodeToCheck; - if (declaration.kind === 230 /* VariableDeclaration */) { - nodeToCheck = declaration.parent.parent; - } - else if (declaration.kind === 245 /* NamedImports */ || declaration.kind === 246 /* ImportSpecifier */ || declaration.kind === 243 /* ImportClause */) { - ts.Debug.fail("We should be getting ImportDeclaration instead to write"); - } - else { - nodeToCheck = declaration; - } - var moduleElementEmitInfo = ts.forEach(moduleElementDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - 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 === 242 /* 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 { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); - asynchronousSubModuleDeclarationEmitInfo = []; - } - writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; - asynchronousSubModuleDeclarationEmitInfo = undefined; - } - moduleElementEmitInfo.asynchronousOutput = writer.getText(); - } - } - }); - setWriter(oldWriter); - } - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { - if (!typeReferenceDirectives) { - return; - } - if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); - } - for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { - var directive = typeReferenceDirectives_1[_i]; - if (!usedTypeDirectiveReferences.has(directive)) { - usedTypeDirectiveReferences.set(directive, directive); - } - } - } - function handleSymbolAccessibilityError(symbolAccessibilityResult) { - 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) { - if (errorInfo.typeName) { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - else { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); - } - function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - reportedDeclarationError = true; - 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_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); - } - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - // 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 === 148 /* Parameter */ && - (resolver.isRequiredInitializedParameter(declaration) || - resolver.isOptionalUninitializedParameterProperty(declaration)); - if (type && !shouldUseResolverType) { - // Write the type - emitType(type); - } - else { - errorNameNode = declaration.name; - var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | - 2048 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); - errorNameNode = undefined; - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - // Write the type - emitType(signature.type); - } - else { - errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - errorNameNode = undefined; - } - } - function emitLines(nodes) { - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var node = nodes_6[_i]; - emit(node); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; - if (!canEmitFn || canEmitFn(node)) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(node); - } - } - } - function emitCommaList(nodes, eachNodeEmitFn, canEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); - } - function writeJsDocComments(declaration) { - if (declaration) { - var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - // 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) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 135 /* ObjectKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 173 /* ThisType */: - case 177 /* LiteralType */: - return writeTextOfNode(currentText, type); - case 205 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(type); - case 161 /* TypeReference */: - return emitTypeReference(type); - case 164 /* TypeQuery */: - return emitTypeQuery(type); - case 166 /* ArrayType */: - return emitArrayType(type); - case 167 /* TupleType */: - return emitTupleType(type); - case 168 /* UnionType */: - return emitUnionType(type); - case 169 /* IntersectionType */: - return emitIntersectionType(type); - case 170 /* ConditionalType */: - return emitConditionalType(type); - case 171 /* InferType */: - return emitInferType(type); - case 172 /* ParenthesizedType */: - return emitParenType(type); - case 174 /* TypeOperator */: - return emitTypeOperator(type); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(type); - case 176 /* MappedType */: - return emitMappedType(type); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - return emitSignatureDeclarationWithJsDocComments(type); - case 165 /* TypeLiteral */: - return emitTypeLiteral(type); - case 71 /* Identifier */: - return emitEntityName(type); - case 145 /* QualifiedName */: - return emitEntityName(type); - case 160 /* TypePredicate */: - return emitTypePredicate(type); - } - function writeEntityName(entityName) { - if (entityName.kind === 71 /* Identifier */) { - writeTextOfNode(currentText, entityName); - } - else { - var left = entityName.kind === 145 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 145 /* QualifiedName */ ? entityName.right : entityName.name; - writeEntityName(left); - write("."); - writeTextOfNode(currentText, right); - } - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, - // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 241 /* 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 === 183 /* PropertyAccessExpression */); - emitEntityName(node.expression); - if (node.typeArguments) { - write("<"); - emitCommaList(node.typeArguments, emitType); - write(">"); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypePredicate(type) { - writeTextOfNode(currentText, type.parameterName); - write(" is "); - emitType(type.type); - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitIntersectionType(type) { - emitSeparatedList(type.types, " & ", emitType); - } - function emitConditionalType(node) { - emitType(node.checkType); - write(" extends "); - emitType(node.extendsType); - write(" ? "); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node.trueType; - emitType(node.trueType); - enclosingDeclaration = prevEnclosingDeclaration; - write(" : "); - emitType(node.falseType); - } - function emitInferType(node) { - write("infer "); - writeTextOfNode(currentText, node.typeParameter.name); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeOperator(type) { - write(ts.tokenToString(type.operator)); - write(" "); - emitType(type.type); - } - function emitIndexedAccessType(node) { - emitType(node.objectType); - write("["); - emitType(node.indexType); - write("]"); - } - function emitMappedType(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write("{"); - writeLine(); - increaseIndent(); - if (node.readonlyToken) { - write(node.readonlyToken.kind === 37 /* PlusToken */ ? "+readonly " : - node.readonlyToken.kind === 38 /* MinusToken */ ? "-readonly " : - "readonly "); - } - write("["); - writeEntityName(node.typeParameter.name); - write(" in "); - emitType(node.typeParameter.constraint); - write("]"); - if (node.questionToken) { - write(node.questionToken.kind === 37 /* PlusToken */ ? "+?" : - node.questionToken.kind === 38 /* MinusToken */ ? "-?" : - "?"); - } - write(": "); - emitType(node.type); - write(";"); - writeLine(); - decreaseIndent(); - write("}"); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - // write members - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentText = node.text; - currentLineMap = ts.getLineStarts(node); - currentIdentifiers = node.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(node); - enclosingDeclaration = node; - 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; - } - var count = 0; - while (true) { - count++; - var name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; - } - } - } - function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { - var tempVarName = getExportTempVariableName(baseName); - if (needsDeclare) { - write("declare "); - } - write("const "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - write(";"); - writeLine(); - return tempVarName; - } - function emitExportAssignment(node) { - if (ts.isSourceFile(node.parent)) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - } - if (node.expression.kind === 71 /* Identifier */) { - write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentText, node.expression); - } - else { - var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }, needsDeclare); - write(node.isExportEquals ? "export = " : "export default "); - write(tempVarName); - } - write(";"); - writeLine(); - // 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); - } - } - function isModuleElementVisible(node) { - return resolver.isDeclarationVisible(node); - } - function emitModuleElement(node, isModuleElementVisible) { - if (isModuleElementVisible) { - writeModuleElement(node); - } - else if (node.kind === 241 /* ImportEqualsDeclaration */ || - (node.parent.kind === 272 /* SourceFile */ && isCurrentFileExternalModule)) { - var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 272 /* SourceFile */) { - // Import declaration of another module that is visited async so lets put it in right spot - asynchronousSubModuleDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - else { - if (node.kind === 242 /* ImportDeclaration */) { - var importDeclaration = node; - if (importDeclaration.importClause) { - isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || - isVisibleNamedBinding(importDeclaration.importClause.namedBindings); - } - } - moduleElementDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - } - } - function writeModuleElement(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - return writeFunctionDeclaration(node); - case 212 /* VariableStatement */: - return writeVariableStatement(node); - case 234 /* InterfaceDeclaration */: - return writeInterfaceDeclaration(node); - case 233 /* ClassDeclaration */: - return writeClassDeclaration(node); - case 235 /* TypeAliasDeclaration */: - return writeTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: - return writeEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return writeModuleDeclaration(node); - case 241 /* ImportEqualsDeclaration */: - return writeImportEqualsDeclaration(node); - case 242 /* ImportDeclaration */: - return writeImportDeclaration(node); - default: - ts.Debug.fail("Unknown symbol kind"); - } - } - 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 === 272 /* SourceFile */) { - var modifiers = ts.getModifierFlags(node); - // If the node is exported - if (modifiers & 1 /* Export */) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - write("export "); - } - if (modifiers & 512 /* Default */) { - write("default "); - } - else if (node.kind !== 234 /* InterfaceDeclaration */ && needsDeclare) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(flags) { - if (flags & 8 /* Private */) { - write("private "); - } - else if (flags & 16 /* Protected */) { - write("protected "); - } - if (flags & 32 /* Static */) { - write("static "); - } - if (flags & 64 /* Readonly */) { - write("readonly "); - } - 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 /* Export */)) { - write("export "); - } - write("import "); - writeTextOfNode(currentText, node.name); - write(" = "); - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - emitExternalModuleSpecifier(node); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function isVisibleNamedBinding(namedBindings) { - if (namedBindings) { - if (namedBindings.kind === 244 /* NamespaceImport */) { - return resolver.isDeclarationVisible(namedBindings); - } - else { - return namedBindings.elements.some(function (namedImport) { return resolver.isDeclarationVisible(namedImport); }); - } - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1 /* Export */)) { - write("export "); - } - write("import "); - if (node.importClause) { - var currentWriterPos = writer.getTextPos(); - if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentText, node.importClause.name); - } - 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 === 244 /* NamespaceImport */) { - write("* as "); - writeTextOfNode(currentText, node.importClause.namedBindings.name); - } - else { - write("{ "); - emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); - write(" }"); - } - } - write(" from "); - } - emitExternalModuleSpecifier(node); - write(";"); - writer.writeLine(); - } - function emitExternalModuleSpecifier(parent) { - // 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 !== 237 /* ModuleDeclaration */; - var moduleSpecifier = parent.kind === 241 /* ImportEqualsDeclaration */ ? ts.getExternalModuleImportEqualsDeclarationExpression(parent) : - parent.kind === 237 /* ModuleDeclaration */ ? parent.name : parent.moduleSpecifier; - if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); - if (moduleName) { - write('"'); - write(moduleName); - write('"'); - return; - } - } - writeTextOfNode(currentText, moduleSpecifier); - } - function emitImportOrExportSpecifier(node) { - if (node.propertyName) { - writeTextOfNode(currentText, node.propertyName); - write(" as "); - } - writeTextOfNode(currentText, node.name); - } - 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) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - emitJsDocComments(node); - write("export "); - if (node.exportClause) { - write("{ "); - emitCommaList(node.exportClause.elements, emitExportSpecifier); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitExternalModuleSpecifier(node); - } - write(";"); - writer.writeLine(); - } - function writeModuleDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isGlobalScopeAugmentation(node)) { - write("global "); - } - else { - if (node.flags & 16 /* Namespace */) { - write("namespace "); - } - else { - write("module "); - } - if (ts.isExternalModuleAugmentation(node)) { - emitExternalModuleSpecifier(node); - } - else { - writeTextOfNode(currentText, node.name); - } - } - while (node.body && node.body.kind !== 238 /* ModuleBlock */) { - node = node.body; - write("."); - writeTextOfNode(currentText, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - if (node.body) { - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - else { - write(";"); - } - } - function writeTypeAliasDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function writeEnumDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentText, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentText, node.name); - var enumMemberValue = resolver.getConstantValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(ts.getTextOfConstantValue(enumMemberValue)); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 153 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - 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 === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - if (node.default && !isPrivateMethodTypeParameter(node)) { - write(" = "); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.default); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError); - } - } - 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 233 /* ClassDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 234 /* InterfaceDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 158 /* ConstructSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 157 /* CallSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 153 /* MethodDeclaration */: - case 152 /* 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 === 233 /* 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 232 /* FunctionDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - case 235 /* TypeAliasDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - } - else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { - write("null"); - } - function getHeritageClauseVisibilityError() { - var diagnosticMessage; - // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 233 /* 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 { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: ts.getNameOfDeclaration(node.parent.parent) - }; - } - } - } - function writeClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) { - emitPropertyDeclaration(param); - } - }); - } - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - var tempVarName; - if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { - 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 === 237 /* ModuleDeclaration */; })); - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.hasModifier(node, 128 /* Abstract */)) { - write("abstract "); - } - write("class "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - if (baseTypeNode) { - if (!ts.isEntityNameExpression(baseTypeNode.expression)) { - write(" extends "); - write(tempVarName); - if (baseTypeNode.typeArguments) { - write("<"); - emitCommaList(baseTypeNode.typeArguments, emitType); - write(">"); - } - } - else { - emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); - } - } - emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(ts.getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function writeInterfaceDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); - if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); - } - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - emitJsDocComments(node); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - emitVariableDeclaration(node); - 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 !== 230 /* VariableDeclaration */ || isVariableDeclarationVisible(node)) { - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */) && node.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (resolver.isLiteralConstDeclaration(node)) { - write(" = "); - resolver.writeLiteralConstValue(node, writer); - } - else if (!ts.hasModifier(node, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 230 /* 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* 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 /* 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 === 233 /* ClassDeclaration */ || node.kind === 148 /* 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 : - 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; - } - } - } - function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : 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 !== 204 /* OmittedExpression */ && isVariableDeclarationVisible(element)) { - elements.push(element); - } - } - emitCommaList(elements, emitBindingElement); - } - function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - writeTextOfNode(currentText, bindingElement.name); - 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 (ts.hasType(node)) { - write(": "); - emitType(node.type); - } - } - function isVariableStatementVisible(node) { - 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; - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isLet(node.declarationList)) { - write("let "); - } - else if (ts.isConst(node.declarationList)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); - write(";"); - writeLine(); - } - function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - var accessorWithTypeAnnotation; - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - 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) { - // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 155 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 155 /* 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 === 233 /* 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 === 156 /* 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_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_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; - } - } - else { - if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - 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 /* 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: accessorWithTypeAnnotation.name - }; - } - } - function writeFunctionDeclaration(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 === 232 /* FunctionDeclaration */) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 153 /* MethodDeclaration */ || node.kind === 154 /* Constructor */) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - } - if (node.kind === 232 /* FunctionDeclaration */) { - write("function "); - writeTextOfNode(currentText, node.name); - } - else if (node.kind === 154 /* Constructor */) { - write("constructor"); - } - else { - 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 === 233 /* 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); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var closeParenthesizedFunctionType = false; - if (node.kind === 159 /* IndexSignature */) { - // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - write("["); - } - else { - if (node.kind === 154 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { - write("();"); - writeLine(); - return; - } - // Construct signature or constructor type write new Signature - if (node.kind === 158 /* ConstructSignature */ || node.kind === 163 /* ConstructorType */) { - write("new "); - } - else if (node.kind === 162 /* 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("("); - } - } - emitTypeParameters(node.typeParameters); - write("("); - } - // Parameters - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 159 /* IndexSignature */) { - write("]"); - } - else { - write(")"); - } - // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 162 /* FunctionType */ || node.kind === 163 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 165 /* TypeLiteral */) { - // Emit type literal signature return type only if specified - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 154 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - else if (closeParenthesizedFunctionType) { - write(")"); - } - function getReturnTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - 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 === 233 /* 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 : - 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 232 /* 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 : - 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; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - 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 { - writeTextOfNode(currentText, node.name); - } - if (resolver.isOptionalParameter(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!ts.hasModifier(node.parent, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - switch (node.parent.kind) { - case 154 /* 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 158 /* 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 157 /* 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 159 /* 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 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node.parent, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - 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 === 233 /* 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 : - 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 232 /* 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 : - 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; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - } - function emitBindingPattern(bindingPattern) { - // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 178 /* ObjectBindingPattern */) { - write("{"); - emitCommaList(bindingPattern.elements, emitBindingElement); - write("}"); - } - else if (bindingPattern.kind === 179 /* ArrayBindingPattern */) { - write("["); - var elements = bindingPattern.elements; - emitCommaList(elements, emitBindingElement); - if (elements && elements.hasTrailingComma) { - write(", "); - } - write("]"); - } - } - function emitBindingElement(bindingElement) { - if (bindingElement.kind === 204 /* 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, ,]) {} - // tslint:disable-next-line no-double-space - // emit : function foo([ , x, , ]) {} - write(" "); - } - else if (bindingElement.kind === 180 /* 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 /* 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("..."); - } - writeTextOfNode(currentText, bindingElement.name); - } - } - } - } - } - function emitNode(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 237 /* ModuleDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 234 /* InterfaceDeclaration */: - case 233 /* ClassDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: - return emitModuleElement(node, isModuleElementVisible(node)); - case 212 /* VariableStatement */: - return emitModuleElement(node, isVariableStatementVisible(node)); - case 242 /* ImportDeclaration */: - // Import declaration without import clause is visible, otherwise it is not visible - return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 248 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return writeFunctionDeclaration(node); - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 159 /* IndexSignature */: - return emitSignatureDeclarationWithJsDocComments(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return emitPropertyDeclaration(node); - case 271 /* EnumMember */: - return emitEnumMemberDeclaration(node); - case 247 /* ExportAssignment */: - return emitExportAssignment(node); - case 272 /* 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, - /*isAbsolutePathAnUrl*/ false); - referencesOutput += "/// " + newLine; - } - 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 === 273 /* Bundle */; - if (isBundledEmit && !addBundledFileReference) { - return; - } - ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); - declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; - addedBundledEmitReference = isBundledEmit; - } - } - } - /* @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 || emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var declarationOutput = emitDeclarationResult.referencesOutput - + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); - } - return emitSkipped; - 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); - declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); - return declarationOutput; - } - } - ts.writeDeclarationFile = writeDeclarationFile; -})(ts || (ts = {})); /// /// -/// /// /// var ts; @@ -71231,10 +72383,8 @@ var ts; var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var bundle = ts.createBundle(sourceFiles); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; } @@ -71243,10 +72393,7 @@ var ts; else { for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { var sourceFile = sourceFiles_1[_a]; - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); if (result) { return result; } @@ -71254,8 +72401,29 @@ var ts; } } ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 273 /* Bundle */) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + else { + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJavaScript(sourceFile); + var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; + return (options.sourceMap && !options.inlineSourceMap) ? 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. @@ -71274,51 +72442,31 @@ var ts; } return ".js" /* Js */; } - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 273 /* 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); - var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); var writer = ts.createTextWriter(newLine); var sourceMap = ts.createSourceMapWriter(host, writer); + var declarationSourceMap = ts.createSourceMapWriter(host, writer, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + }); var currentSourceFile; var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; - var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); - // 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); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); - // Clean up emit nodes on parse tree - transform.dispose(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -71326,19 +72474,9 @@ var ts; sourceMaps: sourceMapDataList }; 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 && !compilerOptions.emitDeclarationOnly) { - if (!emitOnlyDtsFiles) { - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); - } - } - else { - emitSkipped = true; - } - if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; - } + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { emittedFilesList.push(jsFilePath); @@ -71351,11 +72489,76 @@ var ts; } } } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Make sure not to write js file and source map file if any of them cannot be written + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + emitSkipped = true; + return; + } + if (emitOnlyDtsFiles) { + return; + } + // 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, + }); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true }), { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // sourcemap hooks + onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: declarationSourceMap.emitPos, + onSetSourceFile: setSourceFileForDeclarationSourceMaps, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + } + declarationTransform.dispose(); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 272 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); + mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { bundledHelpers = ts.createMap(); isOwnFileEmit = false; @@ -71366,22 +72569,18 @@ var ts; printer.writeFile(sourceFile, writer); } writer.writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); + var sourceMappingURL = mapRecorder.getSourceMappingURL(); if (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(), /*writeByteOrderMark*/ false, sourceFiles); - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); + if (sourceMapFilePath) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state - sourceMap.reset(); + mapRecorder.reset(); writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; @@ -71391,6 +72590,10 @@ var ts; currentSourceFile = node; sourceMap.setSourceFile(node); } + function setSourceFileForDeclarationSourceMaps(node) { + currentSourceFile = node; + declarationSourceMap.setSourceFile(node); + } function emitHelpers(node, writeLines) { var helpersEmitted = false; var bundle = node.kind === 273 /* Bundle */ ? node : undefined; @@ -71528,6 +72731,7 @@ var ts; emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpersIndirect(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { var sourceFile = _b[_a]; print(0 /* SourceFile */, sourceFile, sourceFile); @@ -71885,6 +73089,8 @@ var ts; // Enum case 271 /* EnumMember */: return emitEnumMember(node); + // JSDoc nodes (ignored) + // Transformation nodes (ignored) } // If the node is an expression, try to emit it as an expression with // substitution. @@ -72080,7 +73286,8 @@ var ts; else { emitTypeAnnotation(node.type); } - emitInitializer(node.initializer); + // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); } function emitDecorator(decorator) { writePunctuation("@"); @@ -72102,8 +73309,9 @@ var ts; emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); + emitIfPresent(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { @@ -72222,7 +73430,7 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); writePunctuation("}"); } @@ -72237,7 +73445,7 @@ var ts; } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 336 /* TupleTypeElements */); + emitList(node, node.elementTypes, 272 /* TupleTypeElements */); writePunctuation("]"); } function emitUnionType(node) { @@ -72348,7 +73556,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } // // Expressions @@ -72385,7 +73593,10 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - writePunctuation(shouldEmitDotDot ? ".." : "."); + if (shouldEmitDotDot) { + writePunctuation("."); + } + emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -72411,9 +73622,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - writePunctuation("["); + var openPos = emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - writePunctuation("]"); + emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); @@ -72421,7 +73632,7 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - writeKeyword("new"); + emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); @@ -72439,9 +73650,9 @@ var ts; emitExpression(node.expression); } function emitParenthesizedExpression(node) { - writePunctuation("("); + var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -72459,22 +73670,22 @@ var ts; emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - writeKeyword("delete"); + emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - writeKeyword("typeof"); + emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - writeKeyword("void"); + emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - writeKeyword("await"); + emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); } @@ -72542,7 +73753,7 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - writeKeyword("yield"); + emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } @@ -72586,17 +73797,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); - // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; emitList(node, node.statements, format); + emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */)); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -72611,15 +73818,15 @@ var ts; writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 215 /* IfStatement */) { writeSpace(); emit(node.elseStatement); @@ -72629,8 +73836,15 @@ var ts; } } } + function emitWhileClause(node, startPos) { + var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } function emitDoStatement(node) { - writeKeyword("do"); + emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { writeSpace(); @@ -72638,55 +73852,48 @@ var ts; else { writeLineOrSpace(node); } - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(");"); + emitWhileClause(node, node.statement.end); + writePunctuation(";"); } function emitWhileStatement(node) { - writeKeyword("while"); - writeSpace(); - writePunctuation("("); - emitExpression(node.expression); - writePunctuation(")"); + emitWhileClause(node, node.pos); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); + var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - writeSemicolon(); + pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.condition); - writeSemicolon(); + pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node); emitExpressionWithLeadingSpace(node.incrementor); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("in"); + emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); emitWithTrailingSpace(node.awaitModifier); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - writeKeyword("of"); + emitTokenWithComment(144 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -72700,22 +73907,34 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node); emitWithLeadingSpace(node.label); writeSemicolon(); } - function emitTokenWithComment(token, pos, writer, contextNode) { - var node = contextNode && ts.getParseTreeNode(contextNode); - if (node && node.kind === contextNode.kind) { + function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { + var node = ts.getParseTreeNode(contextNode); + var isSimilarNode = node && node.kind === contextNode.kind; + var startPos = pos; + if (isSimilarNode) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); - if (node && node.kind === contextNode.kind) { + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { + var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer, pos); + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; @@ -72726,35 +73945,35 @@ var ts; writeSemicolon(); } function emitWithStatement(node) { - writeKeyword("with"); + var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); - writePunctuation("("); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writePunctuation(")"); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - writePunctuation(":"); + emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node); writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - writeKeyword("throw"); + emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node); emitExpressionWithLeadingSpace(node.expression); writeSemicolon(); } function emitTryStatement(node) { - writeKeyword("try"); + emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node); writeSpace(); emit(node.tryBlock); if (node.catchClause) { @@ -72763,7 +73982,7 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - writeKeyword("finally"); + emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); writeSpace(); emit(node.finallyBlock); } @@ -72778,7 +73997,7 @@ var ts; function emitVariableDeclaration(node) { emit(node.name); emitTypeAnnotation(node.type); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); @@ -72916,7 +74135,7 @@ var ts; increaseIndent(); } emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); @@ -72969,6 +74188,8 @@ var ts; } emit(node.name); var body = node.body; + if (!body) + return writeSemicolon(); while (body.kind === 237 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); @@ -72979,23 +74200,21 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); - writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); + emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); + emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); emit(node.name); writeSpace(); - writePunctuation("="); + emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); writeSemicolon(); @@ -73010,12 +74229,12 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - writeKeyword("import"); + emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { emit(node.importClause); writeSpace(); - writeKeyword("from"); + emitTokenWithComment(142 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -73024,15 +74243,15 @@ var ts; function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - writePunctuation(","); + emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - writePunctuation("*"); + var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node); writeSpace(); emit(node.name); } @@ -73043,41 +74262,42 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isExportEquals) { - writeOperator("="); + emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node); } else { - writeKeyword("default"); + emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); emitExpression(node.expression); writeSemicolon(); } function emitExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - writePunctuation("*"); + nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node); } if (node.moduleSpecifier) { writeSpace(); - writeKeyword("from"); + var fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(142 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - writeKeyword("export"); + var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); - writeKeyword("as"); + nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node); writeSpace(); - writeKeyword("namespace"); + nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node); writeSpace(); emit(node.name); writeSemicolon(); @@ -73090,14 +74310,14 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); writeSpace(); - writeKeyword("as"); + emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node); writeSpace(); } emit(node.name); @@ -73123,10 +74343,7 @@ var ts; writePunctuation("<"); emitJsxTagName(node.tagName); writeSpace(); - // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); - } + emit(node.attributes); writePunctuation("/>"); } function emitJsxFragment(node) { @@ -73138,11 +74355,10 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); - // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); - emit(node.attributes); } + emit(node.attributes); } writePunctuation(">"); } @@ -73189,44 +74405,31 @@ var ts; // Clauses // function emitCaseClause(node) { - writeKeyword("case"); + emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); emitExpression(node.expression); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { - writeKeyword("default"); - writePunctuation(":"); - emitCaseOrDefaultClauseStatements(node, node.statements); + var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); } - function emitCaseOrDefaultClauseStatements(parentNode, statements) { + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { var emitAsSingleStatement = statements.length === 1 && ( // 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 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { + writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode); writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } + else { + emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode); + } emitList(parentNode, statements, format); } function emitHeritageClause(node) { @@ -73236,12 +74439,12 @@ var ts; emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); + emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); writeSpace(); } emit(node.block); @@ -73287,7 +74490,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer); + emitInitializer(node.initializer, node.name.end, node); } // // Top-level nodes @@ -73308,11 +74511,31 @@ var ts; } emitSourceFileWorker(node); } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.referencedFiles, node.typeReferenceDirectives); + } + function emitTripleSlashDirectives(files, types) { + for (var _a = 0, files_1 = files; _a < files_1.length; _a++) { + var directive = files_1[_a]; + write("/// "); + writeLine(); + } + for (var _b = 0, types_18 = types; _b < types_18.length; _b++) { + var directive = types_18[_b]; + write("/// "); + writeLine(); + } + } function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -73404,10 +74627,10 @@ var ts; emit(node); } } - function emitInitializer(node) { + function emitInitializer(node, equalCommentStartPos, container) { if (node) { writeSpace(); - writeOperator("="); + emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); emitExpression(node); } @@ -73455,7 +74678,7 @@ var ts; emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures return emitTypeArguments(parentNode, parentNode.typeArguments); } emitList(parentNode, typeParameters, 26896 /* TypeParameters */); @@ -73532,6 +74755,9 @@ var ts; } if (format & 7680 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); + if (isEmpty && !isUndefined) { + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + } } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -73639,6 +74865,9 @@ var ts; onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { + if (isEmpty && !isUndefined) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists + } writePunctuation(getClosingBracket(format)); } } @@ -73735,9 +74964,9 @@ var ts; } function writeLines(text) { var lines = text.split(/\r\n?|\n/g); - var indentation = guessIndentation(lines); - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var lineText = lines_1[_a]; + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var lineText = lines_2[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); @@ -73746,21 +74975,6 @@ var ts; } } } - function guessIndentation(lines) { - var indentation; - 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) { - indentation = i; - break; - } - } - } - } - return indentation; - } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { increaseIndent(); @@ -73984,7 +75198,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -74029,8 +75243,15 @@ var ts; * 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. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName) { + function makeUniqueName(baseName, optimistic) { + if (optimistic) { + if (isUniqueName(baseName)) { + generatedNames.set(baseName, true); + return baseName; + } + } // Find the first unique 'name_n', where n is a positive number if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { baseName += "_"; @@ -74118,6 +75339,8 @@ var ts; return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); + case 5 /* OptimisticUnique */: + return makeUniqueName(ts.idText(name), /*optimistic*/ true); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -74219,7 +75442,7 @@ var ts; if (failed) { return ""; } - if (!commonPathComponents) { + if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } return ts.getNormalizedPathFromPathComponents(commonPathComponents); @@ -74351,8 +75574,7 @@ var ts; } 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(); + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " 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; @@ -74377,8 +75599,9 @@ var ts; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } @@ -74409,8 +75632,8 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { @@ -74451,9 +75674,7 @@ var ts; output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); output += " - "; } - var categoryColor = getCategoryFormat(diagnostic.category); - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { @@ -74764,8 +75985,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var sourceFile = files_1[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -74787,13 +76008,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_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -75419,6 +76640,8 @@ var ts; case 185 /* CallExpression */: case 186 /* NewExpression */: case 205 /* ExpressionWithTypeArguments */: + case 254 /* JsxSelfClosingElement */: + case 255 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -75426,8 +76649,8 @@ var ts; } break; } - for (var _b = 0, nodes_8 = nodes; _b < nodes_8.length; _b++) { - var node = nodes_8[_b]; + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; walk(node); } } @@ -75512,9 +76735,9 @@ var ts; return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 9 /* StringLiteral */ - ? b.kind === 9 /* StringLiteral */ && a.text === b.text - : b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText; + return a.kind === 71 /* Identifier */ + ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 9 /* StringLiteral */ && a.text === b.text; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -75533,7 +76756,7 @@ var ts; && !file.isDeclarationFile) { // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; @@ -75551,63 +76774,54 @@ var ts; file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { - switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { - break; + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // 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 (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // 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(node.name); } - 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 237 /* 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); } - 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, /*inAmbientModule*/ true); - } + // 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, /*inAmbientModule*/ true); } } } + } } } function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - (imports || (imports = [])).push(node.arguments[0]); + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); } - else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) { - (imports || (imports = [])).push(node.arguments[0]); + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); } else { ts.forEachChild(node, collectDynamicImportOrRequireCalls); @@ -75706,6 +76920,7 @@ var ts; modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } + // See if we need to reprocess the imports due to prior skipped imports else if (file_1 && modulesWithElidedImports.get(file_1.path)) { if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports.set(file_1.path, false); @@ -75994,9 +77209,9 @@ var ts; if (options.out && options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } - if (options.mapRoot && !options.sourceMap) { + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { // Error to specify --mapRoot without --sourcemap - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { if (!options.declaration) { @@ -76006,6 +77221,9 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } + if (options.declarationMap && !options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } @@ -76021,14 +77239,14 @@ var ts; } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } 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)); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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) { @@ -76036,15 +77254,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - 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")); + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } // 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) { + options.mapRoot) { // there is --mapRoot specified // 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 @@ -76060,7 +77278,7 @@ var ts; } if (options.emitDeclarationOnly) { if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -76159,18 +77377,18 @@ var ts; } return ts.emptyArray; } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } function getCompilerOptionsObjectLiteralSyntax() { @@ -76188,11 +77406,11 @@ var ts; } return _compilerOptionsObjectLiteralSyntax; } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { var props = ts.getPropertyAssignment(objectLiteral, key1, key2); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); } return !!props.length; } @@ -77147,7 +78365,7 @@ var ts; createNewValue: createMissingFileWatch, // Files that are no longer missing (e.g. because they are no longer required) // should no longer be watched. - onDeleteValue: closeFileWatcher + onDeleteValue: ts.closeFileWatcher }); } ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; @@ -77190,75 +78408,74 @@ var ts; return program.isEmittedFile(file); } ts.isEmittedFileOfProgram = isEmittedFileOfProgram; - function addFileWatcher(host, file, cb) { - return host.watchFile(file, cb); + var WatchLogLevel; + (function (WatchLogLevel) { + WatchLogLevel[WatchLogLevel["None"] = 0] = "None"; + WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly"; + WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose"; + })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {})); + function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) { + return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory); } - 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); + ts.getWatchFactory = getWatchFactory; + function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) { + var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; + var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + return { + watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) { + return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) { + return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo); + }, + watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) { + return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo); + } + }; + function watchFilePath(host, file, callback, pollingInterval, path) { + return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval); } - 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); + } + function watchFile(host, file, callback, pollingInterval) { + return host.watchFile(file, callback, pollingInterval); + } + function watchDirectory(host, directory, callback, flags) { + return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0); + } + function getCreateFileWatcher(watchLogLevel, addWatch) { + switch (watchLogLevel) { + case WatchLogLevel.None: + return addWatch; + case WatchLogLevel.TriggerOnly: + return createFileWatcherWithTriggerLogging; + case WatchLogLevel.Verbose: + return createFileWatcherWithLogging; + } + } + function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); return { close: function () { - if (!logOnlyTrigger) { - log(watcherCaption + "Close: " + info); - } + log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)); watcher.close(); } }; } - function closeFileWatcher(watcher) { - watcher.close(); + function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + return addWatch(host, file, function (fileName, cbOptional) { + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(triggerredInfo); + var start = ts.timestamp(); + cb(fileName, cbOptional, passThrough); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + }, flags); + } + function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : ""); } - ts.closeFileWatcher = closeFileWatcher; function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } @@ -77275,15 +78492,17 @@ var ts; var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // 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 nonRelaticeModuleNameCache = ts.createMap(); + var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); - var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); - var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -77356,6 +78575,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); + nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); } function finishCachingPerDirectoryResolution() { @@ -77369,7 +78589,7 @@ var ts; clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); // 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; @@ -77415,15 +78635,8 @@ var ts; 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) { + watchFailedLookupLocationOfResolution(resolution); + if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { @@ -77503,8 +78716,9 @@ var ts; if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { return { dir: rootDir, dirPath: rootPath }; } - var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); - var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); + } + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // 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); @@ -77530,78 +78744,91 @@ var ts; 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; - } + function watchFailedLookupLocationOfResolution(resolution) { + // No need to set the resolution refCount + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + 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]; + if (resolution.refCount !== undefined) { + resolution.refCount++; + return; + } + resolution.refCount = 1; + var failedLookupLocations = resolution.failedLookupLocations; + var setAtRoot = false; + for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { + var failedLookupLocation = failedLookupLocations_1[_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; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; if (!ignore) { - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - if (dirWatcher) { - dirWatcher.refCount++; + // 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); + } + if (dirPath === rootPath) { + setAtRoot = true; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + setDirectoryWatcher(dir, dirPath); } } } + if (setAtRoot) { + setDirectoryWatcher(rootDir, rootPath); + } + } + function setDirectoryWatcher(dir, dirPath) { + 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); + if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + return; } - } - function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { - var failedLookupLocations = _a.failedLookupLocations; - for (var i = startIndex; i < failedLookupLocations.length; i++) { - var failedLookupLocation = failedLookupLocations[i]; + resolution.refCount--; + if (resolution.refCount) { + return; + } + var failedLookupLocations = resolution.failedLookupLocations; + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + if (!ignore) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - 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--; - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + function removeDirectoryWatcher(dirPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { @@ -77688,7 +78915,8 @@ var ts; // 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)) { + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory isChangedFailedLookupLocation = function (location) { var locationPath = resolutionHost.toPath(location); @@ -77717,7 +78945,17 @@ var ts; function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); } - function createTypeRootsWatch(_typeRootPath, typeRoot) { + function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { + if (allFilesHaveInvalidatedResolution) { + return undefined; + } + if (isInDirectoryPath(rootPath, typeRootPath)) { + return rootPath; + } + var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + } + function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); @@ -77729,6 +78967,12 @@ var ts; // 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(); + // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered + // So handle to failed lookup locations here as well to ensure we are invalidating resolutions + var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath); + if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } }, 1 /* Recursive */); } /** @@ -77802,6 +79046,7 @@ var ts; ts.createDiagnosticReporter = createDiagnosticReporter; function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && + !options.preserveWatchOutput && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code && !options.extendedDiagnostics && !options.diagnostics) { @@ -78040,16 +79285,15 @@ var ts; parseConfigFile(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); - var writeLog = loggingEnabled ? trace : ts.noop; - var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; - var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; - var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : + compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectoryWorker = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var newLine = updateNewLine(); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, writeLog); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High); } var compilerHost = { // Members for CompilerHost @@ -78127,7 +79371,7 @@ var ts; return builderProgram; } // Compile the program - if (loggingEnabled) { + if (watchLogLevel !== ts.WatchLogLevel.None) { writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); @@ -78208,7 +79452,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); } } else { @@ -78222,7 +79466,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -78276,6 +79520,9 @@ var ts; (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); } else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } sourceFilesCache.delete(oldSourceFile.path); resolutionCache.removeResolutionsOfFile(oldSourceFile.path); } @@ -78360,10 +79607,10 @@ var ts; } } function watchDirectory(directory, cb, flags) { - return watchDirectoryWorker(host, directory, cb, flags, writeLog); + return watchDirectoryWorker(host, directory, cb, flags); } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -78495,6 +79742,13 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, { name: "watch", shortName: "w", @@ -78576,9 +79830,10 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "es2018.promise": "lib.es2018.promise.d.ts", + "es2018.regexp": "lib.es2018.regexp.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, @@ -78618,6 +79873,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, { name: "emitDeclarationOnly", type: "boolean", @@ -79609,7 +80871,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_6 = function (name) { + var _loop_7 = 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 @@ -79638,7 +80900,7 @@ var ts; } }; for (var name in options) { - _loop_6(name); + _loop_7(name); } return result; } @@ -80230,7 +81492,7 @@ var ts; function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); - var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; // 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. @@ -80420,22 +81682,6 @@ 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. @@ -80446,7 +81692,7 @@ var ts; for (var key in opts) { if (opts.hasOwnProperty(key)) { var type = getOptionFromName(key); - if (type !== undefined) { + if (type !== undefined) { // Ignore unknown options out[key] = getOptionValueWithEmptyStrings(opts[key], type); } } @@ -80456,11 +81702,11 @@ var ts; ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; function getOptionValueWithEmptyStrings(value, option) { switch (option.type) { - case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "". + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". return ""; - case "string":// Could be any arbitrary string -- use empty string instead. + case "string": // Could be any arbitrary string -- use empty string instead. return ""; - case "number":// Allow numbers, but be sure to check it's actually a 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 : ""; @@ -80504,6 +81750,8 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.defaultPreferences = {}; var TextChange = /** @class */ (function () { function TextChange() { } @@ -80896,16 +82144,13 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 71 /* Identifier */ && - (node.parent.kind === 222 /* BreakStatement */ || node.parent.kind === 221 /* ContinueStatement */) && - node.parent.label === node; + return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 /* Identifier */ && - node.parent.kind === 226 /* LabeledStatement */ && - node.parent.label === node; + return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node; } + ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement; function isLabelName(node) { return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } @@ -81042,6 +82287,8 @@ var ts; case 5 /* Property */: // static method / property return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 6 /* Prototype */: + return "local class" /* localClassElement */; default: { ts.assertTypeIsNever(kind); return "" /* unknown */; @@ -81271,12 +82518,7 @@ var ts; // 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; - } - }); + var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); }); // 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; @@ -81516,6 +82758,102 @@ var ts; return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) { + var tokenKind = token.kind; + var remainingMatchingTokens = 0; + while (true) { + token = findPrecedingToken(token.getFullStart(), sourceFile); + if (!token) { + return undefined; + } + if (token.kind === matchingTokenKind) { + if (remainingMatchingTokens === 0) { + return token; + } + remainingMatchingTokens--; + } + else if (token.kind === tokenKind) { + remainingMatchingTokens++; + } + } + } + ts.findPrecedingMatchingToken = findPrecedingMatchingToken; + function isPossiblyTypeArgumentPosition(token, sourceFile) { + // This function determines if the node could be type argument position + // Since during editing, when type argument list is not complete, + // the tree could be of any shape depending on the tokens parsed before current node, + // scanning of the previous identifier followed by "<" before current node would give us better result + // Note that we also balance out the already provided type arguments, arrays, object literals while doing so + var remainingLessThanTokens = 0; + while (token) { + switch (token.kind) { + case 27 /* LessThanToken */: + // Found the beginning of the generic argument expression + token = findPrecedingToken(token.getFullStart(), sourceFile); + var tokenIsIdentifier = token && ts.isIdentifier(token); + if (!remainingLessThanTokens || !tokenIsIdentifier) { + return tokenIsIdentifier; + } + remainingLessThanTokens--; + break; + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + remainingLessThanTokens = +3; + break; + case 46 /* GreaterThanGreaterThanToken */: + remainingLessThanTokens = +2; + break; + case 29 /* GreaterThanToken */: + remainingLessThanTokens++; + break; + case 18 /* CloseBraceToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); + if (!token) + return false; + break; + case 20 /* CloseParenToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); + if (!token) + return false; + break; + case 22 /* CloseBracketToken */: + // This can be object type, skip untill we find the matching open brace token + // Skip untill the matching open brace token + token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); + if (!token) + return false; + break; + // Valid tokens in a type name. Skip. + case 26 /* CommaToken */: + case 36 /* EqualsGreaterThanToken */: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 103 /* TypeOfKeyword */: + case 85 /* ExtendsKeyword */: + case 128 /* KeyOfKeyword */: + case 23 /* DotToken */: + case 49 /* BarToken */: + case 55 /* QuestionToken */: + case 56 /* ColonToken */: + break; + default: + if (ts.isTypeNode(token)) { + break; + } + // Invalid token in type + return false; + } + token = findPrecedingToken(token.getFullStart(), sourceFile); + } + return false; + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; /** * Returns true if the cursor at position in sourceFile is within a comment. * @@ -81712,16 +83050,6 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; - /** Add a value to a set, and return true if it wasn't already present. */ - function addToSeen(seen, key) { - key = String(key); - if (seen.has(key)) { - return false; - } - seen.set(key, true); - return true; - } - ts.addToSeen = addToSeen; function getSnapshotText(snap) { return snap.getText(0, snap.getLength()); } @@ -82019,32 +83347,35 @@ var ts; */ /* @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); - } - } + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); } ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + /* @internal */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + /* @internal */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } + function getFirstChild(node) { + return node.forEachChild(function (child) { return child; }); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -82258,7 +83589,7 @@ var ts; case 13 /* NoSubstitutionTemplateLiteral */: return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; default: - throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; @@ -82365,7 +83696,7 @@ var ts; case 0 /* None */: return { prefix: "" }; default: - throw ts.Debug.assertNever(lexState); + return ts.Debug.assertNever(lexState); } } function isBinaryExpressionOperatorToken(token) { @@ -82924,29 +84255,38 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function createPathCompletion(name, kind, span) { - return { name: name, kind: kind, span: span }; + function nameAndKind(name, kind) { + return { name: name, kind: kind }; + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind; + return ({ name: name, kind: kind, span: span }); + }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker)); + } + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + function getStringLiteralCompletionsFromModuleNamesWorker(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(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); } } else { // Check for node modules - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } - 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 @@ -82961,21 +84301,21 @@ var ts; // 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) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); var result = []; for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, host, exclude, result); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); } 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) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -83004,8 +84344,8 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var filePath = files_2[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; @@ -83016,7 +84356,7 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createPathCompletion(foundFile, "script" /* scriptElement */, span)); + result.push(nameAndKind(foundFile, "script" /* scriptElement */)); }); } // If possible, get folder completion as well @@ -83025,7 +84365,7 @@ var ts; 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(createPathCompletion(directoryName, "directory" /* directory */, span)); + result.push(nameAndKind(directoryName, "directory" /* directory */)); } } } @@ -83038,26 +84378,26 @@ var ts; * 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) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; var fileExtensions = ts.getSupportedExtensions(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (name, kind) { + var _loop_8 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { - result.push(createPathCompletion(name, kind, span)); + result.push(nameAndKind(name, kind)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_7(name, kind); + _loop_8(name, kind); } } } @@ -83066,14 +84406,14 @@ var ts; 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); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); } }); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { var moduleName = _d[_c]; - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } return result; } @@ -83180,23 +84520,13 @@ var ts; } 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); - return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); - } - 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; - } + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) + : undefined; + return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); @@ -83212,7 +84542,7 @@ var ts; try { typeRoots = ts.getEffectiveTypeRoots(options, host); } - catch (_b) { } + catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; @@ -83244,7 +84574,7 @@ var ts; } function pushResult(moduleName) { if (!seen.has(moduleName)) { - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); seen.set(moduleName, true); } } @@ -83308,9 +84638,11 @@ var ts; } // Replace everything after the last directory seperator that appears function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); } // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) function isPathRelativeToScript(path) { @@ -83360,7 +84692,7 @@ var ts; try { return ts.directoryProbablyExists(path, host); } - catch (_a) { } + catch ( /*ignore*/_a) { /*ignore*/ } return undefined; } function tryIOAndConsumeErrors(host, toApply) { @@ -83371,7 +84703,7 @@ var ts; try { return toApply && toApply.apply(host, args); } - catch (_a) { } + catch ( /*ignore*/_a) { /*ignore*/ } return undefined; } })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); @@ -83387,11 +84719,18 @@ var ts; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { + var GlobalsSearch; + (function (GlobalsSearch) { + GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue"; + GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; + GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; + })(GlobalsSearch || (GlobalsSearch = {})); + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && convertPathCompletions(entries); @@ -83400,19 +84739,19 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log); + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, preferences, compilerOptions.target); if (!completionData) { return undefined; } switch (completionData.kind) { case 0 /* Data */: - return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); case 1 /* JsDocTagName */: // If the current position is a jsDoc tag name, only tag names should be provided for completion return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); @@ -83422,11 +84761,11 @@ var ts; case 3 /* JsDocParameterName */: return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); default: - throw ts.Debug.assertNever(completionData); + return ts.Debug.assertNever(completionData); } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log) { + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -83435,12 +84774,12 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "var" /* variableElement */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } default: return ts.Debug.assertNever(completion); @@ -83458,8 +84797,8 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.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. @@ -83477,14 +84816,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, 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, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -83494,7 +84833,7 @@ var ts; if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isMemberCompletionKind(kind) { switch (kind) { @@ -83523,7 +84862,7 @@ var ts; } }); } - function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); if (!info) { return undefined; @@ -83531,12 +84870,12 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (includeInsertTextCompletions) { + if (preferences.includeCompletionsWithInsertText) { if (origin && origin.type === "this-type") { - insertText = needsConvertPropertyAccess ? "this[" + quote(name) + "]" : "this." + name; + insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; } else if (needsConvertPropertyAccess) { - insertText = "[" + quote(name) + "]"; + insertText = "[" + quote(name, preferences) + "]"; var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; @@ -83551,7 +84890,7 @@ var ts; } } } - if (insertText !== undefined && !includeInsertTextCompletions) { + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -83573,9 +84912,17 @@ var ts; replacementSpan: replacementSpan, }; } - function quote(text) { - // TODO: GH#20619 Use configured quote style - return JSON.stringify(text); + function quote(text, preferences) { + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || @@ -83587,7 +84934,7 @@ var ts; function getSourceFromOrigin(origin) { return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. @@ -83597,7 +84944,7 @@ var ts; for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { var symbol = symbols_4[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } @@ -83663,7 +85010,7 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeFromTypeNode(node.parent.parent.objectType).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); default: return undefined; } @@ -83681,8 +85028,7 @@ var ts; // foo({ // '/*completion position*/' // }); - var type = typeChecker.getContextualType(node.parent.parent); - return { kind: 1 /* Properties */, symbols: type && type.getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); } return fromContextualType(); case 184 /* ElementAccessExpression */: { @@ -83694,13 +85040,13 @@ var ts; // } // let a: A; // a['/*completion position*/'] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeAtLocation(expression).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); } return undefined; } case 185 /* CallExpression */: case 186 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { var argumentInfo_1 = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -83733,6 +85079,9 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker), typeChecker) }; } } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } function getStringLiteralTypes(type, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 32768 /* TypeParameter */) { @@ -83746,7 +85095,7 @@ var ts; } 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, includeInsertTextCompletions: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } @@ -83771,9 +85120,16 @@ var ts; || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; } - function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName, preferences) { var typeChecker = program.getTypeChecker(); var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker); + } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); switch (symbolCompletion.type) { @@ -83792,40 +85148,46 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, 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 }; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, codeActions, sourceDisplay); } - case "none": { + case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. - if (allKeywordsCompletions().some(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 allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createCompletionDetails(name, "" /* none */, "keyword" /* keyword */, [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)]) : undefined; } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo && symbolOriginInfo.type === "export" - ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) - : { codeActions: undefined, sourceDisplay: undefined }; + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, codeActions, sourceDisplay) { + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || symbolOriginInfo.type !== "export") { + return { codeActions: undefined, sourceDisplay: undefined }; + } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { @@ -83843,7 +85205,6 @@ var ts; var CompletionKind; (function (CompletionKind) { CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; - /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */ CompletionKind[CompletionKind["Global"] = 1] = "Global"; CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; @@ -83920,7 +85281,7 @@ var ts; function isModuleSymbol(symbol) { return symbol.declarations.some(function (d) { return d.kind === 272 /* SourceFile */; }); } - function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, preferences, target) { var start = ts.timestamp(); 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.) @@ -83930,6 +85291,7 @@ var ts; var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); var insideJsDocTagTypeExpression = false; + var isInSnippetScope = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { @@ -84103,9 +85465,9 @@ var ts; getTypeScriptMemberSymbols(); } else if (isRightOfOpenTag) { - var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNames(), "getJsxIntrinsicTagNames() should all be defined"); + var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); })); } else { symbols = tagSymbols; @@ -84130,7 +85492,7 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, position, sourceFile, typeChecker); - return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 287 /* JSDocParameterTag */: @@ -84147,6 +85509,7 @@ var ts; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile)); if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { @@ -84156,7 +85519,7 @@ var ts; var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; - var isValidAccess = isRhsOfImportDeclaration ? + var isValidAccess = allowTypeOrValue ? // 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; @@ -84179,6 +85542,7 @@ var ts; } } function addTypeProperties(type) { + isNewIdentifierLocation = hasIndexSignature(type); 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 @@ -84197,50 +85561,42 @@ var ts; } } function tryGetGlobalSymbols() { - var objectLikeContainer; - var namedImportsOrExports; - var classLikeContainer; - var jsxContainer; - if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { - 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 - completionKind = 5 /* None */; - // Declaring new property/method/accessor - isNewIdentifierLocation = true; - // 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 === 254 /* JsxSelfClosingElement */) || (jsxContainer.kind === 255 /* 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); - completionKind = 3 /* MemberLike */; - isNewIdentifierLocation = false; - return true; - } - } - } + var result = tryGetObjectLikeCompletionSymbols() + || tryGetImportOrExportClauseCompletionSymbols() + || tryGetConstructorCompletion() + || tryGetClassLikeCompletionSymbols() + || tryGetJsxCompletionSymbols() + || (getGlobalCompletions(), 1 /* Success */); + return result === 1 /* Success */; + } + function tryGetConstructorCompletion() { + if (!tryGetConstructorLikeCompletionContainer(contextToken)) + return 0 /* Continue */; + // no members, only keywords + completionKind = 5 /* None */; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 3 /* ConstructorParameterKeywords */; + return 1 /* Success */; + } + function tryGetJsxCompletionSymbols() { + var jsxContainer = tryGetContainingJsxElement(contextToken); + // Cursor is inside a JSX self-closing element or opening element + var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + if (!attrsType) + return 0 /* Continue */; + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); + completionKind = 3 /* MemberLike */; + isNewIdentifierLocation = false; + return 1 /* Success */; + } + function getGlobalCompletions() { if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 3 /* FunctionLikeBodyKeywords */; + keywordFilters = 4 /* FunctionLikeBodyKeywords */; } // Get all entities in the current scope. - completionKind = 5 /* None */; + completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -84274,13 +85630,11 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (isGlobalCompletionScope(scopeNode)) { - completionKind = 1 /* Global */; - } - var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + isInSnippetScope = isSnippetScope(scopeNode); + var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (options.includeInsertTextCompletions && scopeNode.kind !== 272 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 272 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { @@ -84290,13 +85644,13 @@ var ts; } } } - if (options.includeExternalModuleExports) { + // Don't suggest import completions for a commonjs-only module + if (preferences.includeCompletionsForModuleExports && !(sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator)) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } filterGlobalCompletion(symbols); - return true; } - function isGlobalCompletionScope(scopeNode) { + function isSnippetScope(scopeNode) { switch (scopeNode.kind) { case 272 /* SourceFile */: case 200 /* TemplateExpression */: @@ -84308,9 +85662,10 @@ var ts; } } function filterGlobalCompletion(symbols) { - var isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - if (isTypeCompletion) - keywordFilters = 4 /* TypeKeywords */; + var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile); + if (isTypeOnlyCompletion) + keywordFilters = 5 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -84322,19 +85677,22 @@ var ts; if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); } - if (isTypeCompletion) { + if (allowTypes) { // Its a type, but you can reach it by namespace.type as well - return symbolCanBeReferencedAtTypeLocation(symbol); + var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); + if (symbolAllowedAsType || isTypeOnlyCompletion) { + return symbolAllowedAsType; + } } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); }); } function isContextTokenValueLocation(contextToken) { return contextToken && contextToken.kind === 103 /* TypeOfKeyword */ && - contextToken.parent.kind === 164 /* TypeQuery */; + (contextToken.parent.kind === 164 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { @@ -84358,7 +85716,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 793064 /* Type */) { + if (symbol.flags & 67901928 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -84472,7 +85830,7 @@ var ts; || containingNodeKind === 159 /* IndexSignature */ // [ | : string ] || containingNodeKind === 146 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 129 /* ModuleKeyword */: // module | - case 130 /* NamespaceKeyword */:// namespace | + case 130 /* NamespaceKeyword */: // namespace | return true; case 23 /* DotToken */: return containingNodeKind === 237 /* ModuleDeclaration */; // module A.| @@ -84491,10 +85849,10 @@ var ts; return containingNodeKind === 151 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": + switch (keywordForNode(previousToken)) { + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: return true; } } @@ -84526,18 +85884,19 @@ var ts; * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + function tryGetObjectLikeCompletionSymbols() { + var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); + if (!objectLikeContainer) + return 0 /* Continue */; // We're looking up possible property names from contextual/inferred/declared type. completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 182 /* 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; + return 2 /* Fail */; + isNewIdentifierLocation = hasIndexSignature(typeForObject); typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); existingMembers = objectLikeContainer.properties; } @@ -84547,7 +85906,7 @@ var ts; isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (!ts.isVariableLike(rootDeclaration)) - throw ts.Debug.fail("Root declaration is not variable-like."); + return ts.Debug.fail("Root declaration is not variable-like."); // 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. @@ -84565,7 +85924,7 @@ var ts; if (canGetType) { var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); if (!typeForObject) - return false; + return 2 /* Fail */; // 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; @@ -84575,7 +85934,7 @@ var ts; // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); } - return true; + return 1 /* Success */; } /** * Aggregates relevant symbols for completion in import clauses and export clauses @@ -84592,72 +85951,70 @@ var ts; * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + function tryGetImportOrExportClauseCompletionSymbols() { + var namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken); + if (!namedImportsOrExports) + return undefined; + // cursor is in an import clause + // try to show exported member for imported module var declarationKind = namedImportsOrExports.kind === 245 /* NamedImports */ ? 242 /* ImportDeclaration */ : 248 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { - return false; + return 2 /* Fail */; } completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { symbols = ts.emptyArray; - return true; + return 2 /* Fail */; } var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); - return true; + return 1 /* Success */; } /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. */ - function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + function tryGetClassLikeCompletionSymbols() { + var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location); + if (!decl) + return 0 /* Continue */; // We're looking up possible property names from parent type. completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - // 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 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 /* Private */; - break; - case "static": - classElementModifierFlags = classElementModifierFlags | 32 /* Static */; - break; - } - } - // No member list for private methods - if (!(classElementModifierFlags & 8 /* Private */)) { - var baseClassTypeToGetPropertiesFrom = void 0; - if (baseTypeNode) { - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); - if (classElementModifierFlags & 32 /* Static */) { - // Use static class to get property symbols from - baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); - } - } - 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); + keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + // If you're in an interface you don't want to repeat things from super-interface. So just stop here. + if (!ts.isClassLike(decl)) + return 1 /* Success */; + var classElement = contextToken.parent; + var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + // 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 /* Private */; + break; + case "static": + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + break; } } + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { + // List of property symbols of base type that are not private and already implemented + var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + }); + symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); + } + return 1 /* Success */; } /** * Returns the immediate owning object literal or binding pattern of a context token, @@ -84667,7 +86024,7 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */:// const x = { a: 0, | + case 26 /* CommaToken */: // const x = { a: 0, | var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; @@ -84685,7 +86042,7 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // import { | - case 26 /* CommaToken */:// import { a as 0, | + case 26 /* CommaToken */: // import { a as 0, | switch (contextToken.parent.kind) { case 245 /* NamedImports */: case 249 /* NamedExports */: @@ -84695,61 +86052,9 @@ var ts; } return undefined; } - function isFromClassElementDeclaration(node) { - return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); - } - function isParameterOfConstructorDeclaration(node) { - return ts.isParameter(node) && ts.isConstructorDeclaration(node.parent); - } function isConstructorParameterCompletion(node) { - return node.parent && - 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 /* OpenBraceToken */:// class c { | - if (ts.isClassLike(contextToken.parent)) { - return contextToken.parent; - } - break; - // class c {getValue(): number, | } - case 26 /* CommaToken */: - if (ts.isClassLike(contextToken.parent)) { - return contextToken.parent; - } - break; - // 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) && - (isClassMemberCompletionKeyword(contextToken.kind) || - isClassMemberCompletionKeywordText(contextToken.getText()))) { - return contextToken.parent.parent; - } - } - } - // class c { method() { } | method2() { } } - if (location && location.kind === 293 /* SyntaxList */ && ts.isClassLike(location.parent)) { - return location.parent; - } - return undefined; + return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent) + && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node)); } /** * Returns the immediate owning class declaration of a context token, @@ -84871,14 +86176,7 @@ var ts; return containingNodeKind === 267 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: - return containingNodeKind === 236 /* EnumDeclaration */ || // enum a { | - containingNodeKind === 234 /* InterfaceDeclaration */ || // interface a { | - containingNodeKind === 165 /* TypeLiteral */; // const x : { | - case 25 /* SemicolonToken */: - return containingNodeKind === 150 /* PropertySignature */ && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 234 /* InterfaceDeclaration */ || // interface a { f; | - contextToken.parent.parent.kind === 165 /* TypeLiteral */); // const x : { a; | + return containingNodeKind === 236 /* EnumDeclaration */; // enum a { | case 27 /* LessThanToken */: return containingNodeKind === 233 /* ClassDeclaration */ || // class A< | containingNodeKind === 203 /* ClassExpression */ || // var C = class D< | @@ -84901,7 +86199,7 @@ var ts; containingNodeKind === 244 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromClassElementDeclaration(contextToken)) { + if (isFromObjectTypeDeclaration(contextToken)) { return false; } // falls through @@ -84914,13 +86212,12 @@ var ts; case 110 /* LetKeyword */: case 76 /* ConstKeyword */: case 116 /* YieldKeyword */: - case 139 /* TypeKeyword */:// type htm| + case 139 /* 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)) { + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; } if (isConstructorParameterCompletion(contextToken)) { @@ -84929,28 +86226,28 @@ var ts; // - its name of the parameter and not being edited // eg. constructor(a |<- this shouldnt show completion if (!ts.isIdentifier(contextToken) || - isConstructorParameterCompletionKeywordText(contextToken.getText()) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || isCurrentlyEditingNode(contextToken)) { return false; } } // Previous token may have been a keyword that was converted to an identifier. - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": + switch (keywordForNode(contextToken)) { + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 75 /* ClassKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 83 /* EnumKeyword */: + case 89 /* FunctionKeyword */: + case 109 /* InterfaceKeyword */: + case 110 /* LetKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 115 /* StaticKeyword */: + case 104 /* VarKeyword */: + case 116 /* YieldKeyword */: return true; } return ts.isDeclarationName(contextToken) @@ -85029,7 +86326,7 @@ var ts; // 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); + existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } existingMemberNames.set(existingName, true); } @@ -85040,7 +86337,7 @@ var ts; * * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags */ - function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; @@ -85060,10 +86357,7 @@ var ts; continue; } // 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)) { + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { continue; } var existingName = ts.getPropertyNameForPropertyNameNode(m.name); @@ -85071,23 +86365,11 @@ var ts; existingMemberNames.set(existingName, true); } } - var result = []; - 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++) { - var property = properties_12[_i]; - if (isValidProperty(property, inValidModifierFlags)) { - result.push(property); - } - } - } - function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.escapedName) && - propertySymbol.getDeclarations() && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); - } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. @@ -85110,7 +86392,7 @@ var ts; return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { - return node.getStart() <= position && position <= node.getEnd(); + return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { @@ -85133,10 +86415,10 @@ var ts; // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2 /* PropertyAccess */: - case 5 /* None */: case 1 /* Global */: // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 5 /* None */: case 4 /* String */: return validIdentiferResult; default: @@ -85166,62 +86448,36 @@ var ts; return kind !== 140 /* UndefinedKeyword */; case 1 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* ConstructorParameterKeywords */: - return isConstructorParameterCompletionKeyword(kind); - case 3 /* FunctionLikeBodyKeywords */: - return isFunctionLikeBodyCompletionKeyword(kind); - case 4 /* TypeKeywords */: + case 2 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 3 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 4 /* FunctionLikeBodyKeywords */: + return !isClassMemberCompletionKeyword(kind); + case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); } })); } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 132 /* ReadonlyKeyword */; + } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: case 123 /* ConstructorKeyword */: - case 132 /* ReadonlyKeyword */: case 125 /* GetKeyword */: case 136 /* SetKeyword */: case 120 /* AsyncKeyword */: return true; + default: + return ts.isClassMemberModifier(kind); } } - function isClassMemberCompletionKeywordText(text) { - return isClassMemberCompletionKeyword(ts.stringToToken(text)); - } - function isConstructorParameterCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - } - } - function isConstructorParameterCompletionKeywordText(text) { - return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); - } - function isFunctionLikeBodyCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: - case 117 /* AbstractKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 140 /* UndefinedKeyword */: - return false; - } - return true; + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } function isEqualityOperatorKind(kind) { switch (kind) { @@ -85279,6 +86535,48 @@ var ts; }); return ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined"); } + /** + * 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 tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 293 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 25 /* SemicolonToken */: // class c {getValue(): number; | } + case 18 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 17 /* OpenBraceToken */: // class c { | + case 26 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && (ts.isClassElement(node.parent) || ts.isTypeElement(node.parent)) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -85309,30 +86607,17 @@ var ts; } function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); - return referenceEntries && convertReferencedSymbols(referenceEntries); - } - function convertReferencedSymbols(referenceEntries) { - var fileNameToDocumentHighlights = ts.createMap(); - for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { - var entry = referenceEntries_1[_i]; - var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span; - var highlightSpans = fileNameToDocumentHighlights.get(fileName); - if (!highlightSpans) { - fileNameToDocumentHighlights.set(fileName, highlightSpans = []); - } - highlightSpans.push(span_12); - } - return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) { + if (!referenceEntries) + return undefined; + var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); + return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; return ({ fileName: fileName, highlightSpans: highlightSpans }); }); } function getSyntacticDocumentHighlights(node, sourceFile) { var highlightSpans = getHighlightSpans(node, sourceFile); - if (!highlightSpans || highlightSpans.length === 0) { - return undefined; - } - return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { @@ -85873,7 +87158,9 @@ var ts; } else if (ts.isDefaultImport(direct)) { var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); - addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + if (!isAvailableThroughGlobal) { + addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + } directImports.push(direct); } else { @@ -86025,7 +87312,7 @@ var ts; 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) { + if (!isForRename) { // If renaming `foo`, don't touch `bar`, just `foo`. // Search locally for `bar`. addSearch(name, checker.getSymbolAtLocation(name)); } @@ -86121,8 +87408,8 @@ var ts; function forEachImport(sourceFile, action) { if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); } } else { @@ -86149,19 +87436,6 @@ var ts; }); } } - function importerFromModuleSpecifier(moduleSpecifier) { - var decl = moduleSpecifier.parent; - switch (decl.kind) { - case 185 /* CallExpression */: - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - return decl; - case 252 /* 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. @@ -86200,12 +87474,15 @@ var ts; return exportInfo(symbol, getExportKindForDeclaration(exportNode)); } } + // If we are in `export = a;` or `export default a;`, `parent` is the export assignment. else if (ts.isExportAssignment(parent)) { return getExportAssignmentExport(parent); } + // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. else if (ts.isExportAssignment(parent.parent)) { return getExportAssignmentExport(parent.parent); } + // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } @@ -86276,10 +87553,10 @@ var ts; return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } var decl = importedSymbol.valueDeclaration; - if (ts.isExportAssignment(decl)) { + if (ts.isExportAssignment(decl)) { // `export = class {}` return ts.Debug.assertDefined(decl.expression.symbol); } - else if (ts.isBinaryExpression(decl)) { + else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } return ts.Debug.fail(); @@ -86356,8 +87633,8 @@ var ts; if (parent.kind === 272 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 238 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent)); - return parent.parent; + ts.Debug.assert(parent.kind === 238 /* ModuleBlock */); + return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { return node.kind === 237 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; @@ -86379,12 +87656,13 @@ var ts; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { - var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {}); var checker = program.getTypeChecker(); return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { var definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. - return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }; + return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) }; }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; @@ -86404,9 +87682,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 269 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -86420,8 +87698,8 @@ var ts; } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options)); - return ts.map(x, toReferenceEntry); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { @@ -86429,60 +87707,50 @@ var ts; return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; - function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); - } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); } - function definitionToReferencedSymbolDefinitionInfo(def, checker) { + function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { case "symbol": { - var symbol = def.symbol, node_3 = def.node; - var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var symbol = def.symbol; + var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - 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)] }; + 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)] }; } case "keyword": { - var node_5 = def.node; - var name_5 = ts.tokenToString(node_5.kind); - return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* 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 */ }] }; } case "this": { - 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 }; + 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 }; } case "string": { - 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)] }; + 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)] }; } + default: + return ts.Debug.assertNever(def); } })(); - if (!info) { - return undefined; - } var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); - return { - containerKind: "" /* unknown */, - containerName: "", - fileName: sourceFile.fileName, - kind: kind, - name: name, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: displayParts - }; + var textSpan = getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile); + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: textSpan, displayParts: displayParts }; } - function getDefinitionKindAndDisplayParts(symbol, node, checker) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind; + function getDefinitionKindAndDisplayParts(symbol, checker, node) { + var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); + var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } function toReferenceEntry(entry) { @@ -86513,7 +87781,7 @@ var ts; function implementationKindDisplayParts(node, checker) { var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node); if (symbol) { - return getDefinitionKindAndDisplayParts(symbol, node, checker); + return getDefinitionKindAndDisplayParts(symbol, checker, node); } else if (node.kind === 182 /* ObjectLiteralExpression */) { return { @@ -86547,8 +87815,8 @@ var ts; return { fileName: fileName, span: span }; } FindAllReferences.toHighlightSpan = toHighlightSpan; - function getTextSpan(node) { - var start = node.getStart(); + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); var end = node.getEnd(); if (node.kind === 9 /* StringLiteral */) { start += 1; @@ -86606,7 +87874,7 @@ var ts; case 248 /* ExportDeclaration */: return true; case 185 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); default: return false; } @@ -86638,10 +87906,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ - definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration }, - references: references - }]; + return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -86649,17 +87914,15 @@ var ts; 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.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 if (ts.isLabelOfLabeledStatement(node)) { + // 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); @@ -86673,11 +87936,11 @@ var ts; function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); + var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); var result = []; var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === 79 /* DefaultKeyword */) { - addReference(node, symbol, node, state); + addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { @@ -86686,7 +87949,7 @@ var ts; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); } else { // Global search @@ -86781,7 +88044,11 @@ var ts; this.symbolIdToReferences = []; // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. this.sourceFileToSeenSymbols = []; + this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; }); } + State.prototype.includesSourceFile = function (sourceFile) { + return this.includedSourceFiles.has(sourceFile.fileName); + }; /** 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) @@ -86795,11 +88062,11 @@ var ts; // 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). - 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 _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { - location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, + symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, }; }; @@ -86807,12 +88074,12 @@ var ts; * 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) { + State.prototype.referenceAdder = function (searchSymbol) { var symbolId = ts.getSymbolId(searchSymbol); var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references }); + this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; @@ -86837,7 +88104,7 @@ var ts; 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); + var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; addRef(singleRef); @@ -86873,7 +88140,9 @@ var ts; 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 /* Import */), state); + var exportingFile = declaration.getSourceFile(); + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); } } /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ @@ -86973,6 +88242,17 @@ var ts; // 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; } + /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ + function isSymbolReferencedInFile(definition, checker, sourceFile) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return true; // Be lenient with invalid code. + return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) { + var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), ts.isIdentifier); + return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol; + }); + } + Core.isSymbolReferencedInFile = isSymbolReferencedInFile; function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } var positions = []; @@ -87003,18 +88283,13 @@ var ts; return positions; } function getLabelReferencesInNode(container, targetLabel) { - var references = []; var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); - for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { - var position = possiblePositions_1[_i]; + var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) { 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)); - } - } + return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined; + }); return [{ definition: { type: "label", node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { @@ -87022,9 +88297,11 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.text.length === searchSymbolName.length; + case 9 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + str.text.length === searchSymbolName.length; + } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; case 79 /* DefaultKeyword */: @@ -87034,43 +88311,35 @@ var ts; } } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { - var references = []; - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); - } + return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; + }); + }); return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } - function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - 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, /*includeJsDocComment*/ true); - if (referenceLocation.kind === kind) { - references.push(FindAllReferences.nodeEntry(referenceLocation)); - } - } - } - function getReferencesInSourceFile(sourceFile, search, state) { + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } state.cancellationToken.throwIfCancellationRequested(); - return getReferencesInContainer(sourceFile, sourceFile, search, state); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); } /** * 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) { + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; - getReferencesAtLocation(sourceFile, position, search, state); + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } - function getReferencesAtLocation(sourceFile, position, search, state) { + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { 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 @@ -87099,7 +88368,7 @@ var ts; } if (ts.isExportSpecifier(parent)) { ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); - getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); @@ -87109,7 +88378,8 @@ var ts; } switch (state.specialSearchKind) { case 0 /* None */: - addReference(referenceLocation, relatedSymbol, search.location, state); + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); break; case 1 /* Constructor */: addConstructorReferences(referenceLocation, sourceFile, search, state); @@ -87122,7 +88392,7 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -87138,8 +88408,8 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.options.isForRename && state.markSeenReExportRHS(name)) { - addReference(name, referenceSymbol, name, state); + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { + addReference(name, referenceSymbol, state); } } else { @@ -87161,7 +88431,8 @@ var ts; searchForImportedSymbol(imported, state); } function addRef() { - addReference(referenceLocation, localSymbol, search.location, state); + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); } } function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { @@ -87206,11 +88477,11 @@ var ts; * 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); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state); } } - function addReference(referenceLocation, relatedSymbol, searchLocation, state) { - var addRef = state.referenceAdder(relatedSymbol, searchLocation); + function addReference(referenceLocation, relatedSymbol, state) { + var addRef = state.referenceAdder(relatedSymbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } @@ -87221,9 +88492,9 @@ var ts; /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ function addConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { - addReference(referenceLocation, search.symbol, search.location, state); + addReference(referenceLocation, search.symbol, state); } - var pusher = function () { return state.referenceAdder(search.symbol, search.location); }; + var pusher = function () { return state.referenceAdder(search.symbol); }; if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. @@ -87238,11 +88509,11 @@ var ts; } } function addClassStaticThisReferences(referenceLocation, search, state) { - addReference(referenceLocation, search.symbol, search.location, state); - if (ts.isClassLike(referenceLocation.parent)) { + addReference(referenceLocation, search.symbol, state); + if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); // This is the class declaration. - addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol)); } } function addStaticThisReferences(classLike, pusher) { @@ -87367,7 +88638,7 @@ var ts; return result; } function getContainingTypeReference(node) { - var topLevelTypeReference = undefined; + var topLevelTypeReference; while (node) { if (ts.isTypeNode(node)) { topLevelTypeReference = node; @@ -87421,58 +88692,29 @@ var ts; * distinction between structurally compatible implementations and explicit implementations, so we * must use the AST. * - * @param child A class or interface Symbol + * @param symbol 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 /* Interface */; - return searchHierarchy(child); - function searchHierarchy(symbol) { - if (symbol === parent) { - return true; - } - var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); - var cached = cachedResults.get(key); - 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)) { - if (parentIsInterface) { - var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); - if (interfaceReferences) { - for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { - var typeReference = interfaceReferences_1[_i]; - if (searchTypeReference(typeReference)) { - return true; - } - } - } - } - return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - } - else if (declaration.kind === 234 /* InterfaceDeclaration */) { - if (parentIsInterface) { - return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); - } - } - return false; - }); - cachedResults.set(key, inherits); - return inherits; + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; } - function searchTypeReference(typeReference) { - if (typeReference) { + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { var type = checker.getTypeAtLocation(typeReference); - if (type && type.symbol) { - return searchHierarchy(type.symbol); - } - } - return false; - } + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; } function getReferencesForSuperKeyword(superKeyword) { var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); @@ -87495,24 +88737,19 @@ var ts; default: return undefined; } - var references = []; var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); - for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { - var position = possiblePositions_3[_i]; + var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== 97 /* SuperKeyword */) { - continue; + return; } 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 }]; + return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; + }); + return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -87547,18 +88784,11 @@ var ts; return undefined; } var references = []; - var possiblePositions; - if (searchSpaceNode.kind === 272 /* SourceFile */) { - ts.forEach(sourceFiles, function (sourceFile) { - cancellationToken.throwIfCancellationRequested(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); - getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, staticFlag, references); - }); - } - else { - var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode); - getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, references); + for (var _i = 0, _a = searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + cancellationToken.throwIfCancellationRequested(); + var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode); + getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFile : searchSpaceNode, positions, staticFlag, references); } return [{ definition: { type: "this", node: thisOrSuperKeyword }, @@ -87602,26 +88832,17 @@ var ts; }); } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { - var references = []; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); - getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); - } + return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) { + var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false), ts.isStringLiteral); + return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + }); + }); return [{ definition: { type: "string", node: node }, references: references }]; - 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_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. @@ -87703,9 +88924,6 @@ var ts; * 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: @@ -87717,25 +88935,17 @@ var ts; // 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)) { + if (!symbol || previousIterationSymbolsCache.has(symbol.escapedName)) { return; } 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 === 234 /* InterfaceDeclaration */) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = checker.getTypeAtLocation(typeReference); - if (type) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + for (var _b = 0, _c = ts.getAllSuperTypeNodes(declaration); _b < _c.length; _b++) { + var typeReference = _c[_b]; + var type = checker.getTypeAtLocation(typeReference); + if (!type) + continue; var propertySymbol = checker.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push.apply(result, checker.getRootSymbols(propertySymbol)); @@ -87793,7 +89003,10 @@ var ts; return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { // if it is in the list, then we are done if (search.includes(rootSymbol)) { - return rootSymbol; + // For a root symbol that is a component of a union or intersection, use the original (union/intersection) symbol. + // That we when a symbol references the whole union we avoid claiming it references some particular member of the union. + // For a transient symbol we want to use the root symbol instead. + return ts.getCheckFlags(sym) & 6 /* Synthetic */ ? sym : rootSymbol; } // 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 @@ -87805,7 +89018,7 @@ var ts; } var result = []; getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); - return ts.find(result, search.includes); + return result.some(search.includes) ? rootSymbol : undefined; } return undefined; }); @@ -87838,7 +89051,9 @@ var ts; * 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) { + function getIntersectingMeaningFromDeclarations(node, symbol) { + var meaning = ts.getMeaningFromLocation(node); + var declarations = symbol.declarations; if (declarations) { var lastIterationMeaning = void 0; do { @@ -87859,36 +89074,12 @@ var ts; } return meaning; } + Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; function isImplementation(node) { - if (!node) { - return false; - } - else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { - return true; - } - else if (node.kind === 230 /* VariableDeclaration */) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); - } - else if (ts.isFunctionLike(node)) { - return !!node.body || ts.hasModifier(node, 2 /* Ambient */); - } - else { - switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: - return true; - } - } - return false; - } - function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 212 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 231 /* VariableDeclarationList */); - return node.parent.parent; - } + return !!(node.flags & 2097152 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); } function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { var refSymbol = checker.getSymbolAtLocation(node); @@ -87915,12 +89106,6 @@ var ts; function tryGetClassByExtendingIdentifier(node) { return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); } - function isNameOfExternalModuleImportOrDeclaration(node) { - 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 @@ -87962,9 +89147,8 @@ var ts; } // Labels if (ts.isJumpStatementTarget(node)) { - var labelName = node.text; - var label = ts.getTargetLabel(node.parent, labelName); - return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined; + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -88177,8 +89361,8 @@ var ts; return createDefinitionInfo(decl, symbolKind, symbolName, containerName); } function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; + for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { + var ref = refs_2[_i]; if (ref.pos <= pos && pos <= ref.end) { return ref; } @@ -88820,8 +90004,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88903,7 +90087,7 @@ var ts; case 6 /* NameContainsNonURISafeCharacters */: return "Package name '" + typing + "' contains non URI safe characters"; case 0 /* Ok */: - throw ts.Debug.fail(); // Shouldn't have called this. + return ts.Debug.fail(); // Shouldn't have called this. default: ts.Debug.assertNever(result); } @@ -88919,19 +90103,19 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_8 = function (sourceFile) { + var _loop_9 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; } - ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { + sourceFile.getNamedDeclarations().forEach(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_8(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_9(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -88990,41 +90174,35 @@ var ts; return true; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - var text = ts.getTextOfIdentifierOrLiteral(name); - if (text !== undefined) { - containers.unshift(text); - } - else if (name.kind === 146 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } - } + var name = ts.getNameOfDeclaration(declaration); + if (name && ts.isPropertyNameLiteral(name)) { + containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); + return true; + } + else if (name && name.kind === 146 /* 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) { + if (ts.isPropertyNameLiteral(expression)) { + var text = ts.getTextOfIdentifierOrLiteral(expression); if (includeLastPortion) { containers.unshift(text); } return true; } - if (expression.kind === 183 /* PropertyAccessExpression */) { - var propertyAccess = expression; + if (ts.isPropertyAccessExpression(expression)) { if (includeLastPortion) { - containers.unshift(propertyAccess.name.text); + containers.unshift(expression.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); + return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true); } return false; } @@ -89327,6 +90505,7 @@ var ts; case 1 /* ExportsProperty */: case 2 /* ModuleExports */: case 3 /* PrototypeProperty */: + case 6 /* Prototype */: addNodeWithRecursiveChild(node, node.right); break; case 4 /* ThisProperty */: @@ -89663,16 +90842,20 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } + // See if it is a var initializer. If so, use the var name. else if (node.parent.kind === 230 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } + // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. else if (node.parent.kind === 198 /* BinaryExpression */ && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } + // See if it is a property assignment, and if so use the property name else if (node.parent.kind === 268 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } + // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -89697,44 +90880,111 @@ var ts; (function (ts) { var OrganizeImports; (function (OrganizeImports) { - function organizeImports(sourceFile, formatContext, host) { - // TODO (https://github.com/Microsoft/TypeScript/issues/10020): sort *within* ambient modules (find using isAmbientModule) - // All of the old ImportDeclarations in the file, in syntactic order. - var oldImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - if (oldImportDecls.length === 0) { - return []; - } - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { - return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); - }); - var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { - return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup)) - : importGroup; - }); + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); - // Delete or replace the first import. - if (newImportDecls.length === 0) { - changeTracker.deleteNode(sourceFile, oldImportDecls[0]); - } - else { - // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - useNonAdjustedStartPosition: false, - useNonAdjustedEndPosition: false, - suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + // All of the old ImportDeclarations in the file, in syntactic order. + var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(topLevelImportDecls); + for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { + var ambientModule = _a[_i]; + var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + organizeImportsWorker(ambientModuleImportDecls); } return changeTracker.getChanges(); + function organizeImportsWorker(oldImportDecls) { + if (ts.length(oldImportDecls) === 0) { + return; + } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); + var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); + var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { + return getExternalModuleName(importGroup[0].moduleSpecifier) + ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + : importGroup; + }); + // Delete or replace the first import. + if (newImportDecls.length === 0) { + changeTracker.deleteNode(sourceFile, oldImportDecls[0], { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + }); + } + else { + // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + useNonAdjustedStartPosition: true, + useNonAdjustedEndPosition: false, + suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), + }); + } + // Delete any subsequent imports. + for (var i = 1; i < oldImportDecls.length; i++) { + changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + } + } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports) { - return oldImports; // TODO (https://github.com/Microsoft/TypeScript/issues/10020) + function getModuleBlock(moduleDecl) { + var body = moduleDecl.body; + return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + } + function removeUnusedImports(oldImports, sourceFile, program) { + var typeChecker = program.getTypeChecker(); + var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var usedImports = []; + for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { + var importDecl = oldImports_1[_i]; + var importClause = importDecl.importClause; + if (!importClause) { + // Imports without import clauses are assumed to be included for their side effects and are not removed. + usedImports.push(importDecl); + continue; + } + var name = importClause.name, namedBindings = importClause.namedBindings; + // Default import + if (name && !isDeclarationUsed(name)) { + name = undefined; + } + if (namedBindings) { + if (ts.isNamespaceImport(namedBindings)) { + // Namespace import + if (!isDeclarationUsed(namedBindings.name)) { + namedBindings = undefined; + } + } + else { + // List of named imports + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); + if (newElements.length < namedBindings.elements.length) { + namedBindings = newElements.length + ? ts.updateNamedImports(namedBindings, newElements) + : undefined; + } + } + } + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); + } + } + return usedImports; + function isDeclarationUsed(identifier) { + // The JSX factory symbol is always used. + return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + } } function getExternalModuleName(specifier) { return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier) @@ -89749,7 +90999,7 @@ var ts; if (importGroup.length === 0) { return importGroup; } - var _a = getImportParts(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; + var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports; var coalescedImports = []; if (importWithoutClause) { coalescedImports.push(importWithoutClause); @@ -89758,15 +91008,17 @@ var ts; // produce two import declarations in this special case. if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { // Add the namespace import to the existing default ImportDeclaration. - var defaultImportClause = defaultImports[0].parent; - coalescedImports.push(updateImportDeclarationAndClause(defaultImportClause, defaultImportClause.name, namespaceImports[0])); + var defaultImport = defaultImports[0]; + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); return coalescedImports; } - var sortedNamespaceImports = ts.stableSort(namespaceImports, function (n1, n2) { return compareIdentifiers(n1.name, n2.name); }); + var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { + return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); + }); for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { var namespaceImport = sortedNamespaceImports_1[_i]; // Drop the name, if any - coalescedImports.push(updateImportDeclarationAndClause(namespaceImport.parent, /*name*/ undefined, namespaceImport)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -89774,30 +91026,37 @@ var ts; var newDefaultImport; var newImportSpecifiers = []; if (defaultImports.length === 1) { - newDefaultImport = defaultImports[0]; + newDefaultImport = defaultImports[0].importClause.name; } else { for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { var defaultImport = defaultImports_1[_b]; - newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (n) { return n.elements; })); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || compareIdentifiers(s1.name, s2.name); }); - var importClause = defaultImports.length > 0 - ? defaultImports[0].parent - : namedImports[0].parent; + var importDecl = defaultImports.length > 0 + ? defaultImports[0] + : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 ? undefined : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0], sortedImportSpecifiers); - coalescedImports.push(updateImportDeclarationAndClause(importClause, newDefaultImport, newNamedImports)); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; - function getImportParts(importGroup) { + /* + * Returns entire import declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + * + * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`. + */ + function getCategorizedImports(importGroup) { var importWithoutClause; var defaultImports = []; var namespaceImports = []; @@ -89812,14 +91071,14 @@ var ts; } var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; if (name) { - defaultImports.push(name); + defaultImports.push(importDeclaration); } if (namedBindings) { if (ts.isNamespaceImport(namedBindings)) { - namespaceImports.push(namedBindings); + namespaceImports.push(importDeclaration); } else { - namedImports.push(namedBindings); + namedImports.push(importDeclaration); } } } @@ -89833,12 +91092,11 @@ var ts; function compareIdentifiers(s1, s2) { return ts.compareStringsCaseSensitive(s1.text, s2.text); } - function updateImportDeclarationAndClause(importClause, name, namedBindings) { - var importDeclaration = importClause.parent; - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, name, namedBindings), importDeclaration.moduleSpecifier); - } } OrganizeImports.coalesceImports = coalesceImports; + function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + } /* internal */ // Exported for testing function compareModuleSpecifiers(m1, m2) { var name1 = getExternalModuleName(m1); @@ -89886,13 +91144,13 @@ var ts; 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+(.*))?$/); + var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/); 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")); + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region")); } else { var region = regions.pop(); @@ -90131,10 +91389,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_14 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false)); + /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); } } } @@ -90236,7 +91494,7 @@ var ts; // // Only if all words have some sort of match is the pattern considered matched. var subWordTextChunks = segment.subWordTextChunks; - var matches = undefined; + var matches; for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { var subWordTextChunk = subWordTextChunks_1[_i]; // Try to match the candidate with this word @@ -90284,8 +91542,8 @@ var ts; // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; - var firstMatch = undefined; - var contiguous = undefined; + var firstMatch; + var contiguous; while (true) { // Let's consider our termination cases if (currentChunkSpan === chunkCharacterSpans.length) { @@ -90585,11 +91843,18 @@ var ts; function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { if (readImportFiles === void 0) { readImportFiles = true; } if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } - var referencedFiles = []; - var typeReferenceDirectives = []; + var pragmaContext = { + languageVersion: 1 /* ES5 */, + pragmas: undefined, + checkJsDirective: undefined, + referencedFiles: [], + typeReferenceDirectives: [], + amdDependencies: [], + hasNoDefaultLib: undefined, + moduleName: undefined + }; var importedFiles = []; 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 @@ -90604,23 +91869,6 @@ var ts; } return token; } - function processTripleSlashDirectives() { - var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); - ts.forEach(commentRanges, function (commentRange) { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); - if (referencePathMatchResult) { - isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; - if (fileReference) { - var collection = referencePathMatchResult.isTypeReferenceDirective - ? typeReferenceDirectives - : referencedFiles; - collection.push(fileReference); - } - } - }); - } function getFileReference() { var fileName = ts.scanner.getTokenValue(); var pos = ts.scanner.getTokenPos(); @@ -90881,7 +92129,8 @@ var ts; if (readImportFiles) { processImports(); } - processTripleSlashDirectives(); + ts.processCommentPragmas(pragmaContext, sourceText); + ts.processPragmasIntoFields(pragmaContext, ts.noop); if (externalModule) { // for external modules module all nested ambient modules are augmentations if (ambientExternalModules) { @@ -90891,7 +92140,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; } else { // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 @@ -90910,7 +92159,7 @@ var ts; } } } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -90941,22 +92190,17 @@ var ts; 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(); + var declarations = symbol.declarations; if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. - if (ts.some(declarations, isDefinedInLibraryFile)) { + if (declarations.some(isDefinedInLibraryFile)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // 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 */) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - if (!kind) { - return undefined; - } var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; @@ -90965,12 +92209,11 @@ var ts; return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } - else if (node.kind === 9 /* StringLiteral */) { + else if (ts.isStringLiteral(node)) { 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" /* variableElement */, "" /* none */, node, sourceFile); + return getRenameInfoSuccess(node.text, node.text, "var" /* variableElement */, "" /* none */, node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -91428,11 +92671,75 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program) { + program.getSemanticDiagnostics(sourceFile); + var checker = program.getDiagnosticsProducingTypeChecker(); + var diags = []; + if (sourceFile.commonJsModuleIndicator) { + diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + } + var isJsFile = ts.isSourceFileJavaScript(sourceFile); + function check(node) { + switch (node.kind) { + case 232 /* FunctionDeclaration */: + case 190 /* FunctionExpression */: + if (isJsFile) { + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + } + break; + } + if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + node.forEachChild(check); + } + check(sourceFile); + if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); + if (!name) + continue; + var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + } + } + } + return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + } + ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + function importNameForConvertToDefaultImport(node) { + switch (node.kind) { + case 242 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 241 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + if (result !== "" /* unknown */) { + return result; + } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { return ts.getDeclarationOfKind(symbol, 203 /* ClassExpression */) ? @@ -91446,17 +92753,14 @@ var ts; return "interface" /* interfaceElement */; if (flags & 262144 /* TypeParameter */) return "type parameter" /* typeParameterElement */; - var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - 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 */; - } + 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; @@ -91637,7 +92941,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) { + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) { // At constructor keyword of constructor declaration // 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 @@ -92119,7 +93423,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_10 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -92138,7 +93442,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_10(opt); } return options; } @@ -92915,7 +94219,7 @@ var ts; // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 234 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one + case 234 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -93749,8 +95053,8 @@ var ts; 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 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); + var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { @@ -94717,26 +96021,14 @@ var ts; function isControlFlowEndingStatement(kind, parent) { switch (kind) { case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: - switch (parent.kind) { - case 211 /* Block */: - var grandParent = parent.parent; - switch (grandParent && grandParent.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - // We may want to write inner functions after this. - return false; - default: - return true; - } - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 272 /* SourceFile */: - case 238 /* ModuleBlock */: - return true; - default: - throw ts.Debug.fail(); + case 227 /* ThrowStatement */: { + if (parent.kind !== 211 /* Block */) { + return true; } + var grandParent = parent.parent; + // In a function, we may want to write inner functions after this. + return !(grandParent && grandParent.kind === 190 /* FunctionExpression */ || grandParent.kind === 232 /* FunctionDeclaration */); + } case 221 /* ContinueStatement */: case 222 /* BreakStatement */: return true; @@ -94813,14 +96105,14 @@ var ts; ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; })(ChangeKind || (ChangeKind = {})); - function getSeparatorCharacter(separator) { - return ts.tokenToString(separator.kind); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - textChanges_1.getSeparatorCharacter = getSeparatorCharacter; function getAdjustedStartPosition(sourceFile, node, options, position) { if (options.useNonAdjustedStartPosition) { - return node.getStart(); + return node.getStart(sourceFile); } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); @@ -94847,7 +96139,6 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } - textChanges_1.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { return node.getEnd(); @@ -94858,7 +96149,6 @@ var ts; ? newEnd : end; } - textChanges_1.getAdjustedEndPosition = getAdjustedEndPosition; /** * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ @@ -94874,10 +96164,9 @@ var ts; } var ChangeTracker = /** @class */ (function () { /** Public for tests only. Other callers should use `ChangeTracker.with`. */ - function ChangeTracker(newLineCharacter, formatContext, validator) { + function ChangeTracker(newLineCharacter, formatContext) { this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; - this.validator = validator; this.changes = []; this.deletedNodesInLists = []; // 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 @@ -94895,6 +96184,7 @@ var ts; this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; }; + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); @@ -94954,47 +96244,39 @@ var ts; } return this; }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); }; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); - return this; + this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + }; + ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { + if (options === void 0) { options = {}; } + this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -95012,14 +96294,45 @@ var ts; var pos = before.getStart(sourceFile); this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); + var text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: { pos: pos, end: pos }, text: text }); + }; + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ + ChangeTracker.prototype.insertTypeAnnotation = function (sourceFile, node, type) { + var end = (ts.isFunctionLike(node) + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + ? ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile) || ts.first(node.parameters) + : node.kind !== 230 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name).end; + this.insertNodeAt(sourceFile, end, type, { prefix: ": " }); + }; + ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { + // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter + var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); + this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); + }; ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { if (ts.isStatement(before) || ts.isClassElement(before)) { return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; } - else if (ts.isVariableDeclaration(before)) { + else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2; return { suffix: ", " }; } - throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + else if (ts.isParameter(before)) { + return {}; + } + return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it }; ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { var firstStatement = ts.firstOrUndefined(ctr.body.statements); @@ -95040,7 +96353,7 @@ var ts; } }; ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { - this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); @@ -95074,17 +96387,11 @@ var ts; // 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 /* SemicolonToken */) - }); + this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, { pos: endPosition, end: endPosition }, newNode, this.getInsertNodeAfterOptions(after)); + return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); }; ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { @@ -95096,7 +96403,10 @@ var ts; else if (ts.isVariableDeclaration(node)) { return { prefix: ", " }; } - throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it + else if (ts.isParameter(node)) { + return {}; + } + return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, @@ -95161,17 +96471,9 @@ var ts; // let insert position be the beginning of the line that contains next element startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) }, - 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)) - } - }); + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -95203,13 +96505,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: ts.createToken(separator), - options: {} - }); + this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); // 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 @@ -95217,22 +96513,10 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: insertPos, end: insertPos }, - node: newNode, - options: { indentation: indentation, prefix: this.newLineCharacter } - }); + this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: newNode, - options: { prefix: ts.tokenToString(separator) + " " } - }); + this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; @@ -95244,95 +96528,86 @@ var ts; var newCls = cls.kind === 233 /* ClassDeclaration */ ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); - _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + _this.replaceNode(sourceFile, cls, newCls); }); }; - ChangeTracker.prototype.getChanges = function () { - var _this = this; + /** + * Note: after calling this, the TextChanges object must be discarded! + * @param validate only for tests + * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions, + * so we can only call this once and can't get the non-formatted text separately. + */ + ChangeTracker.prototype.getChanges = function (validate) { this.finishInsertNodeAtClassStart(); - return ts.group(this.changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { - var sourceFile = changesInFile[0].sourceFile; - var textChanges = ChangeTracker.normalize(changesInFile).map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), _this.computeNewText(c, sourceFile)); - }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; - }); - }; - ChangeTracker.prototype.computeNewText = function (change, sourceFile) { - var _this = this; - if (change.kind === ChangeKind.Remove) { - // deletion case - return ""; - } - var options = change.options || {}; - var text; - var pos = change.range.pos; - var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - if (change.kind === ChangeKind.ReplaceWithMultipleNodes) { - var lastIndex_1 = change.nodes.length - 1; - var parts = change.nodes.map(function (n, index) { - var formatted = _this.getFormattedTextOfNode(n, sourceFile, pos, options); - return index === lastIndex_1 || ts.endsWith(formatted, _this.newLineCharacter) - ? formatted - : (formatted + _this.newLineCharacter); - }); - text = parts.join(""); - } - else { - 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 || ""); - }; - ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) { - var nonformattedText = getNonformattedText(node, sourceFile, this.newLineCharacter); - if (this.validator) { - this.validator(nonformattedText); - } - var formatOptions = this.formatContext.options; - var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; - var initialIndentation = options.indentation !== undefined - ? options.indentation - : (options.useIndentationFromFile !== false) - ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter)) - : 0; - var delta = options.delta !== undefined - ? options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(node) - ? (formatOptions.indentSize || 0) - : 0; - 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); - } - return normalized; + return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); }; return ChangeTracker; }()); textChanges_1.ChangeTracker = ChangeTracker; - function getNonformattedText(node, sourceFile, newLine) { - var writer = new Writer(newLine); - var printer = ts.createPrinter({ newLine: newLine === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */ }, writer); - printer.writeNode(4 /* Unspecified */, node, sourceFile, writer); - return { text: writer.getText(), node: assignPositionsToNode(node) }; - } - 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, formatContext); - return applyChanges(nonFormattedText.text, changes); - } + var changesToText; + (function (changesToText) { + function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { + return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + var sourceFile = changesInFile[0].sourceFile; + // order changes by start position + var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); + var _loop_11 = function (i) { + ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { + return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + }); + }; + // verify that change intervals do not overlap, except possibly at end points. + for (var i = 0; i < normalized.length - 1; i++) { + _loop_11(i); + } + var textChanges = normalized.map(function (c) { + return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + }); + return { fileName: sourceFile.fileName, textChanges: textChanges }; + }); + } + changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + if (change.kind === ChangeKind.Remove) { + return ""; + } + if (change.kind === ChangeKind.Text) { + return change.text; + } + var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; + var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; + var text = change.kind === ChangeKind.ReplaceWithMultipleNodes + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter) + : format(change.node); + // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line + var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + return (options.prefix || "") + noIndent + (options.suffix || ""); + } + /** Note: this may mutate `nodeIn`. */ + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; + if (validate) + validate(node, text); + var formatOptions = formatContext.options; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn) ? (formatOptions.indentSize || 0) : 0; + } + var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; + var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); + return applyChanges(text, changes); + } + /** Note: output node may be mutated input node. */ + function getNonformattedText(node, sourceFile, newLineCharacter) { + var writer = new Writer(newLineCharacter); + var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + return { text: writer.getText(), node: assignPositionsToNode(node) }; + } + })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; @@ -95502,7 +96777,7 @@ var ts; 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])) { + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { position = ranges[0].end; advancePastLineBreak(); ranges = ranges.slice(1); @@ -95530,6 +96805,10 @@ var ts; } } } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + } + textChanges_1.isValidLocationToAddComment = isValidLocationToAddComment; })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -95539,6 +96818,22 @@ var ts; (function (codefix) { var codeFixRegistrations = []; var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(changes, description) { + return createCodeFixActionWorker(diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(description, changes, fixId, fixAllDescription, command) { + return { description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } function registerCodeFix(reg) { for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { var error = _a[_i]; @@ -95602,16 +96897,9 @@ var ts; return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; - function codeFixAllWithTextChanges(context, errorCodes, use) { - var changes = []; - eachDiagnostic(context, errorCodes, function (diag) { return use(changes, diag); }); - changes.sort(function (a, b) { return b.span.start - a.span.start; }); - return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); - } - codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges; function eachDiagnostic(_a, errorCodes, cb) { var program = _a.program, sourceFile = _a.sourceFile; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) { + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) { var diag = _b[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); @@ -95661,7 +96949,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, @@ -95677,6 +96965,797 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "annotateWithTypeFromJSDoc"; + var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var decl = getDeclaration(context.sourceFile, context.span.start); + if (!decl) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var decl = getDeclaration(diag.file, diag.start); + if (decl) + doChange(changes, diag.file, decl); + }); }, + }); + function getDeclaration(file, pos) { + var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false); + // For an arrow function with no name, 'name' lands on the first parameter. + return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); + } + function parameterShouldGetTypeFromJSDoc(node) { + return isDeclarationWithType(node) && hasUsableJSDoc(node); + } + codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc; + function hasUsableJSDoc(decl) { + return ts.isFunctionLikeDeclaration(decl) + ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)) + : !decl.type && !!ts.getJSDocType(decl); + } + function doChange(changes, sourceFile, decl) { + if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { + if (!decl.typeParameters) { + var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); + if (typeParameters) + changes.insertTypeParameters(sourceFile, decl, typeParameters); + } + var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19 /* OpenParenToken */)); + for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (!param.type) { + var paramType = ts.getJSDocType(param); + if (paramType) + changes.insertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20 /* CloseParenToken */)); + if (!decl.type) { + var returnType = ts.getJSDocReturnType(decl); + if (returnType) + changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + } + } + else { + var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix + ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. + changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + } + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 230 /* VariableDeclaration */ || + node.kind === 150 /* PropertySignature */ || + node.kind === 151 /* PropertyDeclaration */; + } + function transformJSDocType(node) { + switch (node.kind) { + case 275 /* JSDocAllType */: + case 276 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 279 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 278 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 277 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 281 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 280 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 161 /* 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) { + return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 281 /* 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 === 134 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* 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; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertFunctionToEs6Class"; + var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, + }); + function doChange(changes, sourceFile, position, checker) { + var deletedNodes = []; + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false)); + if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + // Bad input + return undefined; + } + var ctorDeclaration = ctorSymbol.valueDeclaration; + var precedingNode; + var newClassDeclaration; + switch (ctorDeclaration.kind) { + case 232 /* FunctionDeclaration */: + precedingNode = ctorDeclaration; + deleteNode(ctorDeclaration); + newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); + break; + case 230 /* VariableDeclaration */: + precedingNode = ctorDeclaration.parent.parent; + if (ctorDeclaration.parent.declarations.length === 1) { + deleteNode(precedingNode); + } + else { + deleteNode(ctorDeclaration, /*inList*/ true); + } + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); + break; + } + if (!newClassDeclaration) { + return undefined; + } + copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Because the preceding node could be touched, we need to insert nodes before delete nodes. + changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); + for (var _i = 0, deletedNodes_1 = deletedNodes; _i < deletedNodes_1.length; _i++) { + var _a = deletedNodes_1[_i], node = _a.node, inList = _a.inList; + if (inList) { + changes.deleteNodeInList(sourceFile, node); + } + else { + changes.deleteNode(sourceFile, node); + } + } + function deleteNode(node, inList) { + if (inList === void 0) { inList = false; } + // If parent node has already been deleted, do nothing + if (!deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n.node); })) { + deletedNodes.push({ node: node, inList: inList }); + } + } + 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, /*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 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push(memberElement); + } + }); + } + 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) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { + return; + } + var memberDeclaration = symbol.valueDeclaration; + var assignmentBinaryExpression = memberDeclaration.parent; + if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { + 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 === 214 /* ExpressionStatement */ + ? assignmentBinaryExpression.parent : assignmentBinaryExpression; + deleteNode(nodeToDelete); + if (!assignmentBinaryExpression.right) { + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); + } + switch (assignmentBinaryExpression.right.kind) { + case 190 /* FunctionExpression */: { + var functionExpression = assignmentBinaryExpression.right; + 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, sourceFile); + return method; + } + case 191 /* ArrowFunction */: { + var arrowFunction = assignmentBinaryExpression.right; + var arrowFunctionBody = arrowFunction.body; + var bodyBlock = void 0; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 211 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + } + 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, sourceFile); + return method; + } + default: { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + return prop; + } + } + } + } + function createClassFromVariableDeclaration(node) { + var initializer = node.initializer; + if (!initializer || initializer.kind !== 190 /* FunctionExpression */) { + return undefined; + } + if (node.name.kind !== 71 /* Identifier */) { + return undefined; + } + var memberElements = createClassElementsFromSymbol(initializer.symbol); + if (initializer.body) { + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + } + 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(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + } + 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 copyComments(sourceNode, targetNode, sourceFile) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + 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); + }); + } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, sourceFile, changes); + } + } + }); + // No support for fix-all since this applies to the whole file at once anyway. + return [codefix.createCodeFixActionNoFixId(changes, ts.Diagnostics.Convert_to_ES6_module)]; + }, + }); + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 241 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + break; + case 185 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); + } + break; + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 212 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 214 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 185 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + } + return false; + } + case 198 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 178 /* ObjectBindingPattern */: + case 179 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 269 /* ShorthandPropertyAssignment */: + case 270 /* SpreadAssignment */: + return undefined; + case 268 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); + case 153 /* MethodDeclaration */: + return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right)); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 190 /* FunctionExpression */: + case 191 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 203 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 185 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 190 /* FunctionExpression */: { + var expressionName = exported.name; + if (expressionName && expressionName.text !== name) { + // `exports.f = function g() {}` -> `export const f = function g() {}` + return exportConst(); + } + } + // falls through + case 191 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 203 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + return exportConst(); + } + function exportConst() { + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 178 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 179 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 183 /* PropertyAccessExpression */: + return parent.name !== node; + case 180 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + return makeImportDeclaration(name, namedImports, moduleSpecifier); + } + function makeImportDeclaration(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier); + } + codefix.makeImportDeclaration = makeImportDeclaration; + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -95689,8 +97768,8 @@ var ts; if (!qualifiedName) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); - return [{ description: description, changes: changes, fixId: fixId }]; + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -95727,11 +97806,8 @@ var ts; var classDeclaration = getClass(sourceFile, span.start); var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - return { description: description, changes: changes, fixId: fixId }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, fixIds: [fixId], @@ -95742,31 +97818,29 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); }, }); function getClass(sourceFile, pos) { - var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)); - ts.Debug.assert(!!classDeclaration); - return classDeclaration; + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false))); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { // 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 /* Private */); }); var classType = checker.getTypeAtLocation(classDeclaration); - if (!checker.getIndexTypeOfType(classType, 1 /* Number */)) { + if (!classType.getNumberIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } - if (!checker.getIndexTypeOfType(classType, 0 /* String */)) { + if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { @@ -95793,7 +97867,7 @@ var ts; if (!info) return undefined; var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs ? ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); @@ -95803,7 +97877,7 @@ var ts; getAllCodeActions: function (context) { var seenNames = ts.createMap(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var program = context.program; + var program = context.program, preferences = context.preferences; var info = getInfo(diag.file, diag.start, program.getTypeChecker()); if (!info) return; @@ -95813,7 +97887,7 @@ var ts; } // Always prefer to add a method declaration if possible. if (call) { - addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, preferences); } else { if (inJs) { @@ -95872,10 +97946,8 @@ var ts; } function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); - return { description: description, changes: changes, fixId: fixId }; + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { @@ -95914,9 +97986,8 @@ var ts; return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); - return { description: description, changes: changes, fixId: fixId }; + return codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( @@ -95940,15 +98011,14 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); - return { description: description, changes: changes, fixId: fixId }; + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic, preferences); changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -95972,8 +98042,7 @@ var ts; return undefined; var node = info.node, suggestion = info.suggestion; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); - return [{ description: description, changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96010,10 +98079,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 793064 /* Type */; + flags |= 67901928 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 107455 /* Value */; + flags |= 67216319 /* Value */; } return flags; } @@ -96029,37 +98098,27 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); - return codeAction && [__assign({ fixId: fixId }, codeAction)]; + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = getTypesPackageNameToInstall(host, sourceFile, start); + return packageName === undefined ? [] + : [codefix.createCodeFixAction(/*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start); if (pkg) { commands.push(getCommand(diag.file.fileName, pkg)); } }); }, }); - function getModuleName(sourceFile, pos) { - return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; - } function getCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, moduleName) { + function getTypesPackageNameToInstall(host, sourceFile, pos) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; var packageName = ts.getPackageName(moduleName).packageName; - // If !registry, registry not available yet, can't do anything. return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; } - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { - var packageName = getTypesPackageNameToInstall(host, moduleName); - return packageName === undefined ? undefined : { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), - changes: [], - commands: [getCommand(fileName, packageName)], - }; - } - codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -96077,30 +98136,34 @@ var ts; getCodeActions: function (context) { var program = context.program, sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); }); - return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes); - }); }, + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + } + }); + }, }); function getClass(sourceFile, pos) { - // This is the identifier in the case of a class declaration + // Token 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, pos, /*includeJsDocComment*/ false); - var classDeclaration = token.parent; - ts.Debug.assert(ts.isClassLike(classDeclaration)); - return classDeclaration; + return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { 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 abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -96126,7 +98189,7 @@ var ts; return undefined; var constructor = nodes.constructor, superCall = nodes.superCall; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -96179,7 +98242,7 @@ var ts; var sourceFile = context.sourceFile, span = context.span; var ctr = getNode(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96213,7 +98276,7 @@ var ts; return undefined; var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96229,7 +98292,7 @@ var ts; return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && heritageClauses[0].token === 85 /* ExtendsKeyword */ && @@ -96265,7 +98328,7 @@ var ts; return undefined; } var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_this_to_unresolved_variable, fixId, ts.Diagnostics.Add_this_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96282,7 +98345,7 @@ var ts; } // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper ts.suppressLeadingAndTrailingTrivia(token); - changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -96296,29 +98359,33 @@ var ts; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = getToken(sourceFile, context.span.start); + var errorCode = context.errorCode, sourceFile = context.sourceFile; + var importDecl = tryGetFullImport(sourceFile, context.span.start); + if (importDecl) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); + return [codefix.createCodeFixAction(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } + var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); if (deletion.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); - result.push({ description: description, changes: deletion, fixId: fixIdDelete }); + result.push(codefix.createCodeFixAction(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } - var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, context.errorCode, sourceFile, token); }); + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); - result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + result.push(codefix.createCodeFixAction(prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); } return result; }, fixIds: [fixIdPrefix, fixIdDelete], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var sourceFile = context.sourceFile; - var token = getToken(diag.file, diag.start); + var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); switch (context.fixId) { case fixIdPrefix: if (ts.isIdentifier(token) && canPrefix(token)) { @@ -96326,17 +98393,28 @@ var ts; } break; case fixIdDelete: - tryDeleteDeclaration(changes, sourceFile, token); + var importDecl = tryGetFullImport(diag.file, diag.start); + if (importDecl) { + changes.deleteNode(sourceFile, importDecl); + } + else { + tryDeleteDeclaration(changes, sourceFile, token); + } break; default: ts.Debug.fail(JSON.stringify(context.fixId)); } }); }, }); + // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. + function tryGetFullImport(sourceFile, pos) { + var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; + } function getToken(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.findPrecedingToken(pos, sourceFile); // this handles var ["computed"] = 12; - return token.kind === 21 /* OpenBracketToken */ ? ts.getTokenAtPosition(sourceFile, pos + 1, /*includeJsDocComment*/ false) : token; + return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. @@ -96401,6 +98479,10 @@ var ts; break; case 148 /* Parameter */: var oldFunction = parent.parent; + if (ts.isSetAccessor(oldFunction)) { + // Setter must have a parameter + break; + } if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the @@ -96411,7 +98493,7 @@ var ts; // to replace the span (vs the full span) of the old function - the old leading // and trailing trivia will remain. ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction, ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, oldFunction, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); @@ -96432,9 +98514,9 @@ var ts; changes.deleteNodeInList(sourceFile, parent); } break; - case 243 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + case 243 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *' var importClause = parent; - if (!importClause.namedBindings) { + if (!importClause.namedBindings) { // |import d from './file'| changes.deleteNode(sourceFile, ts.getAncestor(importClause, 242 /* ImportDeclaration */)); } else { @@ -96530,47 +98612,40 @@ var ts; return undefined; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); - var actions = [fix(type, fixIdPlain)]; + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; if (typeNode.kind === 277 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable)); + actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; - function fix(type, fixId) { - var newText = typeString(type, checker); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], - fixId: fixId, - }; + function fix(type, fixId, fixAllDescription) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], getAllCodeActions: function (context) { var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; var checker = program.getTypeChecker(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + return codefix.codeFixAll(context, errorCodes, function (changes, err) { var info = getInfo(err.file, err.start, checker); if (!info) return; var typeNode = info.typeNode, type = info.type; var fixedType = typeNode.kind === 277 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; - changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + doChange(changes, sourceFile, typeNode, fixedType, checker); }); } }); + function doChange(changes, sourceFile, oldTypeNode, newType, checker) { + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); + } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); var typeNode = decl && decl.type; return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; } - function createChange(declaration, sourceFile, newText) { - return ts.createTextChange(ts.createTextSpanFromNode(declaration, sourceFile), newText); - } - function typeString(type, checker) { - return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); - } function isTypeContainer(node) { // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments @@ -96616,7 +98691,7 @@ var ts; if (!nodes) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96639,6 +98714,9 @@ var ts; function getNodes(sourceFile, start) { var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } var insertBefore; switch (containingFunction.kind) { case 153 /* MethodDeclaration */: @@ -96690,9 +98768,8 @@ var ts; getAllCodeActions: ts.notImplemented, }); function createCodeAction(descriptionDiagnostic, diagnosticArgs, changes) { - var description = ts.formatMessage.apply(undefined, [undefined, descriptionDiagnostic].concat(diagnosticArgs)); // TODO: GH#20315 - return { description: description, changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(changes, [descriptionDiagnostic].concat(diagnosticArgs)); } function convertToImportCodeFixContext(context, symbolToken, symbolName) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; @@ -96708,7 +98785,8 @@ var ts; cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolName, - symbolToken: symbolToken + symbolToken: symbolToken, + preferences: context.preferences, }; } var ImportKind; @@ -96718,12 +98796,12 @@ var ts; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken) { + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken, preferences) { var exportInfos = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host)).moduleSpecifier; - var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken }; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } codefix.getImportCompletionAction = getImportCompletionAction; @@ -96785,34 +98863,20 @@ var ts; var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); var cached = cachedImportDeclarations[moduleSymbolId]; if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { - var declaration = checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; - return declaration && { declaration: declaration, importKind: importKind }; + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 242 /* ImportDeclaration */ || i.kind === 241 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } return cached; } - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 242 /* ImportDeclaration */: - return parent; - case 252 /* ExternalModuleReference */: - return parent.parent; - case 248 /* ExportDeclaration */: - case 185 /* CallExpression */:// For "require()" calls - // Ignore these, can't add imports to them. - return undefined; - default: - ts.Debug.fail(); - } - } function getCodeActionForNewImport(context, _a) { var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; - var sourceFile = context.sourceFile, symbolName = context.symbolName; + var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); + var quotedModuleSpecifier = ts.createLiteral(moduleSpecifierWithoutQuotes, shouldUseSingleQuote(sourceFile, preferences)); var importDecl = importKind !== 3 /* Equals */ ? ts.createImportDeclaration( /*decorators*/ undefined, @@ -96833,11 +98897,14 @@ var ts; // are there are already a new line seperating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } - 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 shouldUseSingleQuote(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single"; + } + else { + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + } } function usesJsExtensionOnImports(sourceFile) { return ts.firstDefined(sourceFile.imports, function (_a) { @@ -96858,35 +98925,40 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { - var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; + function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var addJsExtension = usesJsExtensionOnImports(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); if (global) { return [global]; } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); - if (!baseUrl) { + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), compilerOptions, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { return [relativePath]; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { return [relativePath]; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, compilerOptions, addJsExtension); if (paths) { var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); if (fromPaths) { return [fromPaths]; } } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); if (isPathRelativeToParent(relativeToBaseUrl)) { return [relativePath]; } @@ -97140,7 +99212,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); return newImportInfos.map(function (info) { return getCodeActionForNewImport(ctx, info); }); } function newImportInfoFromExistingSpecifier(_a) { @@ -97219,7 +99291,7 @@ var ts; var parent = token.parent; var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent); if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258 /* JsxOpeningFragment */) { - umdSymbol = checker.resolveName(checker.getJsxNamespace(), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false); + umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false); } } if (ts.isUMDExportSymbol(umdSymbol)) { @@ -97249,7 +99321,7 @@ var ts; // Fall back to the `import * as ns` style import. return 2 /* Namespace */; default: - throw ts.Debug.assertNever(moduleKind); + return ts.Debug.assertNever(moduleKind); } } function getActionsForNonUMDImport(context) { @@ -97257,13 +99329,14 @@ var ts; var sourceFile = context.sourceFile, span = context.span, program = context.program, cancellationToken = context.cancellationToken; var checker = program.getTypeChecker(); var symbolToken = ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false); - var isJsxNamespace = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken; - if (!isJsxNamespace && !ts.isIdentifier(symbolToken)) { + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; + if (!symbolName) return undefined; - } - var symbolName = isJsxNamespace ? checker.getJsxNamespace() : symbolToken.text; - var allSourceFiles = program.getSourceFiles(); - var compilerOptions = program.getCompilerOptions(); // "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 currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); @@ -97273,7 +99346,7 @@ var ts; function addSymbol(moduleSymbol, exportedSymbol, importKind) { originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); } - forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); // check the default export var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); @@ -97281,7 +99354,7 @@ var ts; var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if ((localSymbol && localSymbol.escapedName === symbolName || getEscapedNameForExportDefault(defaultExport) === symbolName || - moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { addSymbol(moduleSymbol, localSymbol || defaultExport, 1 /* Default */); } } @@ -97342,21 +99415,22 @@ var ts; return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { - return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); } codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); var res = ""; var lastCharWasValid = true; - var firstCharCode = moduleSpecifier.charCodeAt(0); + var firstCharCode = baseName.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); + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); var isValid = ts.isIdentifierPart(ch, target); if (isValid) { var char = String.fromCharCode(ch); @@ -97386,55 +99460,39 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, span = context.span; + var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } - var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter).change])], - fixId: fixId, - }, - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [ - ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), - ])], - // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - fixId: undefined, - }]; + var fixes = [ + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId([codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), + ]; + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); + } + return fixes; }, fixIds: [fixId], getAllCodeActions: function (context) { - var seenLines = ts.createMap(); // Only need to add `// @ts-ignore` for a line once. - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { - if (err.start !== undefined) { - var _a = getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options)), lineNumber = _a.lineNumber, change = _a.change; - if (ts.addToSeen(seenLines, lineNumber)) { - changes.push(change); - } + var seenLines = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { + makeChange(changes, diag.file, diag.start, seenLines); } }); }, }); - function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) { + function makeChange(changes, sourceFile, position, seenLines) { var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; - var lineStartPosition = ts.getStartPositionOfLine(lineNumber, 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, /*includeJsDocComment*/ false); - var tokenLeadingComments = ts.getLeadingCommentRangesOfNode(token, sourceFile); - if (!tokenLeadingComments || !tokenLeadingComments.length || tokenLeadingComments[0].pos >= startPosition) { - return { lineNumber: lineNumber, change: ts.createTextChangeFromStartLength(startPosition, 0, "// @ts-ignore" + newLineCharacter) }; - } + // Only need to add `// @ts-ignore` for a line once. + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } - // If all fails, add an extra new line immediately before the error span. - return { lineNumber: lineNumber, change: ts.createTextChangeFromStartLength(position, 0, (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter) }; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -97449,12 +99507,12 @@ var ts; * @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, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); } } } @@ -97462,7 +99520,7 @@ var ts; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -97500,7 +99558,7 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { @@ -97510,11 +99568,11 @@ var ts; } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); } else { ts.Debug.assert(declarations.length === signatures.length); - out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); } break; } @@ -97539,7 +99597,7 @@ var ts; function getSynthesizedDeepClones(nodes) { return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); } - function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { + function createMethodFromCallExpression(_a, methodName, inJs, makeStatic, preferences) { var typeArguments = _a.typeArguments, args = _a.arguments; return ts.createMethod( /*decorators*/ undefined, @@ -97550,7 +99608,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody()); + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, minArgumentCount, inJs) { @@ -97568,7 +99626,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers) { + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { /** 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. @@ -97600,16 +99658,16 @@ var ts; } return createStubbedMethod(modifiers, name, optional, /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined); + /*returnType*/ undefined, preferences); } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } - function createStubbedMethodBody() { + function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), - /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], /*multiline*/ true); } function createVisibilityModifier(flags) { @@ -97647,28 +99705,23 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (_a) { - var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; if (ts.isSourceFileJavaScript(sourceFile)) { return undefined; // TODO: GH#20113 } var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var fix = getFix(sourceFile, token, errorCode, program, cancellationToken); - if (!fix) - return undefined; - var declaration = fix.declaration, textChanges = fix.textChanges; - var name = ts.getNameOfDeclaration(declaration); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); - return [{ description: description, changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }], fixId: fixId }]; + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); + return changes.length === 0 ? undefined + : [codefix.createCodeFixAction(changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; var seenFunctions = ts.createMap(); - return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { - var fix = getFix(sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); - if (fix) - changes.push.apply(changes, fix.textChanges); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); }); }, }); @@ -97682,18 +99735,26 @@ var ts; return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function getFix(sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { - if (!isAllowedTokenKind(token.kind)) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { return undefined; } + var parent = token.parent; 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, program, cancellationToken); + if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + return parent; + } + return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, program, cancellationToken); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + return symbol.valueDeclaration; + } } } var containingFunction = ts.getContainingFunction(token); @@ -97704,43 +99765,41 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction, program, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return !seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction)) - ? getCodeActionForParameters(ts.cast(token.parent, ts.isParameter), containingFunction, sourceFile, program, cancellationToken) - : undefined; + if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + return param; + } + return undefined; // 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, sourceFile, program, cancellationToken) : undefined; + if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + return containingFunction; + } + return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, program, cancellationToken) : undefined; + if (ts.isSetAccessor(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + return containingFunction; + } + return undefined; default: - throw ts.Debug.fail(String(errorCode)); + return ts.Debug.fail(String(errorCode)); } } - function isAllowedTokenKind(kind) { - switch (kind) { - case 71 /* Identifier */: - case 24 /* DotDotDotToken */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; + function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); } } - function getCodeActionForVariableDeclaration(declaration, program, cancellationToken) { - if (!ts.isIdentifier(declaration.name)) - return undefined; - var type = inferTypeForVariableFromUsage(declaration.name, program, cancellationToken); - return makeFix(declaration, declaration.name.getEnd(), type, program); - } function isApplicableFunctionForInference(declaration) { switch (declaration.kind) { case 232 /* FunctionDeclaration */: @@ -97752,47 +99811,47 @@ var ts; } return false; } - function getCodeActionForParameters(parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; + return; } var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - if (!types) - return undefined; // We didn't actually find a set of type inference positions matching each parameter position - if (containingFunction.parameters.length !== types.length) { - return undefined; + if (!types || containingFunction.parameters.length !== types.length) { + return; } - var textChanges = ts.arrayFrom(ts.mapDefinedIterator(ts.zipToIterator(containingFunction.parameters, types), function (_a) { - var parameter = _a[0], type = _a[1]; - return type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined; - })); - return textChanges.length ? { declaration: parameterDeclaration, textChanges: textChanges } : undefined; + ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (!parameter.type && !parameter.initializer) { + annotate(changes, sourceFile, parameter, type, program); + } + }); } - function getCodeActionForSetAccessor(setAccessorDeclaration, program, cancellationToken) { - var setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { - return undefined; + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || + inferTypeForVariableFromUsage(param.name, program, cancellationToken); + annotate(changes, sourceFile, param, type, program); } - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(setAccessorParameter.name, program, cancellationToken); - return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); } - function getCodeActionForGetAccessor(getAccessorDeclaration, sourceFile, program, cancellationToken) { - if (!ts.isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, program, cancellationToken); - var closeParenToken = ts.findChildOfKind(getAccessorDeclaration, 20 /* CloseParenToken */, sourceFile); - return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + function annotate(changes, sourceFile, declaration, type, program) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); + if (typeNode) + changes.insertTypeAnnotation(sourceFile, declaration, typeNode); } - function makeFix(declaration, start, type, program) { - return type && { declaration: declaration, textChanges: [makeChange(declaration, start, type, program)] }; - } - function makeChange(declaration, start, type, program) { - var typeString = type && typeToString(type, declaration, program.getTypeChecker()); - return typeString === undefined ? undefined : ts.createTextChangeFromStartLength(start, 0, ": " + typeString); + function getTypeNodeIfAccessible(type, enclosingScope, checker) { + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + }); + return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. @@ -97818,48 +99877,6 @@ var ts; } } } - function getTypeAccessiblityWriter(checker) { - var str = ""; - var typeIsAccessible = true; - var writeText = function (text) { return str += text; }; - return { - getText: function () { return typeIsAccessible ? str : undefined; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - write: writeText, - writeTextOfNode: writeText, - rawWrite: writeText, - writeLiteral: writeText, - getTextPos: function () { return 0; }, - getLine: function () { return 0; }, - getColumn: function () { return 0; }, - getIndent: function () { return 0; }, - isAtStartOfLine: function () { return false; }, - writeLine: function () { return writeText(" "); }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { str = ""; typeIsAccessible = true; }, - trackSymbol: function (symbol, declaration, meaning) { - if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { - typeIsAccessible = false; - } - }, - reportInaccessibleThisError: function () { typeIsAccessible = false; }, - reportPrivateInBaseOfClassExpression: function () { typeIsAccessible = false; }, - reportInaccessibleUniqueSymbolError: function () { typeIsAccessible = false; } - }; - } - function typeToString(type, enclosingDeclaration, checker) { - var writer = getTypeAccessiblityWriter(checker); - checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); - return writer.getText(); - } var InferFromReference; (function (InferFromReference) { function inferTypeFromReferences(references, checker, cancellationToken) { @@ -97889,13 +99906,13 @@ var ts; var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; - var isRestParameter = ts.isRestParameter(parameter); + var isRest = ts.isRestParameter(parameter); for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { continue; } - if (isRestParameter) { + if (isRest) { for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); } @@ -97908,7 +99925,7 @@ var ts; return undefined; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRestParameter ? checker.createArrayType(type) : type; + return isRest ? checker.createArrayType(type) : type; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -97965,6 +99982,8 @@ var ts; case 37 /* PlusToken */: usageContext.isNumberOrString = true; break; + // case SyntaxKind.ExclamationToken: + // no inferences here; } } function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { @@ -98230,9 +100249,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -98242,12 +100259,8 @@ var ts; return variations; } function createAction(context, sourceFile, node, replacement) { - // TODO: GH#21246 Should be able to use `replaceNode`, but be sure to preserve comments (see `codeFixCalledES2015Import11.ts`) - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceRange(sourceFile, { pos: node.getStart(), end: node.end }, replacement); }); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), - changes: changes, - }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -98273,15 +100286,171 @@ var ts; if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } - fixes.push({ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), - changes: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }), - }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(changes, ts.Diagnostics.Use_synthetic_default_member)); return fixes; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; + var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; + var fixIdAddInitializer = "addMissingPropertyInitializer"; + var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); + if (!propertyDeclaration) + return; + var result = [ + getActionForAddMissingUndefinedType(context, propertyDeclaration), + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) + ]; + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + return result; + }, + fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); + if (!propertyDeclaration) + return; + switch (context.fixId) { + case fixIdAddDefiniteAssignmentAssertions: + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + break; + case fixIdAddUndefinedType: + addUndefinedType(changes, diag.file, propertyDeclaration); + break; + case fixIdAddInitializer: + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return; + addInitializer(changes, diag.file, propertyDeclaration, initializer); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, + }); + function getPropertyDeclaration(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + } + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + } + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getActionForAddMissingUndefinedType(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + } + function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); + var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types)); + } + function getActionForAddMissingInitializer(context, propertyDeclaration) { + var checker = context.program.getTypeChecker(); + var initializer = getInitializer(checker, propertyDeclaration); + if (!initializer) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + } + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { + var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); + } + function getInitializer(checker, propertyDeclaration) { + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + } + function getDefaultValueFromType(checker, type) { + if (type.flags & 2 /* String */) { + return ts.createLiteral(""); + } + else if (type.flags & 4 /* Number */) { + return ts.createNumericLiteral("0"); + } + else if (type.flags & 8 /* Boolean */) { + return ts.createFalse(); + } + else if (type.flags & 224 /* Literal */) { + return ts.createLiteral(type.value); + } + else if (type.flags & 131072 /* Union */) { + return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); + } + else if (ts.getObjectFlags(type) & 1 /* Class */) { + var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); + if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) + return undefined; + var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; }); + if (constructorDeclaration && constructorDeclaration.parameters.length) + return undefined; + return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "useDefaultImport"; + var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var info = getInfo(sourceFile, start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); }, + }); + function getInfo(sourceFile, pos) { + var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + if (!ts.isIdentifier(name)) + return undefined; // bad input + var parent = name.parent; + if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) { + return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression }; + } + else if (ts.isNamespaceImport(parent)) { + var importNode = parent.parent.parent; + return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; + } + } + function doChange(changes, sourceFile, info) { + changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// +/// +/// +/// /// /// /// @@ -98300,960 +100469,8 @@ var ts; /// /// /// -/* @internal */ -var ts; -(function (ts) { - var refactor; - (function (refactor) { - var annotateWithTypeFromJSDoc; - (function (annotateWithTypeFromJSDoc) { - var refactorName = "Annotate with type from JSDoc"; - var actionName = "annotate"; - var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (ts.isInJavaScriptFile(context.file)) { - return undefined; - } - var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); - if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { - return [{ - name: refactorName, - description: description, - actions: [ - { - description: 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 === 148 /* 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.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions); - 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.replaceNode(sourceFile, decl, functionWithType, ts.textChanges.useNonAdjustedPositions); - return { - edits: changeTracker.getChanges(), - renameFilename: undefined, - renameLocation: undefined - }; - } - function isDeclarationWithType(node) { - return ts.isFunctionLikeDeclaration(node) || - node.kind === 230 /* VariableDeclaration */ || - node.kind === 148 /* Parameter */ || - node.kind === 150 /* PropertySignature */ || - node.kind === 151 /* 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 232 /* FunctionDeclaration */: - return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); - case 154 /* Constructor */: - return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); - case 190 /* FunctionExpression */: - return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); - case 191 /* ArrowFunction */: - return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); - case 153 /* MethodDeclaration */: - return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body); - case 155 /* GetAccessor */: - return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body); - case 156 /* 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 230 /* VariableDeclaration */: - return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer); - case 150 /* PropertySignature */: - return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); - case 151 /* 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 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: - return ts.createTypeReferenceNode("any", ts.emptyArray); - case 279 /* JSDocOptionalType */: - return transformJSDocOptionalType(node); - case 278 /* JSDocNonNullableType */: - return transformJSDocType(node.type); - case 277 /* JSDocNullableType */: - return transformJSDocNullableType(node); - case 281 /* JSDocVariadicType */: - return transformJSDocVariadicType(node); - case 280 /* JSDocFunctionType */: - return transformJSDocFunctionType(node); - case 148 /* Parameter */: - return transformJSDocParameter(node); - case 161 /* 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 === 281 /* 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 === 134 /* NumberKeyword */ ? "n" : "s", - /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* 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; - (function (refactor) { - var convertFunctionToES6Class; - (function (convertFunctionToES6Class) { - var refactorName = "Convert to ES2015 class"; - var actionName = "convert"; - var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (!ts.isInJavaScriptFile(context.file)) { - return undefined; - } - var symbol = getConstructorSymbol(context); - if (!symbol) { - return undefined; - } - if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { - symbol = symbol.valueDeclaration.initializer.symbol; - } - if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { - return [ - { - name: refactorName, - description: description, - actions: [ - { - description: description, - name: actionName - } - ] - } - ]; - } - } - function getEditsForAction(context, action) { - // Somehow wrong action got invoked? - if (actionName !== action) { - return undefined; - } - var sourceFile = context.file; - var ctorSymbol = getConstructorSymbol(context); - var deletedNodes = []; - var deletes = []; - if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { - return undefined; - } - var ctorDeclaration = ctorSymbol.valueDeclaration; - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var precedingNode; - var newClassDeclaration; - switch (ctorDeclaration.kind) { - case 232 /* FunctionDeclaration */: - precedingNode = ctorDeclaration; - deleteNode(ctorDeclaration); - newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); - break; - case 230 /* VariableDeclaration */: - precedingNode = ctorDeclaration.parent.parent; - if (ctorDeclaration.parent.declarations.length === 1) { - deleteNode(precedingNode); - } - else { - deleteNode(ctorDeclaration, /*inList*/ true); - } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); - break; - } - if (!newClassDeclaration) { - return undefined; - } - // Because the preceding node could be touched, we need to insert nodes before delete nodes. - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); - for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { - var deleteCallback = deletes_1[_i]; - deleteCallback(); - } - return { - edits: changeTracker.getChanges(), - renameFilename: undefined, - renameLocation: undefined, - }; - 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); - if (inList) { - deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); }); - } - else { - deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); }); - } - } - 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, /*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 /* StaticKeyword */)]); - if (memberElement) { - memberElements.push(memberElement); - } - }); - } - 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) { - // both properties and methods are bound as property symbols - if (!(symbol.flags & 4 /* Property */)) { - return; - } - var memberDeclaration = symbol.valueDeclaration; - var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - 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 === 214 /* ExpressionStatement */ - ? assignmentBinaryExpression.parent : assignmentBinaryExpression; - deleteNode(nodeToDelete); - if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, - /*type*/ undefined, /*initializer*/ undefined); - } - switch (assignmentBinaryExpression.right.kind) { - case 190 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - 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 191 /* ArrowFunction */: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 211 /* Block */) { - bodyBlock = arrowFunctionBody; - } - else { - bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); - } - 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(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop); - return prop; - } - } - } - } - function copyComments(sourceNode, targetNode) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - 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); - }); - } - function createClassFromVariableDeclaration(node) { - var initializer = node.initializer; - if (!initializer || initializer.kind !== 190 /* FunctionExpression */) { - return undefined; - } - if (node.name.kind !== 71 /* Identifier */) { - return undefined; - } - var memberElements = createClassElementsFromSymbol(initializer.symbol); - if (initializer.body) { - memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); - } - 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(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); - } - 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 actionName = "Convert to ES6 module"; - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); - refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition; - if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { - return undefined; - } - var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); - return !isAtTriggerLocation(file, node) ? undefined : [ - { - name: actionName, - description: description, - actions: [ - { - description: description, - name: actionName, - }, - ], - }, - ]; - } - function isAtTriggerLocation(sourceFile, node, onSecondTry) { - if (onSecondTry === void 0) { onSecondTry = false; } - switch (node.kind) { - case 185 /* CallExpression */: - return isAtTopLevelRequire(node); - case 183 /* PropertyAccessExpression */: - return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) - || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); - case 231 /* VariableDeclarationList */: - return isVariableDeclarationTriggerLocation(ts.firstOrUndefined(node.declarations)); - case 230 /* VariableDeclaration */: - return isVariableDeclarationTriggerLocation(node); - default: - return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) - || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); - } - function isVariableDeclarationTriggerLocation(decl) { - return !!decl && !!decl.initializer && ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); - } - } - function isAtTopLevelRequire(call) { - if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { - return false; - } - var propAccess = call.parent; - var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; - if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { - return true; - } - if (!ts.isVariableDeclaration(varDecl)) { - return false; - } - var varDeclList = varDecl.parent; - if (varDeclList.kind !== 231 /* VariableDeclarationList */) { - return false; - } - var varStatement = varDeclList.parent; - return varStatement.kind === 212 /* VariableStatement */ && varStatement.parent.kind === 272 /* SourceFile */; - } - function getEditsForAction(context, _actionName) { - ts.Debug.assertEqual(actionName, _actionName); - var file = context.file, program = context.program; - ts.Debug.assert(ts.isSourceFileJavaScript(file)); - var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); - if (moduleExportsChangedToDefault) { - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, file, changes); - } - } - }); - return { edits: edits, renameFilename: undefined, renameLocation: undefined }; - } - function fixImportOfModuleExports(importingFile, exportingFile, changes) { - for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); - if (!imported || imported.resolvedFileName !== exportingFile.fileName) { - continue; - } - var parent = moduleSpecifier.parent; - switch (parent.kind) { - case 252 /* ExternalModuleReference */: { - var importEq = parent.parent; - changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); - break; - } - case 185 /* CallExpression */: { - var call = parent; - if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { - changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); - } - break; - } - } - } - } - /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { - var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; - var exports = collectExportRenames(sourceFile, checker, identifiers); - convertExportsAccesses(sourceFile, exports, changes); - var moduleExportsChangedToDefault = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); - moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; - } - return moduleExportsChangedToDefault; - } - function collectExportRenames(sourceFile, checker, identifiers) { - var res = ts.createMap(); - forEachExportReference(sourceFile, function (node) { - var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; - if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { - // Unconditionally add an underscore in case `text` is a keyword. - res.set(text, makeUniqueName("_" + text, identifiers)); - } - }); - return res; - } - function convertExportsAccesses(sourceFile, exports, changes) { - forEachExportReference(sourceFile, function (node, isAssignmentLhs) { - if (isAssignmentLhs) { - return; - } - var text = node.name.text; - changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); - }); - } - function forEachExportReference(sourceFile, cb) { - sourceFile.forEachChild(function recur(node) { - if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { - var parent = node.parent; - cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); - } - node.forEachChild(recur); - }); - } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { - switch (statement.kind) { - case 212 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); - return false; - case 214 /* ExpressionStatement */: { - var expression = statement.expression; - switch (expression.kind) { - case 185 /* CallExpression */: { - if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { - // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); - } - return false; - } - case 198 /* BinaryExpression */: { - var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); - } - } - } - // falls through - default: - return false; - } - } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { - var declarationList = statement.declarationList; - var foundImport = false; - var newNodes = ts.flatMap(declarationList.declarations, function (decl) { - var name = decl.name, initializer = decl.initializer; - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { - // `const alias = module.exports;` can be removed. - foundImport = true; - return []; - } - if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); - } - else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); - } - else { - // Move it out to its own variable statement. - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); - } - }); - if (foundImport) { - // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - } - } - /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { - switch (name.kind) { - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: { - // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` - var tmp = makeUniqueName(propertyName, identifiers); - return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), - makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), - ]; - } - case 71 /* Identifier */: - // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; - default: - ts.Debug.assertNever(name); - } - } - function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { - if (!ts.isPropertyAccessExpression(left)) { - return false; - } - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { - // `const alias = module.exports;` or `module.exports = alias;` can be removed. - changes.deleteNode(sourceFile, statement); - } - else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); - } - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - return changedToDefaultExport; - } - } - else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { - convertNamedExport(sourceFile, statement, left.name, right, changes, exports); - } - return false; - var _a; - } - /** - * Convert `module.exports = { ... }` to individual exports.. - * We can't always do this if the module has interesting members -- then it will be a default export instead. - */ - function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { - switch (prop.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 269 /* ShorthandPropertyAssignment */: - case 270 /* SpreadAssignment */: - return undefined; - case 268 /* PropertyAssignment */: - return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); - case 153 /* MethodDeclaration */: - return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); - default: - ts.Debug.assertNever(prop); - } - }); - } - function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { - // If "originalKeywordKind" was set, this is e.g. `exports. - var text = propertyName.text; - var rename = exports.get(text); - if (rename !== undefined) { - /* - const _class = 0; - export { _class as class }; - */ - var newNodes = [ - makeConst(/*modifiers*/ undefined, rename, right), - makeExportDeclaration([ts.createExportSpecifier(rename, text)]), - ]; - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - } - else { - changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); - } - } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; - switch (exported.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: { - // `module.exports = function f() {}` --> `export default function f() {}` - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 203 /* ClassExpression */: { - // `module.exports = class C {}` --> `export default class C {}` - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 185 /* CallExpression */: - if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { - return convertReExportAll(exported.arguments[0], checker); - } - // falls through - default: - // `module.exports = 0;` --> `export default 0;` - return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; - } - } - function convertReExportAll(reExported, checker) { - // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` - var moduleSpecifier = reExported.text; - var moduleSymbol = checker.getSymbolAtLocation(reExported); - var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; - return exports.has("export=") - ? [[reExportDefault(moduleSpecifier)], true] - : !exports.has("default") - ? [[reExportStar(moduleSpecifier)], false] - // If there's some non-default export, must include both `export *` and `export default`. - : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; - } - function reExportStar(moduleSpecifier) { - return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); - } - function reExportDefault(moduleSpecifier) { - return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); - } - function convertExportsDotXEquals(name, exported) { - var modifiers = [ts.createToken(84 /* ExportKeyword */)]; - switch (exported.kind) { - case 190 /* FunctionExpression */: { - var expressionName = exported.name; - if (expressionName && expressionName.text !== name) { - // `exports.f = function g() {}` -> `export const f = function g() {}` - return exportConst(); - } - } - // falls through - case 191 /* ArrowFunction */: - // `exports.f = function() {}` --> `export function f() {}` - return functionExpressionToDeclaration(name, modifiers, exported); - case 203 /* ClassExpression */: - // `exports.C = class {}` --> `export class C {}` - return classExpressionToDeclaration(name, modifiers, exported); - default: - return exportConst(); - } - function exportConst() { - // `exports.x = 0;` --> `export const x = 0;` - return makeConst(modifiers, ts.createIdentifier(name), exported); - } - } - /** - * Converts `const <> = require("x");`. - * Returns nodes that will replace the variable declaration for the commonjs import. - * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. - */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { - switch (name.kind) { - case 178 /* ObjectBindingPattern */: { - var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { - return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) - ? undefined - : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); - }); - if (importSpecifiers) { - return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; - } - } - // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 179 /* ArrayBindingPattern */: { - /* - import x from "x"; - const [a, b, c] = x; - */ - var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); - return [ - makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), - makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), - ]; - } - case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); - default: - ts.Debug.assertNever(name); - } - } - /** - * Convert `import x = require("x").` - * Also converts uses like `x.y()` to `y()` and uses a named import. - */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { - var nameSymbol = checker.getSymbolAtLocation(name); - // Maps from module property name to name actually used. (The same if there isn't shadowing.) - var namedBindingsNames = ts.createMap(); - // True if there is some non-property use like `x()` or `f(x)`. - var needDefaultImport = false; - for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { - var use = _a[_i]; - if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { - // This was a use of a different symbol with the same name, due to shadowing. Ignore. - continue; - } - var parent = use.parent; - if (ts.isPropertyAccessExpression(parent)) { - var expression = parent.expression, propertyName = parent.name.text; - ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` - var idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); - } - changes.replaceNode(file, parent, ts.createIdentifier(idName)); - } - else { - needDefaultImport = true; - } - } - var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { - var propertyName = _a[0], idName = _a[1]; - return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); - })); - if (!namedBindings) { - // If it was unused, ensure that we at least import *something*. - needDefaultImport = true; - } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; - } - // Identifiers helpers - function makeUniqueName(name, identifiers) { - while (identifiers.original.has(name) || identifiers.additional.has(name)) { - name = "_" + name; - } - identifiers.additional.set(name, true); - return name; - } - function collectFreeIdentifiers(file) { - var map = ts.createMultiMap(); - file.forEachChild(function recur(node) { - if (ts.isIdentifier(node) && isFreeIdentifier(node)) { - map.add(node.text, node); - } - node.forEachChild(recur); - }); - return map; - } - function isFreeIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 183 /* PropertyAccessExpression */: - return parent.name !== node; - case 180 /* BindingElement */: - return parent.propertyName !== node; - default: - return true; - } - } - // Node helpers - function functionExpressionToDeclaration(name, additionalModifiers, fn) { - return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); - } - function classExpressionToDeclaration(name, additionalModifiers, cls) { - return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); - } - function makeSingleImport(localName, propertyName, moduleSpecifier) { - return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); - } - function makeImport(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); - } - function makeImportSpecifier(propertyName, name) { - return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); - } - function makeConst(modifiers, name, init) { - return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); - } - function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { - return ts.createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); - } - })(refactor = ts.refactor || (ts.refactor = {})); -})(ts || (ts = {})); +/// +/// /// /// /* @internal */ @@ -99478,7 +100695,7 @@ var ts; } else if (ts.isVariableStatement(node)) { var numInitializers = 0; - var lastInitializer = undefined; + var lastInitializer = void 0; for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.initializer) { @@ -99595,7 +100812,7 @@ var ts; switch (node.kind) { case 232 /* FunctionDeclaration */: case 233 /* ClassDeclaration */: - if (node.parent.kind === 272 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { + if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } @@ -99875,12 +101092,12 @@ var ts; var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); - var returnType = undefined; + var returnType; var parameters = []; var callArguments = []; var writes; usagesInScope.forEach(function (usage, name) { - var typeNode = undefined; + var typeNode; 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) {" @@ -100115,7 +101332,7 @@ var ts; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -100130,14 +101347,14 @@ var ts; changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else if (node.parent.kind === 214 /* 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.replaceNode(context.file, node.parent, newVariableStatement, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { var newVariableStatement = ts.createVariableStatement( @@ -100157,7 +101374,7 @@ var ts; } else { var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } } } @@ -100167,7 +101384,7 @@ var ts; return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function getContainingVariableDeclarationIfInList(node, scope) { - var prevNode = undefined; + var prevNode; while (node !== undefined && node !== scope) { if (ts.isVariableDeclaration(node) && node.initializer === prevNode && @@ -100192,16 +101409,16 @@ var ts; ts.Debug.assert(fileName === renameFilename); for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) { var change = textChanges_3[_b]; - var span_15 = change.span, newText = change.newText; + var span = change.span, newText = change.newText; var index = newText.indexOf(functionNameText); if (index !== -1) { - lastPos = span_15.start + delta + index; + lastPos = span.start + delta + index; // If the reference comes first, return immediately. if (!isDeclaredBeforeUse) { return lastPos; } } - delta += newText.length - span_15.length; + delta += newText.length - span.length; } } // If the declaration comes first, return the position of the last occurrence. @@ -100210,7 +101427,7 @@ var ts; return lastPos; } function getFirstDeclaration(type) { - var firstDeclaration = undefined; + var firstDeclaration; var symbol = type.symbol; if (symbol && symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -100332,7 +101549,7 @@ var ts; 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 prevMember; var allProperties = true; for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { var member = members_6[_i]; @@ -100354,7 +101571,7 @@ var ts; } function getNodeToInsertConstantBefore(node, scope) { ts.Debug.assert(!ts.isClassLike(scope)); - var prevScope = undefined; + var prevScope; for (var curr = node; curr !== scope; curr = curr.parent) { if (isScope(curr)) { prevScope = curr; @@ -100362,7 +101579,7 @@ var ts; } for (var curr = (prevScope || node).parent;; curr = curr.parent) { if (isBlockLike(curr)) { - var prevStatement = undefined; + var prevStatement = void 0; for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement.pos > node.pos) { @@ -100427,13 +101644,13 @@ var ts; var visibleDeclarationsInExtractedRange = []; var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID var exposedVariableDeclarations = []; - var firstExposedNonVariableDeclaration = undefined; + var firstExposedNonVariableDeclaration; var expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : undefined; - var expressionDiagnostic = undefined; + var expressionDiagnostic; if (expression === undefined) { var statements = targetRange.range; var start = ts.first(statements).getStart(); @@ -100511,7 +101728,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_10 = function (i) { + var _loop_12 = 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 @@ -100521,7 +101738,7 @@ var ts; constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); } var hasWrite = false; - var readonlyClassPropertyWrite = undefined; + var readonlyClassPropertyWrite; usagesPerScope[i].usages.forEach(function (value) { if (value.usage === 2 /* Write */) { hasWrite = true; @@ -100551,7 +101768,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_10(i); + _loop_12(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { @@ -100819,165 +102036,251 @@ var ts; })(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) { - var refactorName = "Install missing types package"; - var actionName = "install"; - var description = "Install missing types package"; - refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { - // Then it will be available via `fixCannotFindModule`. - return undefined; - } - var action = getAction(context); - return action && [ - { - name: refactorName, - description: 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 242 /* ImportDeclaration */: - case 252 /* 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 description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); - refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); - function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition, program = context.program; - if (!ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { - return undefined; - } - var importInfo = getConvertibleImportAtPosition(file, startPosition); - if (!importInfo) { - return undefined; - } - var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); - if (!(resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) { - return undefined; - } - return [ - { - name: actionName, - description: description, - actions: [ - { - description: 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 241 /* ImportEqualsDeclaration */: - var eq = node; - var moduleReference = eq.moduleReference; - return moduleReference.kind === 252 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression) - ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression } - : undefined; - case 242 /* ImportDeclaration */: - var d = node; - var importClause = d.importClause; - return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* 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 244 /* NamespaceImport */: - case 252 /* 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 = {})); -/// -/// -/// /// -/// -/// +/* @internal */ +var ts; +(function (ts) { + var sourcemaps; + (function (sourcemaps) { + sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; + function decode(host, mapPath, map, program, fallbackCache) { + if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } + var currentDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot || currentDirectory; + var decodedMappings; + var generatedOrderedMappings; + var sourceOrderedMappings; + return { + getOriginalPosition: getOriginalPosition, + getGeneratedPosition: getGeneratedPosition + }; + function getGeneratedPosition(loc) { + var maps = getGeneratedOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { + return loc; + } + return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos + } + function getOriginalPosition(loc) { + var maps = getSourceOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos + } + function getSourceFileLike(fileName, location) { + // Lookup file in program, if provided + var file = program && program.getSourceFile(fileName); + if (!file) { + // Otherwise check the cache (which may hit disk) + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + return fallbackCache.get(path); + } + return file; + } + function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { + var file = getSourceFileLike(fileName, directory); + if (!file) { + return -1; + } + return ts.getPositionOfLineAndCharacter(file, line, character); + } + function getDecodedMappings() { + return decodedMappings || (decodedMappings = calculateDecodedMappings()); + } + function getSourceOrderedMappings() { + return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); + } + function getGeneratedOrderedMappings() { + return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); + } + function calculateDecodedMappings() { + var state = { + encodedText: map.mappings, + currentNameIndex: undefined, + sourceMapNamesLength: map.names ? map.names.length : undefined, + currentEmittedColumn: 0, + currentEmittedLine: 0, + currentSourceColumn: 0, + currentSourceLine: 0, + currentSourceIndex: 0, + positions: [], + decodingIndex: 0, + processPosition: processPosition, + }; + while (!hasCompletedDecoding(state)) { + decodeSinglePosition(state); + if (state.error) { + host.log("Encountered error while decoding sourcemap found at " + mapPath + ": " + state.error); + return []; + } + } + return state.positions; + } + function compareProcessedPositionSourcePositions(a, b) { + return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || + ts.compareValues(a.sourcePosition, b.sourcePosition); + } + function compareProcessedPositionEmittedPositions(a, b) { + return ts.compareValues(a.emittedPosition, b.emittedPosition); + } + function processPosition(position) { + var sourcePath = map.sources[position.sourceIndex]; + return { + emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), + sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), + sourcePath: sourcePath, + }; + } + } + sourcemaps.decode = decode; + function hasCompletedDecoding(state) { + return state.decodingIndex === state.encodedText.length; + } + function decodeSinglePosition(state) { + while (state.decodingIndex < state.encodedText.length) { + var char = state.encodedText.charCodeAt(state.decodingIndex); + if (char === 59 /* semicolon */) { + // New line + state.currentEmittedLine++; + state.currentEmittedColumn = 0; + state.decodingIndex++; + continue; + } + if (char === 44 /* comma */) { + // Next entry is on same line - no action needed + state.decodingIndex++; + continue; + } + // Read the current position + // 1. Column offset from prev read jsColumn + state.currentEmittedColumn += base64VLQFormatDecode(); + // Incorrect emittedColumn dont support this map + if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { + return; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { + return; + } + // 2. Relative sourceIndex + state.currentSourceIndex += base64VLQFormatDecode(); + // Incorrect sourceIndex dont support this map + if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { + return; + } + // Dont support reading mappings that dont have information about original source position + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { + return; + } + // 3. Relative sourceLine 0 based + state.currentSourceLine += base64VLQFormatDecode(); + // Incorrect sourceLine dont support this map + if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { + return; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { + return; + } + // 4. Relative sourceColumn 0 based + state.currentSourceColumn += base64VLQFormatDecode(); + // Incorrect sourceColumn dont support this map + if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { + return; + } + // 5. Check if there is name: + if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { + if (state.currentNameIndex === undefined) { + state.currentNameIndex = 0; + } + state.currentNameIndex += base64VLQFormatDecode(); + // Incorrect nameIndex dont support this map + // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap + // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { + // return; + // } + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { + return; + } + // Entry should be complete + capturePosition(); + return; + } + createErrorIfCondition(/*condition*/ true, "No encoded entry found"); + return; + function capturePosition() { + state.positions.push(state.processPosition({ + emittedColumn: state.currentEmittedColumn, + emittedLine: state.currentEmittedLine, + sourceColumn: state.currentSourceColumn, + sourceIndex: state.currentSourceIndex, + sourceLine: state.currentSourceLine, + nameIndex: state.currentNameIndex + })); + } + function createErrorIfCondition(condition, errormsg) { + if (state.error) { + // An error was already reported + return true; + } + if (condition) { + state.error = errormsg; + } + return condition; + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; state.decodingIndex++) { + if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { + return; + } + // 6 digit number + var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + function base64FormatDecode(char) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + } + function isSourceMappingSegmentEnd(encodedText, pos) { + return (pos === encodedText.length || + encodedText.charCodeAt(pos) === 44 /* comma */ || + encodedText.charCodeAt(pos) === 59 /* semicolon */); + } + })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); +})(ts || (ts = {})); /// /// /// @@ -100999,6 +102302,7 @@ var ts; /// /// /// +/// /// /// /// @@ -101008,10 +102312,11 @@ var ts; /// /// /// +/// var ts; (function (ts) { /** The version of the language service API */ - ts.servicesVersion = "0.7"; + ts.servicesVersion = "0.8"; 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) : @@ -101071,104 +102376,15 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { - ts.scanner.setTextPos(pos); - while (pos < end) { - var token = ts.scanner.scan(); - var textPos = ts.scanner.getTextPos(); - if (textPos <= end) { - if (token === 71 /* Identifier */) { - ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(this) + " to have an Identifier in its trivia"); - } - nodes.push(createNode(token, pos, textPos, this)); - } - pos = textPos; - if (token === 1 /* EndOfFileToken */) { - break; - } - } - return pos; - }; - NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, this); - list._children = []; - var pos = nodes.pos; - for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { - var node = nodes_9[_i]; - if (pos < node.pos) { - pos = this.addSyntheticNodes(list._children, pos, node.pos); - } - list._children.push(node); - pos = node.end; - } - if (pos < nodes.end) { - this.addSyntheticNodes(list._children, pos, nodes.end); - } - return list; - }; - NodeObject.prototype.createChildren = function (sourceFile) { - var _this = this; - if (!ts.isNodeKind(this.kind)) { - this._children = ts.emptyArray; - return; - } - if (ts.isJSDocCommentContainingNode(this)) { - /** 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 = []; - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - var pos = this.pos; - var processNode = function (node) { - pos = _this.addSyntheticNodes(children, pos, node.pos); - children.push(node); - pos = node.end; - }; - var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); - } - 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) { - this.addSyntheticNodes(children, pos, this.end); - } - ts.scanner.setText(undefined); - this._children = children; - }; NodeObject.prototype.getChildCount = function (sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children.length; + return this.getChildren(sourceFile).length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children[index]; + return this.getChildren(sourceFile)[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; + return this._children || (this._children = createChildren(this, sourceFile)); }; NodeObject.prototype.getFirstToken = function (sourceFile) { this.assertHasRealPosition(); @@ -101195,6 +102411,69 @@ var ts; }; return NodeObject; }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified 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 = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 71 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } var TokenOrIdentifierObject = /** @class */ (function () { function TokenOrIdentifierObject(pos, end) { // Set properties in same order as NodeObject @@ -101443,7 +102722,7 @@ var ts; */ function findInheritedJSDocComments(declaration, propertyName, typeChecker) { var foundDocs = false; - return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { + return ts.flatMap(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { if (foundDocs) { return ts.emptyArray; } @@ -101460,20 +102739,6 @@ var ts; 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) { @@ -101530,20 +102795,8 @@ var ts; } function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); - if (name) { - var result_6 = ts.getTextOfIdentifierOrLiteral(name); - if (result_6 !== undefined) { - return result_6; - } - if (name.kind === 146 /* ComputedPropertyName */) { - var expr = name.expression; - if (expr.kind === 183 /* PropertyAccessExpression */) { - return expr.name.text; - } - return ts.getTextOfIdentifierOrLiteral(expr); - } - } - return undefined; + return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) : + name.kind === 146 /* ComputedPropertyName */ && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined); } function visit(node) { switch (node.kind) { @@ -101918,6 +103171,31 @@ var ts; return ThrottledCancellationToken; }()); ts.ThrottledCancellationToken = ThrottledCancellationToken; + /* @internal */ + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } + ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -101931,6 +103209,7 @@ var ts; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } + var sourcemappedFileCache; function log(message) { if (host.log) { host.log(message); @@ -102023,6 +103302,10 @@ var ts; // 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; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourcemappedFileCache = createSourceFileLikeCache(host); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); @@ -102130,18 +103413,25 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return semanticDiagnostics.concat(declarationDiagnostics); } + function getSuggestionDiagnostics(fileName) { + synchronizeHostData(); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program); + } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } + if (options === void 0) { options = ts.defaultPreferences; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), fullPreferences); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName, preferences); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -102152,9 +103442,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { - return undefined; - } - if (ts.isLabelName(node)) { + // Avoid giving quickInfo for the sourceFile as a whole. return undefined; } var typeChecker = program.getTypeChecker(); @@ -102163,6 +103451,11 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 71 /* Identifier */: + if (ts.isLabelName(node)) { + // Type here will be 'any', avoid displaying this. + return undefined; + } + // falls through case 183 /* PropertyAccessExpression */: case 145 /* QualifiedName */: case 99 /* ThisKeyword */: @@ -102170,27 +103463,25 @@ var ts; case 97 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); - if (type) { - return { - 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(typeChecker) : undefined, - tags: type.symbol ? type.symbol.getJsDocTags() : undefined - }; - } + return type && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type.symbol ? type.symbol.getJsDocTags() : undefined + }; } return undefined; } - var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; return { - kind: displayPartsDocumentationsAndKind.symbolKind, + kind: symbolKind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: displayPartsDocumentationsAndKind.displayParts, - documentation: displayPartsDocumentationsAndKind.documentation, - tags: displayPartsDocumentationsAndKind.tags + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: displayParts, + documentation: documentation, + tags: tags, }; } function getSymbolAtLocationForQuickInfo(node, checker) { @@ -102198,32 +103489,156 @@ var ts; && ts.isPropertyAssignment(node.parent) && node.parent.name === node) { var type = checker.getContextualType(node.parent.parent); - if (type) { - var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); - if (property) { - return property; - } + var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); + if (property) { + return property; } } return checker.getSymbolAtLocation(node); } + var sourceMapCommentRegExp = /^\/\/[@#] sourceMappingURL=(.+)$/gm; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; + } + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + sourceMapCommentRegExp.lastIndex = starts[index]; + var comment = sourceMapCommentRegExp.exec(mappedFile.text); + if (comment) { + return comment[1]; + } + } + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, program, sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function makeGetTargetOfMappedPosition(extract, create) { + return getTargetOfMappedPosition; + function getTargetOfMappedPosition(input) { + var info = extract(input); + if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { + var file = program.getSourceFile(info.fileName); + if (!file) { + var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); + file = sourcemappedFileCache.get(path); + } + if (!file) { + return input; + } + var mapper = getSourceMapper(info.fileName, file); + var newLoc = mapper.getOriginalPosition(info); + if (newLoc === info) + return input; + return getTargetOfMappedPosition(create(newLoc, input)); + } + return input; + } + } + var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + containerKind: info.containerKind, + containerName: info.containerName, + fileName: newLoc.fileName, + kind: info.kind, + name: info.name, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + } + }); }); + function getTargetOfMappedDeclarationFiles(infos) { + return ts.map(infos, getTargetOfMappedDeclarationInfo); + } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position)); } function getDefinitionAndBoundSpan(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + var result = ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + if (!result) + return result; + var mappedDefs = getTargetOfMappedDeclarationFiles(result.definitions); + if (mappedDefs === result.definitions) { + return result; + } + return { + definitions: mappedDefs, + textSpan: result.textSpan + }; } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); + return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position)); } /// Goto implementation + var getTargetOfMappedImplementationLocation = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + fileName: newLoc.fileName, + kind: info.kind, + displayParts: info.displayParts, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + } + }); }); + function getTargetOfMappedImplementationLocations(infos) { + return ts.map(infos, getTargetOfMappedImplementationLocation); + } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); + return getTargetOfMappedImplementationLocations(ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position)); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -102443,29 +103858,32 @@ var ts; } return []; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); 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, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); }); } - function getCombinedCodeFix(scope, fixId, formatOptions) { + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions) { + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -102479,6 +103897,7 @@ var ts; : Promise.reject("Host does not implement `installPackage`"); default: ts.Debug.fail(); + // TODO: Debug.assertNever(action); will only work if there is more than one type. } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -102562,7 +103981,7 @@ var ts; if (!ts.isInComment(sourceFile, matchPosition)) { continue; } - var descriptor = undefined; + var descriptor = void 0; for (var i = 0; i < descriptors.length; i++) { if (matchArray[i + firstDescriptorCaptureIndex]) { descriptor = descriptors[i]; @@ -102646,7 +104065,7 @@ var ts; var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } - function getRefactorContext(file, positionOrRange, formatOptions) { + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; return { file: file, @@ -102656,23 +104075,27 @@ var ts; host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, + preferences: preferences, }; } - function getApplicableRefactors(fileName, positionOrRange) { + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); } - function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -103050,24 +104473,23 @@ var ts; return textSpan(node); } if (node.kind === 198 /* BinaryExpression */) { - var binaryExpression = node; + var _a = node, left = _a.left, operatorToken = _a.operatorToken; // 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 (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } - if (binaryExpression.operatorToken.kind === 58 /* EqualsToken */ && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.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 /* CommaToken */) { - return spanInNode(binaryExpression.left); + if (operatorToken.kind === 26 /* CommaToken */) { + return spanInNode(left); } } if (ts.isExpressionNode(node)) { @@ -103095,46 +104517,49 @@ var ts; break; } } - // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 268 /* 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 === 188 /* 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); - } - // initializer of variable/parameter declaration go to previous node - if ((node.parent.kind === 230 /* VariableDeclaration */ || - node.parent.kind === 148 /* Parameter */)) { - var paramOrVarDecl = node.parent; - if (paramOrVarDecl.initializer === node || - paramOrVarDecl.type === node || - ts.isAssignmentOperator(node.kind)) { - return spanInPreviousNode(node); + switch (node.parent.kind) { + case 268 /* PropertyAssignment */: + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + return spanInNode(node.parent.initializer); + } + break; + case 188 /* TypeAssertionExpression */: + // Breakpoint in type assertion goes to its operand + if (node.parent.type === node) { + return spanInNextNode(node.parent.type); + } + break; + case 230 /* VariableDeclaration */: + case 148 /* Parameter */: { + // initializer of variable/parameter declaration go to previous node + var _b = node.parent, initializer = _b.initializer, type = _b.type; + if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; } - } - if (node.parent.kind === 198 /* 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); + case 198 /* BinaryExpression */: { + var left = node.parent.left; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + break; } + default: + // return type of function go to previous token + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } } // Default go to parent to set the breakpoint return spanInNode(node.parent); } } function textSpanFromVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ && - variableDeclaration.parent.declarations[0] === variableDeclaration) { + if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) { // First declaration - include let keyword return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); } @@ -103159,7 +104584,7 @@ var ts; variableDeclaration.parent.parent.kind === 220 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ && + if (ts.isVariableDeclarationList(variableDeclaration.parent) && 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 @@ -103717,8 +105142,7 @@ 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(), + category: ts.diagnosticCategoryName(diagnostic), code: diagnostic.code }; } @@ -103768,7 +105192,7 @@ var ts; }; LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { var newLine = ts.getNewLineOrDefaultFromHost(this.host); - return ts.realizeDiagnostics(diagnostics, newLine); + return realizeDiagnostics(diagnostics, newLine); }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; @@ -103806,6 +105230,10 @@ var ts; return _this.realizeDiagnostics(diagnostics); }); }; + LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + }; LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { var _this = this; return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { @@ -103936,16 +105364,16 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = options === undefined ? undefined : JSON.parse(options); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -104102,8 +105530,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { - var ref = refs_2[_i]; + for (var _i = 0, refs_3 = refs; _i < refs_3.length; _i++) { + var ref = refs_3[_i]; result.push({ path: ts.normalizeSlashes(ref.fileName), position: ref.pos, diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 74ec9b4a722..7bc03ae0a6c 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -64,8 +64,15 @@ var ts; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; - DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message"; })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + function diagnosticCategoryName(d, lowerCase) { + if (lowerCase === void 0) { lowerCase = true; } + var name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; + } + ts.diagnosticCategoryName = diagnosticCategoryName; var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; @@ -81,6 +88,37 @@ var ts; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + function _contextuallyTypePragmas(args) { + return args; + } + ts.commentPragmas = _contextuallyTypePragmas({ + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true } + ], + kind: 1 + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 + }, + "ts-check": { + kind: 2 + }, + "ts-nocheck": { + kind: 2 + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 + }, + }); })(ts || (ts = {})); var ts; (function (ts) { @@ -141,7 +179,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.8"; + ts.versionMajorMinor = "2.9"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { @@ -156,6 +194,10 @@ var ts; })(ts || (ts = {})); (function (ts) { ts.emptyArray = []; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -658,18 +700,6 @@ var ts; }; } ts.singleIterator = singleIterator; - function span(array, f) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (!f(array[i], i)) { - return [array.slice(0, i), array.slice(i)]; - } - } - return [array.slice(0), []]; - } - return undefined; - } - ts.span = span; function spanMap(array, keyfn, mapfn) { var result; if (array) { @@ -1008,7 +1038,7 @@ var ts; } ts.elementAt = elementAt; function firstOrUndefined(array) { - return elementAt(array, 0); + return array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -1017,7 +1047,7 @@ var ts; } ts.first = first; function lastOrUndefined(array) { - return elementAt(array, -1); + return array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -1200,19 +1230,21 @@ var ts; } ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } var result = createMap(); 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); + result.set(makeKey(value), makeValue(value)); } return result; } ts.arrayToMap = arrayToMap; function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } 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; + result[makeKey(value)] = makeValue(value); } return result; } @@ -1221,6 +1253,20 @@ var ts; return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } ts.arrayToSet = arrayToSet; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -1278,15 +1324,6 @@ var ts; } } } - function group(values, getGroupId) { - var groupIdToGroup = createMultiMap(); - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - groupIdToGroup.add(getGroupId(value), value); - } - return arrayFrom(groupIdToGroup.values()); - } - ts.group = group; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -1394,7 +1431,6 @@ var ts; return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.formatStringFromArgs = formatStringFromArgs; - ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } @@ -1736,6 +1772,10 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAreDeclarationMapsEnabled(options) { + return !!(options.declaration && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined @@ -2096,7 +2136,6 @@ 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); }); @@ -2127,7 +2166,7 @@ var ts; } } }; - for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + for (var _i = 0, _b = sort(files, compareStringsCaseSensitive); _i < _b.length; _i++) { var current = _b[_i]; _loop_1(current); } @@ -2137,7 +2176,7 @@ var ts; return; } } - for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -2160,7 +2199,7 @@ var ts; } includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -2503,7 +2542,7 @@ var ts; } ts.matchedText = matchedText; function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; + var matchedValue; var longestMatchPrefixLength = -1; for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { var v = values_2[_i]; @@ -2585,6 +2624,38 @@ var ts; return t === undefined ? undefined : [t]; } ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(ts || (ts = {})); var ts; (function (ts) { @@ -2600,6 +2671,269 @@ var ts; FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); + var PollingInterval; + (function (PollingInterval) { + PollingInterval[PollingInterval["High"] = 2000] = "High"; + PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; + PollingInterval[PollingInterval["Low"] = 250] = "Low"; + })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); + function getPriorityValues(highPriorityValue) { + var mediumPriorityValue = highPriorityValue * 2; + var lowPriorityValue = mediumPriorityValue * 4; + return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; + } + function pollingInterval(watchPriority) { + return pollingIntervalsForPriority[watchPriority]; + } + var pollingIntervalsForPriority = getPriorityValues(250); + function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { + return host.watchFile(fileName, callback, pollingInterval(watchPriority)); + } + ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; + ts.missingFileModifiedTime = new Date(0); + function createPollingIntervalBasedLevels(levels) { + return _a = {}, + _a[PollingInterval.Low] = levels.Low, + _a[PollingInterval.Medium] = levels.Medium, + _a[PollingInterval.High] = levels.High, + _a; + var _a; + } + var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); + ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); + function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + } + function getCustomLevels(baseVariable) { + var customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + var customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + var customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + var customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && + createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels); + } + } + ts.setCustomPollingValues = setCustomPollingValues; + function createDynamicPriorityPollingWatchFile(host) { + var watchedFiles = []; + var changedFilesInLastPoll = []; + var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low); + var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium); + var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High); + return watchFile; + function watchFile(fileName, callback, defaultPollingInterval) { + var file = { + fileName: fileName, + callback: callback, + unchangedPolls: 0, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + var queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } + else { + ts.Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(queue) { + pollQueue(changedFilesInLastPoll, PollingInterval.Low, 0, changedFilesInLastPoll.length); + pollPollingIntervalQueue(queue); + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(PollingInterval.Low); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + var needsVisit = queue.length; + var definedValueCopyToIndex = pollIndex; + for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + polled++; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); + if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + } + else if (fileChanged) { + watchedFile.unchangedPolls = 0; + if (queue !== changedFilesInLastPoll) { + queue[pollIndex] = undefined; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } + else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } + else if (queue === changedFilesInLastPoll) { + watchedFile.unchangedPolls = 1; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, PollingInterval.Low); + } + else if (pollingInterval !== PollingInterval.High) { + watchedFile.unchangedPolls++; + queue[pollIndex] = undefined; + addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); + } + if (queue[pollIndex]) { + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case PollingInterval.Low: + return lowPollingIntervalQueue; + case PollingInterval.Medium: + return mediumPollingIntervalQueue; + case PollingInterval.High: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + } + function getModifiedTime(fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + } + ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; + function onWatchedFileStat(watchedFile, modifiedTime) { + var oldTime = watchedFile.mtime.getTime(); + var newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + var eventKind = oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + watchedFile.callback(watchedFile.fileName, eventKind); + return true; + } + return false; + } + ts.onWatchedFileStat = onWatchedFileStat; + function createRecursiveDirectoryWatcher(host) { + return createDirectoryWatcher; + function createDirectoryWatcher(dirName, callback) { + var watcher = host.watchDirectory(dirName, function (fileName) { + callback(fileName); + updateChildWatches(result, callback); + }); + var result = { + close: function () { + watcher.close(); + result.childWatches.forEach(ts.closeFileWatcher); + result = undefined; + }, + dirName: dirName, + childWatches: ts.emptyArray + }; + updateChildWatches(result, callback); + return result; + } + function updateChildWatches(watcher, callback) { + if (watcher) { + watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + } + } + function watchChildDirectories(parentDir, existingChildWatches, callback) { + var newChildWatches; + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(ts.getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return newChildWatches || ts.emptyArray; + function createAndAddChildDirectoryWatcher(childName) { + var result = createDirectoryWatcher(ts.getNormalizedAbsolutePath(childName, parentDir), callback); + addChildDirectoryWatcher(result); + } + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + } + ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -2628,75 +2962,104 @@ var ts; catch (_a) { _crypto = undefined; } - var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } - function createMD5HashUsingNativeCrypto(data) { - var hash = _crypto.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - } - function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - var fileWatcherCallbacks = ts.createMultiMap(); - return { addFile: addFile, removeFile: removeFile }; - function reduceDirWatcherRefCountForFile(fileName) { - var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers.get(dirName); - if (watcher) { - watcher.referenceCount -= 1; - if (watcher.referenceCount <= 0) { - watcher.close(); - dirWatchers.delete(dirName); - } - } - } - function addDirWatcher(dirPath) { - var watcher = dirWatchers.get(dirPath); - if (watcher) { - watcher.referenceCount += 1; - return; - } - watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); - watcher.referenceCount = 1; - dirWatchers.set(dirPath, watcher); - return; - } - function addFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.add(filePath, callback); - } - function addFile(fileName, callback) { - addFileWatcherCallback(fileName, callback); - addDirWatcher(ts.getDirectoryPath(fileName)); - return { fileName: fileName, callback: callback }; - } - function removeFile(watchedFile) { - removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback); - reduceDirWatcherRefCountForFile(watchedFile.fileName); - } - function removeFileWatcherCallback(filePath, callback) { - fileWatcherCallbacks.remove(filePath, callback); - } - function fileEventHandler(eventName, relativeFileName, baseDirPath) { - var fileName = !ts.isString(relativeFileName) - ? undefined - : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename")) { - var callbacks = fileWatcherCallbacks.get(fileName); - if (callbacks) { - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); - } - } - } - } - } - var watchedFileSet = createWatchedFileSet(); + var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; + var platform = _os.platform(); + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + var tscWatchFile = process.env.TSC_WATCHFILE; + var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; + var dynamicPollingWatchFile; + var nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + readFile: readFile, + writeFile: writeFile, + watchFile: getWatchFile(), + watchDirectory: getWatchDirectory(), + resolvePath: function (path) { return _path.resolve(path); }, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: function (directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, + readDirectory: readDirectory, + getModifiedTime: getModifiedTime, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (_a) { } + return 0; + }, + exit: function (exitCode) { + process.exit(exitCode); + }, + realpath: function (path) { + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } + }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (_a) { + } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout, + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, + setBlocking: function () { + if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { + process.stdout._handle.setBlocking(true); + } + }, + base64decode: Buffer.from ? function (input) { + return Buffer.from(input, "base64").toString("utf8"); + } : function (input) { + return new Buffer(input, "base64").toString("utf8"); + }, + base64encode: Buffer.from ? function (input) { + return Buffer.from(input).toString("base64"); + } : function (input) { + return new Buffer(input).toString("base64"); + } + }; + return nodeSystem; function isFileSystemCaseSensitive() { if (platform === "win32" || platform === "win64") { return false; @@ -2709,40 +3072,154 @@ var ts; return ch === up ? ch.toLowerCase() : up; }); } - var platform = _os.platform(); - var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function getWatchFile() { + switch (tscWatchFile) { + case "PriorityPollingInterval": + return fsWatchFile; + case "DynamicPriorityPolling": + return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + case "UseFsEvents": + return watchFileUsingFsWatch; + case "UseFsEventsWithFallbackDynamicPolling": + dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }); + return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile); + case "UseFsEventsOnParentDirectory": + return createNonPollingWatchFile(); + } + return useNonPollingWatchers ? + createNonPollingWatchFile() : + function (fileName, callback) { return fsWatchFile(fileName, callback); }; + } + function getWatchDirectory() { + var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); + if (fsSupportsRecursive) { + return watchDirectoryUsingFsWatch; + } + var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? + createWatchDirectoryUsing(fsWatchFile) : + tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? + createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : + watchDirectoryUsingFsWatch; + var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ + filePathComparer: useCaseSensitiveFileNames ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive, + directoryExists: directoryExists, + getAccessileSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, + watchDirectory: watchDirectory + }); + return function (directoryName, callback, recursive) { + if (recursive) { + return watchDirectoryRecursively(directoryName, callback); + } + watchDirectory(directoryName, callback); + }; + } + function createNonPollingWatchFile() { + var fileWatcherCallbacks = ts.createMultiMap(); + var dirWatchers = ts.createMap(); + var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback) { + var filePath = toCanonicalName(fileName); + fileWatcherCallbacks.add(filePath, callback); + var dirPath = ts.getDirectoryPath(filePath) || "."; + var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath); + watcher.referenceCount++; + return { + close: function () { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } + else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath) { + var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { + var fileName = !ts.isString(relativeFileName) + ? undefined + : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { + var fileCallback = callbacks_1[_i]; + fileCallback(fileName, FileWatcherEventKind.Changed); + } + } + }); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } + } function fsWatchFile(fileName, callback, pollingInterval) { _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + var eventKind; 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) { + var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + return; + } + eventKind = FileWatcherEventKind.Deleted; + } + else if (isPreviouslyDeleted) { + eventKind = FileWatcherEventKind.Created; + } + else if (+curr.mtime === +prev.mtime) { return; } + else { + eventKind = FileWatcherEventKind.Changed; + } callback(fileName, eventKind); } } - function fsWatchDirectory(directoryName, callback, recursive) { + function createFileWatcherCallback(callback) { + return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + } + function createFsWatchCallbackForFileWatcherCallback(fileName, callback) { + return function (eventName) { + if (eventName === "rename") { + callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + } + else { + callback(fileName, FileWatcherEventKind.Changed); + } + }; + } + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) { + return function (eventName, relativeFileName) { + if (eventName === "rename") { + callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); + } + }; + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) { var options; - var watcher = !directoryExists(directoryName) ? - watchMissingDirectory() : - watchPresentDirectory(); + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); return { close: function () { watcher.close(); + watcher = undefined; } }; - function watchPresentDirectory() { + function invokeCallbackAndUpdateWatcher(createWatcher) { + callback("rename", ""); + if (watcher) { + watcher.close(); + watcher = createWatcher(); + } + } + function watchPresentFileSystemEntry() { if (options === undefined) { if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; @@ -2751,24 +3228,40 @@ var ts; options = { persistent: true }; } } - var dirWatcher = _fs.watch(directoryName, options, callback); - dirWatcher.on("error", function () { - if (!directoryExists(directoryName)) { - watcher = watchMissingDirectory(); - callback("rename", ""); - } - }); - return dirWatcher; + try { + var presentWatcher = _fs.watch(fileOrDirectory, options, callback); + presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); + return presentWatcher; + } + catch (e) { + return watchPresentFileSystemEntryWithFsWatchFile(); + } } - function watchMissingDirectory() { - return fsWatchFile(directoryName, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { - watcher.close(); - watcher = watchPresentDirectory(); - callback("rename", ""); - } - }); + function watchPresentFileSystemEntryWithFsWatchFile() { + return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval); } + function watchMissingFileSystemEntry() { + return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { + invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); + } + }, pollingInterval); + } + } + function watchFileUsingFsWatch(fileName, callback, pollingInterval) { + return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, fsWatchFile, pollingInterval); + } + function createWatchFileUsingDynamicWatchFile(watchFile) { + return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback), false, watchFile, pollingInterval); }; + } + function fsWatchDirectory(directoryName, callback, recursive) { + return fsWatch(directoryName, 1, callback, !!recursive, fsWatchFile); + } + function watchDirectoryUsingFsWatch(directoryName, callback, recursive) { + return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive); + } + function createWatchDirectoryUsing(fsWatchFile) { + return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); }; } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { @@ -2863,103 +3356,23 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - var nodeSystem = { - clearScreen: function () { - process.stdout.write("\x1Bc"); - }, - args: process.argv.slice(2), - newLine: _os.EOL, - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - write: function (s) { - process.stdout.write(s); - }, - readFile: readFile, - writeFile: writeFile, - watchFile: function (fileName, callback, pollingInterval) { - if (useNonPollingWatchers) { - var watchedFile_1 = watchedFileSet.addFile(fileName, callback); - return { - close: function () { return watchedFileSet.removeFile(watchedFile_1); } - }; - } - else { - return fsWatchFile(fileName, callback, pollingInterval); - } - }, - watchDirectory: function (directoryName, callback, recursive) { - 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, - directoryExists: directoryExists, - createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { - _fs.mkdirSync(directoryName); - } - }, - getExecutingFilePath: function () { - return __filename; - }, - getCurrentDirectory: function () { - return process.cwd(); - }, - getDirectories: getDirectories, - getEnvironmentVariable: function (name) { - return process.env[name] || ""; - }, - readDirectory: readDirectory, - getModifiedTime: function (path) { - try { - return _fs.statSync(path).mtime; - } - catch (e) { - return undefined; - } - }, - createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, - getMemoryUsage: function () { - if (global.gc) { - global.gc(); - } - return process.memoryUsage().heapUsed; - }, - getFileSize: function (path) { - try { - var stat = _fs.statSync(path); - if (stat.isFile()) { - return stat.size; - } - } - catch (_a) { } - return 0; - }, - exit: function (exitCode) { - process.exit(exitCode); - }, - realpath: function (path) { - try { - return _fs.realpathSync(path); - } - catch (_a) { - return path; - } - }, - debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), - tryEnableSourceMapsForHost: function () { - try { - require("source-map-support").install(); - } - catch (_a) { - } - }, - setTimeout: setTimeout, - clearTimeout: clearTimeout - }; - return nodeSystem; + function getModifiedTime(path) { + try { + return _fs.statSync(path).mtime; + } + catch (e) { + return undefined; + } + } + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + function createMD5HashUsingNativeCrypto(data) { + var hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -3023,6 +3436,7 @@ var ts; return sys; })(); if (ts.sys && ts.sys.getEnvironmentVariable) { + setCustomPollingValues(ts.sys); ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) ? 1 : 0; @@ -3616,6 +4030,7 @@ var ts; Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), 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}'."), @@ -3687,7 +4102,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), 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."), @@ -3727,6 +4142,8 @@ var ts; 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."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), 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."), @@ -3860,7 +4277,7 @@ var ts; Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), - Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), @@ -3904,6 +4321,8 @@ var ts; Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused."), 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."), @@ -3963,6 +4382,7 @@ var ts; 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."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), 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."), @@ -3983,14 +4403,20 @@ var ts; 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"), + JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), 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}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), 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}'"), + Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{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"), @@ -4027,6 +4453,33 @@ var ts; Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), + Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_this_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_this_to_all_unresolved_variables_matching_a_member_name_95037", "Add 'this.' to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), }; })(ts || (ts = {})); var ts; @@ -4240,9 +4693,9 @@ var ts; return false; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; - function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 && + text.charCodeAt(start + 2) === 33; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { @@ -4270,18 +4723,15 @@ var ts; ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } - if (nodeIsMissing(node)) { - return ""; - } - var text = sourceFile.text; - return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; - function getTextOfNodeFromSourceText(sourceText, node) { + function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -4356,8 +4806,7 @@ var ts; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 237 && - (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + return ts.isModuleDeclaration(node) && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; function isModuleWithStringLiteralName(node) { @@ -4386,18 +4835,19 @@ var ts; } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { - if (!node || !isAmbientModule(node)) { - return false; - } + return isAmbientModule(node) && isModuleAugmentationExternal(node); + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isModuleAugmentationExternal(node) { switch (node.parent.kind) { case 272: return ts.isExternalModule(node.parent); case 238: - return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } - ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -4463,6 +4913,10 @@ var ts; } } ts.isAnyImportSyntax = isAnyImportSyntax; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -4521,6 +4975,11 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { + var start = ts.skipTrivia(sourceFile.text, startNode.pos); + return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); + } + ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -4832,6 +5291,10 @@ var ts; return false; } ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 231 && node.parent.parent.kind === 212; @@ -5229,6 +5692,10 @@ var ts; return isInJavaScriptFile(file); } ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isSourceFileNotJavaScript(file) { + return !isInJavaScriptFile(file); + } + ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { return node && !!(node.flags & 65536); } @@ -5245,7 +5712,7 @@ var ts; (node.typeArguments[0].kind === 137 || node.typeArguments[0].kind === 134); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { if (callExpression.kind !== 185) { return false; } @@ -5257,7 +5724,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 || arg.kind === 13; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -5268,14 +5735,78 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 230) { - var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 190 || declaration.initializer.kind === 203); + function getJSInitializerSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return symbol; + } + var declaration = symbol.valueDeclaration; + var e = getDeclaredJavascriptInitializer(declaration) || getAssignedJavascriptInitializer(declaration); + return e && e.symbol ? e.symbol : symbol; + } + ts.getJSInitializerSymbol = getJSInitializerSymbol; + function getDeclaredJavascriptInitializer(node) { + if (node && ts.isVariableDeclaration(node) && node.initializer) { + return getJavascriptInitializer(node.initializer, false) || + ts.isIdentifier(node.name) && getDefaultedJavascriptInitializer(node.name, node.initializer, false); + } + } + ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + function getAssignedJavascriptInitializer(node) { + if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58) { + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + } + ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + function getJavascriptInitializer(initializer, isPrototypeAssignment) { + if (ts.isCallExpression(initializer)) { + var e = skipParentheses(initializer.expression); + return e.kind === 190 || e.kind === 191 ? initializer : undefined; + } + if (initializer.kind === 190 || initializer.kind === 203) { + return initializer; + } + if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } + } + ts.getJavascriptInitializer = getJavascriptInitializer; + function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } + } + function getOuterNameOfJsInitializer(node) { + if (ts.isBinaryExpression(node.parent)) { + var parent = (node.parent.operatorToken.kind === 54 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 58 && ts.isIdentifier(parent.left)) { + return parent.left; + } + } + else if (ts.isVariableDeclaration(node.parent)) { + return node.parent.name; + } + } + ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + function isSameEntityName(name, initializer) { + if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { + return name.escapedText === initializer.escapedText; + } + if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) { + return (initializer.expression.kind === 99 || + ts.isIdentifier(initializer.expression) && + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) && + isSameEntityName(name, initializer.name); + } + if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) { + return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression); } return false; } - ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; function getRightMostAssignedExpression(node) { while (isAssignmentExpression(node, true)) { node = node.right; @@ -5292,64 +5823,73 @@ var ts; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr)) { - return 0; - } - if (expr.operatorToken.kind !== 58 || expr.left.kind !== 183) { + if (!isInJavaScriptFile(expr) || + expr.operatorToken.kind !== 58 || + !ts.isPropertyAccessExpression(expr.left)) { return 0; } var lhs = expr.left; - if (lhs.expression.kind === 71) { - var lhsId = lhs.expression; - if (lhsId.escapedText === "exports") { - return 1; - } - else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { - return 2; - } - else { - return 5; - } - } - else if (lhs.expression.kind === 99) { + if (lhs.expression.kind === 99) { return 4; } - else if (lhs.expression.kind === 183) { - var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 71) { - var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { - return 1; - } - if (innerPropertyAccess.name.escapedText === "prototype") { - return 3; - } + else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + return 2; + } + else if (isEntityNameExpression(lhs.expression)) { + if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(expr.right)) { + return 6; } + else if (isPrototypeAccess(lhs.expression)) { + return 3; + } + var nextToLast = lhs; + while (ts.isPropertyAccessExpression(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + ts.Debug.assert(ts.isIdentifier(nextToLast.expression)); + var id = nextToLast.expression; + if (id.escapedText === "exports" || + id.escapedText === "module" && nextToLast.name.escapedText === "exports") { + return 1; + } + return 5; } return 0; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && expr.parent && expr.parent.kind === 214 && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function importFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 242: + case 248: + return node.parent; + case 252: + return node.parent.parent; + case 185: + return node.parent; + default: + return ts.Debug.fail(ts.Debug.showSyntaxKind(node)); + } + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; function getExternalModuleName(node) { - if (node.kind === 242) { - return node.moduleSpecifier; - } - if (node.kind === 241) { - var reference = node.moduleReference; - if (reference.kind === 252) { - return reference.expression; - } - } - if (node.kind === 248) { - return node.moduleSpecifier; - } - if (isModuleWithStringLiteralName(node)) { - return node.name; + switch (node.kind) { + case 242: + case 248: + return node.moduleSpecifier; + case 241: + return node.moduleReference.kind === 252 ? node.moduleReference.expression : undefined; + default: + return ts.Debug.assertNever(node); } } ts.getExternalModuleName = getExternalModuleName; @@ -5399,6 +5939,14 @@ var ts; node.expression.operatorToken.kind === 58 && node.expression.right; } + function getSourceOfDefaultedAssignment(node) { + return ts.isExpressionStatement(node) && + ts.isBinaryExpression(node.expression) && + getSpecialPropertyAssignmentKind(node.expression) !== 0 && + ts.isBinaryExpression(node.expression.right) && + node.expression.right.operatorToken.kind === 54 && + node.expression.right.right; + } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { case 212: @@ -5432,7 +5980,8 @@ var ts; (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node) { + if (parent && parent.parent && parent.parent.parent && + (getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || @@ -5469,7 +6018,8 @@ var ts; ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { var host = getJSDocHost(node); - var decl = getSourceOfAssignment(host) || + var decl = getSourceOfDefaultedAssignment(host) || + getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || @@ -5494,7 +6044,7 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined; + return node.dotDotDotToken !== undefined || node.type && node.type.kind === 281; } ts.isRestParameter = isRestParameter; function getAssignmentTargetKind(node) { @@ -5565,6 +6115,10 @@ var ts; return false; } ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -5579,6 +6133,13 @@ var ts; return walkUp(node, 189); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + function skipParentheses(node) { + while (node.kind === 189) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; function isDeleteTarget(node) { if (node.kind !== 183 && node.kind !== 184) { return false; @@ -5597,14 +6158,7 @@ var ts; } ts.isNodeDescendantOf = isNodeDescendantOf; function isDeclarationName(name) { - switch (name.kind) { - case 71: - case 9: - case 8: - return ts.isDeclaration(name.parent) && name.parent.name === name; - default: - return false; - } + return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; function isAnyDeclarationName(name) { @@ -5683,6 +6237,12 @@ var ts; return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85); return heritageClause ? heritageClause.types : undefined; @@ -5717,38 +6277,6 @@ var ts; return undefined; } ts.getAncestor = getAncestor; - function getFileReferenceFromReferencePath(comment, commentRange) { - var simpleReferenceRegEx = /^\/\/\/\s*= 48 && lookAhead <= 57) { + return "\\x00"; + } + return "\\0"; + } return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { @@ -6464,37 +6993,26 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (ts.hasType(node)) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocType(node); - } + function getEffectiveTypeAnnotationNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; - function getEffectiveReturnTypeNode(node, checkJSDoc) { - if (node.type) { - return node.type; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - return ts.getJSDocReturnType(node); - } + function getEffectiveReturnTypeNode(node) { + return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { - if (node.typeParameters) { - return node.typeParameters; - } - if (checkJSDoc || isInJavaScriptFile(node)) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; - } + function getEffectiveTypeParameterDeclarations(node) { + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; - function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { + function getJSDocTypeParameterDeclarations(node) { + var templateTag = ts.getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + function getEffectiveSetAccessorTypeAnnotationNode(node) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); + return parameter && getEffectiveTypeAnnotationNode(parameter); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -6579,7 +7097,7 @@ var ts; } return currentDetachedCommentInfo; function isPinnedCommentLocal(comment) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } ts.emitDetachedComments = emitDetachedComments; @@ -6754,10 +7272,17 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 || - node.kind === 183 && isEntityNameExpression(node.expression); + return node.kind === 71 || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 145 && node.parent.right === node) || (node.parent.kind === 183 && node.parent.name === node); @@ -6837,6 +7362,73 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + output += String.fromCharCode(value); + } + else { + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -7150,6 +7742,40 @@ var ts; return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; + function showModuleSpecifier(_a) { + var moduleSpecifier = _a.moduleSpecifier; + return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); + } + ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -7184,27 +7810,20 @@ var ts; } ts.textSpanContainsTextSpan = textSpanContainsTextSpan; function textSpanOverlapsWith(span, other) { - var overlapStart = Math.max(span.start, other.start); - var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); - return overlapStart < overlapEnd; + return textSpanOverlap(span, other) !== undefined; } ts.textSpanOverlapsWith = textSpanOverlapsWith; function textSpanOverlap(span1, span2) { - var overlapStart = Math.max(span1.start, span2.start); - var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (overlapStart < overlapEnd) { - return createTextSpanFromBounds(overlapStart, overlapEnd); - } - return undefined; + var overlap = textSpanIntersection(span1, span2); + return overlap && overlap.length === 0 ? undefined : overlap; } ts.textSpanOverlap = textSpanOverlap; function textSpanIntersectsWithTextSpan(span, other) { - return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); } ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; function textSpanIntersectsWith(span, start, length) { - var end = start + length; - return start <= textSpanEnd(span) && end >= span.start; + return decodedTextSpanIntersectsWith(span.start, span.length, start, length); } ts.textSpanIntersectsWith = textSpanIntersectsWith; function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { @@ -7218,12 +7837,9 @@ var ts; } ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; function textSpanIntersection(span1, span2) { - var intersectStart = Math.max(span1.start, span2.start); - var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (intersectStart <= intersectEnd) { - return createTextSpanFromBounds(intersectStart, intersectEnd); - } - return undefined; + var start = Math.max(span1.start, span2.start); + var end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + return start <= end ? createTextSpanFromBounds(start, end) : undefined; } ts.textSpanIntersection = textSpanIntersection; function createTextSpan(start, length) { @@ -7236,6 +7852,12 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; + function createTextRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos); + return { pos: pos, end: end }; + } + ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -7486,6 +8108,10 @@ var ts; return declaration.name || nameForNamelessJSDocTypedef(declaration); } ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; + function isNamedDeclaration(node) { + return !!node.name; + } + ts.isNamedDeclaration = isNamedDeclaration; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -7528,31 +8154,31 @@ var ts; 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; }); } - return undefined; + return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 287); + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285); + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 286); + return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 288); + return getFirstJSDocTag(node, ts.isJSDocReturnTag); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 290); + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getJSDocTypeTag(node) { - var tag = getFirstJSDocTag(node, 289); + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -7560,12 +8186,9 @@ var ts; } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 289); - if (!tag && node.kind === 148) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); } return tag && tag.typeExpression && tag.typeExpression.type; } @@ -7583,13 +8206,11 @@ var ts; return tags; } ts.getJSDocTags = getJSDocTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); } function getAllJSDocTagsOfKind(node, kind) { - var tags = getJSDocTags(node); - return ts.filter(tags, function (doc) { return doc.kind === kind; }); + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); @@ -8197,6 +8818,10 @@ var ts; return node.kind === 285; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 286; + } + ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { return node.kind === 287; } @@ -8295,6 +8920,14 @@ var ts; return false; } ts.isModifierKind = isModifierKind; + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 115; + } + ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { return isModifierKind(node.kind); } @@ -8877,6 +9510,43 @@ var ts; return !!node.type; } ts.hasType = hasType; + function couldHaveType(node) { + switch (node.kind) { + case 148: + case 150: + case 151: + case 152: + case 153: + case 154: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 162: + case 163: + case 172: + case 174: + case 176: + case 188: + case 190: + case 191: + case 206: + case 230: + case 232: + case 235: + case 274: + case 277: + case 278: + case 279: + case 280: + case 281: + return true; + } + return false; + } + ts.couldHaveType = couldHaveType; function hasInitializer(node) { return !!node.initializer; } @@ -8904,6 +9574,30 @@ var ts; return node.kind === 161 || node.kind === 205; } ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { return node.kind === 9 || node.kind === 13; } @@ -10513,6 +11207,13 @@ var ts; return token = 26; case 46: return token = 23; + case 96: + while (pos < end && text.charCodeAt(pos) !== 96) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 13; } if (isIdentifierStart(ch, 6)) { while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { @@ -10635,6 +11336,12 @@ var ts; } } } + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 && + text.charCodeAt(start + 2) === 42 && + text.charCodeAt(start + 3) !== 47; + } + ts.isJSDocLikeText = isJSDocLikeText; function forEachChild(node, cbNode, cbNodes) { if (!node || node.kind <= 144) { return; @@ -10990,6 +11697,7 @@ var ts; case 254: case 255: return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); case 261: return visitNodes(cbNode, cbNodes, node.properties); @@ -11203,7 +11911,8 @@ var ts; sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; nextToken(); - processReferenceComments(sourceFile); + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); sourceFile.statements = parseList(0, parseStatement); ts.Debug.assert(token() === 1); sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); @@ -11216,6 +11925,9 @@ var ts; fixupParentReferences(sourceFile); } return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic)); + } } function addJSDocComment(node) { var comments = ts.getJSDocCommentRanges(node, sourceFile.text); @@ -11339,9 +12051,7 @@ var ts; return inContext(16384); } function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); } function parseErrorAtPosition(start, length, message, arg0) { var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -11350,9 +12060,14 @@ var ts; } parseErrorBeforeNextFinishedNode = true; } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); + parseErrorAtPosition(scanner.getTextPos(), length, message); } function getNodePos() { return scanner.getStartPos(); @@ -11582,24 +12297,25 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76) { - return nextToken() === 83; + switch (token()) { + case 76: + return nextToken() === 83; + case 84: + nextToken(); + if (token() === 79) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); + case 79: + return nextTokenCanFollowDefaultKeyword(); + case 115: + case 125: + case 136: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === 84) { - nextToken(); - if (token() === 79) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); - } - if (token() === 79) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === 115) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); @@ -12156,9 +12872,20 @@ var ts; nextToken(); return finishNode(node); } - function parseJSDocAllType() { + function parseJSDocAllType(postFixEquals) { var result = createNode(275); + if (postFixEquals) { + return createJSDocPostfixType(279, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(278); nextToken(); + result.type = parseNonArrayType(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { @@ -12196,14 +12923,21 @@ var ts; parameter.name = parseIdentifierName(); parseExpected(56); } - parameter.type = parseType(); + parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocNodeWithType(kind) { - var result = createNode(kind); - nextToken(); - result.type = parseNonArrayType(); - return finishNode(result); + function parseJSDocType() { + var dotdotdot = parseOptionalToken(24); + var type = parseType(); + if (dotdotdot) { + var variadic = createNode(281, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 58) { + return createJSDocPostfixType(279, type); + } + return type; } function parseTypeQuery() { var node = createNode(164); @@ -12531,13 +13265,15 @@ var ts; case 135: return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 39: - return parseJSDocAllType(); + return parseJSDocAllType(false); + case 61: + return parseJSDocAllType(true); case 55: return parseJSDocUnknownOrNullableType(); case 89: return parseJSDocFunctionType(); case 51: - return parseJSDocNodeWithType(278); + return parseJSDocNonNullableType(); case 13: case 9: case 8: @@ -12617,12 +13353,6 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 58: - if (!(contextFlags & 1048576)) { - return type; - } - type = createJSDocPostfixType(279, type); - break; case 51: type = createJSDocPostfixType(278, type); break; @@ -12683,12 +13413,6 @@ var ts; return parseTypeOperator(operator); case 126: return parseInferType(); - case 24: { - var result = createNode(281); - nextToken(); - result.type = parsePostfixTypeOrHigher(); - return finishNode(result); - } } return parsePostfixTypeOrHigher(); } @@ -13126,7 +13850,7 @@ var ts; function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); var consumeCurrentOperator = token() === 40 ? newPrecedence >= precedence : newPrecedence > precedence; @@ -13155,48 +13879,7 @@ var ts; if (inDisallowInContext() && token() === 92) { return false; } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54: - return 1; - case 53: - return 2; - case 49: - return 3; - case 50: - return 4; - case 48: - return 5; - case 32: - case 33: - case 34: - case 35: - return 6; - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: - return 7; - case 45: - case 46: - case 47: - return 8; - case 37: - case 38: - return 9; - case 39: - case 41: - case 42: - return 10; - case 40: - return 11; - } - return -1; + return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { var node = createNode(198, left.pos); @@ -13255,18 +13938,19 @@ var ts; if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); return token() === 40 ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; if (simpleUnaryExpression.kind === 188) { - 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); + parseErrorAt(pos, end, 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 { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; @@ -13383,7 +14067,7 @@ var ts; 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)); + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } @@ -13419,8 +14103,19 @@ var ts; currentToken = scanner.scanJsxToken(); return finishNode(node); } - function parseJsxChild() { - switch (token()) { + function parseJsxChild(openingTag, token) { + switch (token) { + case 1: + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 28: + case 7: + return undefined; case 10: case 11: return parseJsxText(); @@ -13428,8 +14123,9 @@ var ts; return parseJsxExpression(false); case 27: return parseJsxElementOrSelfClosingElementOrFragment(false); + default: + return ts.Debug.assertNever(token); } - ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTag) { var list = []; @@ -13437,27 +14133,10 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28) { + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; - } - else if (token() === 1) { - 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) { - break; - } - var child = parseJsxChild(); - if (child) { - list.push(child); - } + list.push(child); } parsingContext = saveParsingContext; return createNodeArray(list, listPos); @@ -13471,11 +14150,12 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(27); if (token() === 29) { - parseExpected(29); var node_1 = createNode(258, fullStart); + scanJsxText(); return finishNode(node_1); } var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; if (token() === 29) { @@ -13494,6 +14174,7 @@ var ts; node = createNode(254, fullStart); } node.tagName = tagName; + node.typeArguments = typeArguments; node.attributes = attributes; return finishNode(node); } @@ -13511,7 +14192,9 @@ var ts; } function parseJsxExpression(inExpressionContext) { var node = createNode(263); - parseExpected(17); + if (!parseExpected(17)) { + return undefined; + } if (token() !== 18) { node.dotDotDotToken = parseOptionalToken(24); node.expression = parseAssignmentExpressionOrHigher(); @@ -13569,8 +14252,7 @@ var ts; var node = createNode(259); 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); + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { parseExpected(29); @@ -13935,7 +14617,7 @@ var ts; parseExpected(88); var awaitToken = parseOptionalToken(121); parseExpected(19); - var initializer = undefined; + var initializer; if (token() !== 25) { if (token() === 104 || token() === 110 || token() === 76) { initializer = parseVariableDeclarationList(true); @@ -14511,18 +15193,6 @@ var ts; node.body = parseFunctionBlockOrSemicolon(0); return finishNode(node); } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114: - case 112: - case 113: - case 115: - case 132: - return true; - default: - return false; - } - } function isClassMemberStart() { var idToken; if (token() === 57) { @@ -14530,7 +15200,7 @@ var ts; } while (ts.isModifierKind(token())) { idToken = token(); - if (isClassMemberModifier(idToken)) { + if (ts.isClassMemberModifier(idToken)) { return true; } nextToken(); @@ -14917,7 +15587,7 @@ var ts; node.name = identifierName; } if (kind === 246 && checkIdentifierIsKeyword) { - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } @@ -14949,84 +15619,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); - var referencedFiles = []; - var typeReferenceDirectives = []; - var amdDependencies = []; - var amdModuleName; - var checkJsDirective = undefined; - while (true) { - var kind = triviaScanner.scan(); - if (kind !== 2) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*= pos_2); pos_2 = child.end; - }); + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); ts.Debug.assert(pos_2 <= node.end); } } @@ -15805,6 +16401,12 @@ var ts; child._children = undefined; adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } @@ -15848,15 +16450,15 @@ var ts; var lastNodeEntirelyBeforePosition; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } } return bestResult; - function getLastChild(node) { + function getLastDescendant(node) { while (true) { - var lastChild = getLastChildWorker(node); + var lastChild = ts.getLastChild(node); if (lastChild) { node = lastChild; } @@ -15865,15 +16467,6 @@ var ts; } } } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } function visit(child) { if (ts.nodeIsMissing(child)) { return; @@ -15974,6 +16567,200 @@ var ts; function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); } + function processCommentPragmas(context, sourceText) { + var triviaScanner = ts.createScanner(context.languageVersion, false, 0, sourceText); + var pragmas = []; + while (true) { + var kind = triviaScanner.scan(); + if (!ts.isTrivia(kind)) { + break; + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = ts.createMap(); + for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { + var pragma = pragmas_1[_i]; + if (context.pragmas.has(pragma.name)) { + var currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } + else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } + } + ts.processCommentPragmas = processCommentPragmas; + function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = undefined; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach(function (entryOrList, key) { + switch (key) { + case "reference": { + var referencedFiles_1 = context.referencedFiles; + var typeReferenceDirectives_1 = context.typeReferenceDirectives; + ts.forEach(ts.toArray(entryOrList), function (arg) { + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (arg.arguments.types) { + typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + } + else if (arg.arguments.path) { + referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + } + else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { + var _b = _a.arguments, name = _b.name, path = _b.path; + return ({ name: name, path: path }); + }); + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) { + var entry = entryOrList_1[_i]; + if (context.moduleName) { + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } + else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + ts.forEach(ts.toArray(entryOrList), function (entry) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": return; + default: ts.Debug.fail("Unhandled pragma kind"); + } + }); + } + ts.processPragmasIntoFields = processPragmasIntoFields; + var namedArgRegExCache = ts.createMap(); + function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im"); + namedArgRegExCache.set(name, result); + return result; + } + var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; + var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + function extractPragmas(pragmas, range, text) { + var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + var name = tripleSlash[1].toLowerCase(); + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & 1)) { + return; + } + if (pragma.args) { + var argument = {}; + for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) { + var arg = _a[_i]; + var matcher = getNamedArgRegEx(arg.name); + var matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; + } + else if (matchResult) { + if (arg.captureSpan) { + var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length; + argument[arg.name] = { + value: matchResult[3], + pos: startPos, + end: startPos + matchResult[3].length + }; + } + else { + argument[arg.name] = matchResult[3]; + } + } + } + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + } + else { + pragmas.push({ name: name, args: { arguments: {}, range: range } }); + } + return; + } + var singleLine = singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2, singleLine); + } + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; + var multiLineMatch; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4, multiLineMatch); + } + } + function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) + return; + var name = match[1].toLowerCase(); + var pragma = ts.commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + var args = match[2]; + var argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") + return; + pragmas.push({ name: name, args: { arguments: argument, range: range } }); + return; + } + function getNamedPragmaArguments(pragma, text) { + if (!text) + return {}; + if (!pragma.args) + return {}; + var args = text.split(/\s+/); + var argMap = {}; + for (var i = 0; i < pragma.args.length; i++) { + var argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -16031,6 +16818,13 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, { name: "watch", shortName: "w", @@ -16108,9 +16902,10 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "es2018.promise": "lib.es2018.promise.d.ts", + "es2018.regexp": "lib.es2018.regexp.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, @@ -16150,6 +16945,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, { name: "emitDeclarationOnly", type: "boolean", @@ -17568,7 +18370,7 @@ var ts; function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); - var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; @@ -17706,12 +18508,6 @@ var ts; wildcardFiles.delete(lowerPriorityPath); } } - function caseSensitiveKeyMapper(key) { - return key; - } - function caseInsensitiveKeyMapper(key) { - return key.toLowerCase(); - } function convertCompilerOptionsForTelemetry(opts) { var out = {}; for (var key in opts) { @@ -17956,8 +18752,10 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createMap(); - var moduleNameToDirectoryMap = ts.createMap(); + return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName); + } + ts.createModuleResolutionCache = createModuleResolutionCache; + function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); @@ -18023,7 +18821,7 @@ var ts; } } } - ts.createModuleResolutionCache = createModuleResolutionCache; + ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -18034,7 +18832,7 @@ var ts; var result = perFolderCache && perFolderCache.get(moduleName); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } } else { @@ -18156,7 +18954,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); } - var matchedPattern = undefined; + var matchedPattern; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); @@ -18516,7 +19314,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -18568,6 +19366,7 @@ var ts; } return packageName; } + ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { @@ -18582,12 +19381,13 @@ var ts; typesPackageName; } ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { var result = cache && cache.get(containingDirectory); if (result) { if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } + failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } @@ -18606,7 +19406,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -18901,7 +19701,7 @@ var ts; case 6: return "Package name '" + typing + "' contains non URI safe characters"; case 0: - throw ts.Debug.fail(); + return ts.Debug.fail(); default: ts.Debug.assertNever(result); } @@ -18999,10 +19799,7 @@ var ts; } return; } - for (var _i = 0, watchers_1 = watchers; _i < watchers_1.length; _i++) { - var w = watchers_1[_i]; - w.close(); - } + ts.clearMap(watchers, ts.closeFileWatcher); this.projectWatchers.delete(projectName); if (this.log.isEnabled()) { this.log.writeLine("Closing file watchers for project '" + projectName + "' - done."); @@ -19233,25 +20030,38 @@ var ts; TypingsInstaller.prototype.watchFiles = function (projectName, files) { var _this = this; if (!files.length) { + this.closeWatchers(projectName); return; } - this.closeWatchers(projectName); - var isInvoked = false; - var watchers = []; - 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 + "'"); - } - if (!isInvoked) { - _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); - isInvoked = true; - } - }, 2000); - watchers.push(w); + var watchers = this.projectWatchers.get(projectName); + if (!watchers) { + watchers = ts.createMap(); + this.projectWatchers.set(projectName, watchers); } - this.projectWatchers.set(projectName, watchers); + var isInvoked = false; + var isLoggingEnabled = this.log.isEnabled(); + ts.mutateMap(watchers, ts.arrayToSet(files), { + createNewValue: function (file) { + if (isLoggingEnabled) { + _this.log.writeLine("FileWatcher:: Added:: WatchInfo: " + file); + } + var watcher = _this.installTypingHost.watchFile(file, function (f, eventKind) { + if (isLoggingEnabled) { + _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + file + ":: handler is already invoked '" + isInvoked + "'"); + } + if (!isInvoked) { + _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); + isInvoked = true; + } + }, 2000); + return isLoggingEnabled ? { + close: function () { + _this.log.writeLine("FileWatcher:: Closed:: WatchInfo: " + file); + } + } : watcher; + }, + onDeleteValue: ts.closeFileWatcher + }); }; TypingsInstaller.prototype.createSetTypings = function (request, typings) { return { diff --git a/lib/zh-CN/diagnosticMessages.generated.json b/lib/zh-CN/diagnosticMessages.generated.json index ac797aec838..8ac36006c92 100644 --- a/lib/zh-CN/diagnosticMessages.generated.json +++ b/lib/zh-CN/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "两个取值函数必须都是抽象的或都是非抽象的。", "Add_0_to_existing_import_declaration_from_1_90015": "将“{0}”从“{1}”添加到现有导入声明", "Add_async_modifier_to_containing_function_90029": "将异步修饰符添加到包含函数", + "Add_definite_assignment_assertion_to_property_0_95020": "向属性“{0}”添加明确的赋值断言", "Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名", + "Add_initializer_to_property_0_95019": "向属性“{0}”添加初始值设定项", "Add_missing_super_call_90001": "添加缺失的 \"super()\" 调用", "Add_this_to_unresolved_variable_90008": "向未解析的变量添加 \"this.\"", + "Add_undefined_type_to_property_0_95018": "向属性“{0}”添加“未定义”类型", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "添加 tsconfig.json 文件有助于组织包含 TypeScript 和 JavaScript 文件的项目。有关详细信息,请访问 https://aka.ms/tsconfig。", "Additional_Checks_6176": "其他检查", "Advanced_Options_6178": "高级选项", "All_declarations_of_0_must_have_identical_modifiers_2687": "“{0}”的所有声明必须具有相同的修饰符。", "All_declarations_of_0_must_have_identical_type_parameters_2428": "“{0}”的所有声明都必须具有相同的类型参数。", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有声明必须是连续的。", + "All_imports_in_import_declaration_are_unused_6192": "未使用导入声明中的所有导入。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允许从不带默认输出的模块中默认输入。这不会影响代码发出,只是类型检查。", "Allow_javascript_files_to_be_compiled_6102": "允许编译 JavaScript 文件。", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "提供 \"--isolatedModules\" 标志的情况下不允许使用环境常数枚举。", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "枚举声明只能与命名空间或其他枚举声明合并。", "Enum_declarations_must_all_be_const_or_non_const_2473": "枚举声明必须全为常数或非常数。", "Enum_member_expected_1132": "应为枚举成员。", "Enum_member_must_have_initializer_1061": "枚举成员必须具有初始化表达式。", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "文件是 CommonJS 模块;它可能会转换为 ES6 模块。", "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}”后的父目录(\"..\")。", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "导入可能会转换为默认导入。", "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": "模块扩大中不允许导入。请考虑将它们移动到封闭的外部模块。", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc \"@param\" 标记的名称为“{0}”,但该名称没有参数。如果它为数组类型,将匹配 \"arguments\"。", "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 类型只能在文档注释内部使用。", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 类型可能会移到 TypeScript 类型。", "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}”没有相应的结束标记。", @@ -476,6 +485,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 元素不能具有多个名称相同的特性。", "JSX_expressions_must_have_one_parent_element_2657": "JSX 表达式必须具有一个父元素。", "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 片段没有相应的结束标记。", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂杂注时,不支持 JSX 片段", "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "使用 --jsxFactory 时不支持 JSX 片段", "JSX_spread_child_must_be_an_array_type_2609": "JSX 扩展子属性必须为数组类型。", "Jump_target_cannot_cross_function_boundary_1107": "跳转目标不能跨越函数边界。", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "模块“{0}”没有导出的成员“{1}”。你是否指的是“{2}”?", "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 *\" 一起使用。", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。", "Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。", "Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明", + "Remove_import_from_0_90005": "从“{0}”删除导入", "Replace_import_with_0_95015": "用“{0}”替换导入。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "报告 switch 语句中遇到 fallthrough 情况的错误。", @@ -657,7 +669,7 @@ "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}”的解析。", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "在位置“{1}”的缓存中找到模块“{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}”。", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "此构造函数可能会转换为类声明。", "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": "不允许使用尾随逗号。", @@ -887,6 +900,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "变量声明列表不能为空。", "Version_0_6029": "版本 {0}", "Watch_input_files_6005": "监视输入文件。", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否在监视模式下保留过时的控制台输出,而不是清除屏幕。", "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}()\" 吗?", diff --git a/lib/zh-TW/diagnosticMessages.generated.json b/lib/zh-TW/diagnosticMessages.generated.json index c44acb2bd94..b3c6db2f4dc 100644 --- a/lib/zh-TW/diagnosticMessages.generated.json +++ b/lib/zh-TW/diagnosticMessages.generated.json @@ -95,15 +95,19 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "存取子必須兩者均為抽象或非抽象。", "Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告", "Add_async_modifier_to_containing_function_90029": "將 async 修飾詞新增至包含的函式", + "Add_definite_assignment_assertion_to_property_0_95020": "將明確指派判斷提示新增至屬性 '{0}'", "Add_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章", + "Add_initializer_to_property_0_95019": "將初始設定式新增至屬性 '{0}'", "Add_missing_super_call_90001": "新增遺漏的 'super()' 呼叫", "Add_this_to_unresolved_variable_90008": "將 'this' 新增至未解析的變數", + "Add_undefined_type_to_property_0_95018": "將 'undefined' 類型新增至屬性 '{0}'", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "新增 tsconfig.json 檔案有助於組織同時包含 TypeScript 及 JavaScript 檔案的專案。若要深入了解,請前往 https://aka.ms/tsconfig。", "Additional_Checks_6176": "其他檢查", "Advanced_Options_6178": "進階選項", "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。", + "All_imports_in_import_declaration_are_unused_6192": "匯入宣告中的所有匯入皆未使用。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允許從沒有預設匯出的模組進行預設匯入。這不會影響程式碼發出,僅為類型檢查。", "Allow_javascript_files_to_be_compiled_6102": "允許編譯 JavaScript 檔案。", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "提供 '--isolatedModules' 旗標時,不可使用環境常數列舉。", @@ -324,6 +328,7 @@ "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_can_only_merge_with_namespace_or_other_enum_declarations_2567": "列舉宣告只能與命名空間或其他列舉宣告合併。", "Enum_declarations_must_all_be_const_or_non_const_2473": "列舉宣告必須都是 const 或非 const。", "Enum_member_expected_1132": "必須是列舉成員。", "Enum_member_must_have_initializer_1061": "列舉成員必須有初始設定式。", @@ -378,6 +383,7 @@ "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_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "檔案為 CommonJS 模組; 其可轉換為 ES6 模組。", "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}'。", @@ -424,6 +430,7 @@ "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_may_be_converted_to_a_default_import_80003": "匯入可轉換成預設匯入。", "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": "模組增強指定中不允許匯入。請考慮將其移至封入外部模組。", @@ -462,8 +469,10 @@ "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' 標籤的名稱為 '{0}',但沒有任何參數使用該名稱。如有陣列類型,則會與 'arguments' 相符。", "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 類型只能在文件註解中使用。", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 類型可移為 TypeScript 類型。", "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}' 沒有對應的結尾標記。", @@ -476,6 +485,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 項目不得有多個同名的屬性。", "JSX_expressions_must_have_one_parent_element_2657": "JSX 運算式必須具有一個父元素。", "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 片段沒有對應的結尾標記。", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用內嵌 JSX 處理站 pragma 時,不支援 JSX 片段", "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "使用 --jsxFactory 時,不支援 JSX 片段", "JSX_spread_child_must_be_an_array_type_2609": "JSX 擴張子系必須為陣列類型。", "Jump_target_cannot_cross_function_boundary_1107": "跳躍目標不得跨越函式界限。", @@ -507,6 +517,7 @@ "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_has_no_exported_member_1_Did_you_mean_2_2724": "模組 '{0}' 沒有任何匯出的成員 '{1}'。您是否指的是 '{2}'?", "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 *' 的方式使用。", @@ -650,6 +661,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。", "Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。", "Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告", + "Remove_import_from_0_90005": "從 '{0}' 移除匯入", "Replace_import_with_0_95015": "以 '{0}' 取代匯入。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "回報 switch 陳述式內 fallthrough 案例的錯誤。", @@ -657,7 +669,7 @@ "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}' 的解析。", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "從位置 '{1}' 的快取中找到模組 '{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}'。", @@ -791,6 +803,7 @@ "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_constructor_function_may_be_converted_to_a_class_declaration_80002": "此建構函式可轉換為類別宣告。", "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": "尾端不得為逗號。", @@ -887,6 +900,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "變數宣告清單不得為空白。", "Version_0_6029": "版本 {0}", "Watch_input_files_6005": "監看輸入檔案。", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否要將已過期的主控台輸出,維持在監看模式下,而非清除螢幕。", "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}()' 嗎?", From 3280865049a0036f0be580056f815dac1bb9e031 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 28 Mar 2018 18:37:07 -0700 Subject: [PATCH 45/75] Do not watch child directories of the sym link folders Fixes #22668 --- src/compiler/sys.ts | 31 +++++++++------- src/harness/unittests/tscWatchMode.ts | 44 +++++++++++++++++++++++ src/harness/virtualFileSystemWithWatch.ts | 11 +++--- 3 files changed, 70 insertions(+), 16 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index f459515301c..b2818918af8 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -337,6 +337,7 @@ namespace ts { getAccessileSortedChildDirectories(path: string): ReadonlyArray; directoryExists(dir: string): boolean; filePathComparer: Comparer; + realpath(s: string): string; } /** @@ -392,9 +393,12 @@ namespace ts { function watchChildDirectories(parentDir: string, existingChildWatches: ChildWatches, callback: DirectoryWatcherCallback): ChildWatches { let newChildWatches: DirectoryWatcher[] | undefined; enumerateInsertsAndDeletes( - host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : emptyArray, + host.directoryExists(parentDir) ? mapDefined(host.getAccessileSortedChildDirectories(parentDir), child => { + const childFullName = getNormalizedAbsolutePath(child, parentDir); + return host.filePathComparer(childFullName, host.realpath(childFullName)) === Comparison.EqualTo ? childFullName : undefined; + }) : emptyArray, existingChildWatches, - (child, childWatcher) => host.filePathComparer(getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName), + (child, childWatcher) => host.filePathComparer(child, childWatcher.dirName), createAndAddChildDirectoryWatcher, closeFileWatcher, addChildDirectoryWatcher @@ -406,7 +410,7 @@ namespace ts { * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName: string) { - const result = createDirectoryWatcher(getNormalizedAbsolutePath(childName, parentDir), callback); + const result = createDirectoryWatcher(childName, callback); addChildDirectoryWatcher(result); } @@ -601,14 +605,7 @@ namespace ts { exit(exitCode?: number): void { process.exit(exitCode); }, - realpath(path: string): string { - try { - return _fs.realpathSync(path); - } - catch { - return path; - } - }, + realpath, debugMode: some(process.execArgv, arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)), tryEnableSourceMapsForHost() { try { @@ -700,7 +697,8 @@ namespace ts { filePathComparer: useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, directoryExists, getAccessileSortedChildDirectories: path => getAccessibleFileSystemEntries(path).directories, - watchDirectory + watchDirectory, + realpath }); return (directoryName, callback, recursive) => { @@ -1043,6 +1041,15 @@ namespace ts { return filter(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory)); } + function realpath(path: string): string { + try { + return _fs.realpathSync(path); + } + catch { + return path; + } + } + function getModifiedTime(path: string) { try { return _fs.statSync(path).mtime; diff --git a/src/harness/unittests/tscWatchMode.ts b/src/harness/unittests/tscWatchMode.ts index e056153518a..999201029de 100644 --- a/src/harness/unittests/tscWatchMode.ts +++ b/src/harness/unittests/tscWatchMode.ts @@ -2358,6 +2358,50 @@ declare module "fs" { it("uses non recursive dynamic polling when renaming file in subfolder", () => { verifyRenamingFileInSubFolder(TestFSWithWatch.Tsc_WatchDirectory.DynamicPolling); }); + + it("when there are symlinks to folders in recursive folders", () => { + const cwd = "/home/user/projects/myproject"; + const file1: FileOrFolder = { + path: `${cwd}/src/file.ts`, + content: `import * as a from "a"` + }; + const tsconfig: FileOrFolder = { + path: `${cwd}/tsconfig.json`, + content: `{ "compilerOptions": { "extendedDiagnostics": true, "traceResolution": true }}` + }; + const realA: FileOrFolder = { + path: `${cwd}/node_modules/reala/index.d.ts`, + content: `export {}` + }; + const realB: FileOrFolder = { + path: `${cwd}/node_modules/realb/index.d.ts`, + content: `export {}` + }; + const symLinkA: FileOrFolder = { + path: `${cwd}/node_modules/a`, + symLink: `${cwd}/node_modules/reala` + }; + const symLinkB: FileOrFolder = { + path: `${cwd}/node_modules/b`, + symLink: `${cwd}/node_modules/realb` + }; + const symLinkBInA: FileOrFolder = { + path: `${cwd}/node_modules/reala/node_modules/b`, + symLink: `${cwd}/node_modules/b` + }; + const symLinkAInB: FileOrFolder = { + path: `${cwd}/node_modules/realb/node_modules/a`, + symLink: `${cwd}/node_modules/a` + }; + const files = [file1, tsconfig, realA, realB, symLinkA, symLinkB, symLinkBInA, symLinkAInB]; + const environmentVariables = createMap(); + environmentVariables.set("TSC_WATCHDIRECTORY", TestFSWithWatch.Tsc_WatchDirectory.NonRecursiveWatchDirectory); + const host = createWatchedSystem(files, { environmentVariables, currentDirectory: cwd }); + createWatchOfConfigFile("tsconfig.json", host); + checkWatchedDirectories(host, emptyArray, /*recursive*/ true); + checkWatchedDirectories(host, [cwd, `${cwd}/node_modules`, `${cwd}/node_modules/@types`, `${cwd}/node_modules/reala`, `${cwd}/node_modules/realb`, + `${cwd}/node_modules/reala/node_modules`, `${cwd}/node_modules/realb/node_modules`, `${cwd}/src`], /*recursive*/ false); + }); }); }); } diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index cd5f5cf1b18..21f16ab579d 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -314,7 +314,8 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory + watchDirectory, + realpath: s => this.realpath(s) }); } else if (tscWatchDirectory === Tsc_WatchDirectory.NonRecursiveWatchDirectory) { @@ -323,7 +324,8 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory + watchDirectory, + realpath: s => this.realpath(s) }); } else if (tscWatchDirectory === Tsc_WatchDirectory.DynamicPolling) { @@ -333,7 +335,8 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory + watchDirectory, + realpath: s => this.realpath(s) }); } } @@ -649,7 +652,7 @@ interface Array {}` const realpath = this.realpath(path); if (path !== realpath) { - return this.getRealFsEntry(isFsEntry, realpath as Path); + return this.getRealFsEntry(isFsEntry, this.toPath(realpath)); } return undefined; From e40f2943b1b6f96710db82555b29c760f2f793b0 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 28 Mar 2018 21:10:29 -0700 Subject: [PATCH 46/75] Revert "Do not watch child directories of the sym link folders" This reverts commit 3280865049a0036f0be580056f815dac1bb9e031. --- src/compiler/sys.ts | 31 +++++++--------- src/harness/unittests/tscWatchMode.ts | 44 ----------------------- src/harness/virtualFileSystemWithWatch.ts | 11 +++--- 3 files changed, 16 insertions(+), 70 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index b2818918af8..f459515301c 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -337,7 +337,6 @@ namespace ts { getAccessileSortedChildDirectories(path: string): ReadonlyArray; directoryExists(dir: string): boolean; filePathComparer: Comparer; - realpath(s: string): string; } /** @@ -393,12 +392,9 @@ namespace ts { function watchChildDirectories(parentDir: string, existingChildWatches: ChildWatches, callback: DirectoryWatcherCallback): ChildWatches { let newChildWatches: DirectoryWatcher[] | undefined; enumerateInsertsAndDeletes( - host.directoryExists(parentDir) ? mapDefined(host.getAccessileSortedChildDirectories(parentDir), child => { - const childFullName = getNormalizedAbsolutePath(child, parentDir); - return host.filePathComparer(childFullName, host.realpath(childFullName)) === Comparison.EqualTo ? childFullName : undefined; - }) : emptyArray, + host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : emptyArray, existingChildWatches, - (child, childWatcher) => host.filePathComparer(child, childWatcher.dirName), + (child, childWatcher) => host.filePathComparer(getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName), createAndAddChildDirectoryWatcher, closeFileWatcher, addChildDirectoryWatcher @@ -410,7 +406,7 @@ namespace ts { * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName: string) { - const result = createDirectoryWatcher(childName, callback); + const result = createDirectoryWatcher(getNormalizedAbsolutePath(childName, parentDir), callback); addChildDirectoryWatcher(result); } @@ -605,7 +601,14 @@ namespace ts { exit(exitCode?: number): void { process.exit(exitCode); }, - realpath, + realpath(path: string): string { + try { + return _fs.realpathSync(path); + } + catch { + return path; + } + }, debugMode: some(process.execArgv, arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)), tryEnableSourceMapsForHost() { try { @@ -697,8 +700,7 @@ namespace ts { filePathComparer: useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, directoryExists, getAccessileSortedChildDirectories: path => getAccessibleFileSystemEntries(path).directories, - watchDirectory, - realpath + watchDirectory }); return (directoryName, callback, recursive) => { @@ -1041,15 +1043,6 @@ namespace ts { return filter(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory)); } - function realpath(path: string): string { - try { - return _fs.realpathSync(path); - } - catch { - return path; - } - } - function getModifiedTime(path: string) { try { return _fs.statSync(path).mtime; diff --git a/src/harness/unittests/tscWatchMode.ts b/src/harness/unittests/tscWatchMode.ts index 999201029de..e056153518a 100644 --- a/src/harness/unittests/tscWatchMode.ts +++ b/src/harness/unittests/tscWatchMode.ts @@ -2358,50 +2358,6 @@ declare module "fs" { it("uses non recursive dynamic polling when renaming file in subfolder", () => { verifyRenamingFileInSubFolder(TestFSWithWatch.Tsc_WatchDirectory.DynamicPolling); }); - - it("when there are symlinks to folders in recursive folders", () => { - const cwd = "/home/user/projects/myproject"; - const file1: FileOrFolder = { - path: `${cwd}/src/file.ts`, - content: `import * as a from "a"` - }; - const tsconfig: FileOrFolder = { - path: `${cwd}/tsconfig.json`, - content: `{ "compilerOptions": { "extendedDiagnostics": true, "traceResolution": true }}` - }; - const realA: FileOrFolder = { - path: `${cwd}/node_modules/reala/index.d.ts`, - content: `export {}` - }; - const realB: FileOrFolder = { - path: `${cwd}/node_modules/realb/index.d.ts`, - content: `export {}` - }; - const symLinkA: FileOrFolder = { - path: `${cwd}/node_modules/a`, - symLink: `${cwd}/node_modules/reala` - }; - const symLinkB: FileOrFolder = { - path: `${cwd}/node_modules/b`, - symLink: `${cwd}/node_modules/realb` - }; - const symLinkBInA: FileOrFolder = { - path: `${cwd}/node_modules/reala/node_modules/b`, - symLink: `${cwd}/node_modules/b` - }; - const symLinkAInB: FileOrFolder = { - path: `${cwd}/node_modules/realb/node_modules/a`, - symLink: `${cwd}/node_modules/a` - }; - const files = [file1, tsconfig, realA, realB, symLinkA, symLinkB, symLinkBInA, symLinkAInB]; - const environmentVariables = createMap(); - environmentVariables.set("TSC_WATCHDIRECTORY", TestFSWithWatch.Tsc_WatchDirectory.NonRecursiveWatchDirectory); - const host = createWatchedSystem(files, { environmentVariables, currentDirectory: cwd }); - createWatchOfConfigFile("tsconfig.json", host); - checkWatchedDirectories(host, emptyArray, /*recursive*/ true); - checkWatchedDirectories(host, [cwd, `${cwd}/node_modules`, `${cwd}/node_modules/@types`, `${cwd}/node_modules/reala`, `${cwd}/node_modules/realb`, - `${cwd}/node_modules/reala/node_modules`, `${cwd}/node_modules/realb/node_modules`, `${cwd}/src`], /*recursive*/ false); - }); }); }); } diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 21f16ab579d..cd5f5cf1b18 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -314,8 +314,7 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory, - realpath: s => this.realpath(s) + watchDirectory }); } else if (tscWatchDirectory === Tsc_WatchDirectory.NonRecursiveWatchDirectory) { @@ -324,8 +323,7 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory, - realpath: s => this.realpath(s) + watchDirectory }); } else if (tscWatchDirectory === Tsc_WatchDirectory.DynamicPolling) { @@ -335,8 +333,7 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory, - realpath: s => this.realpath(s) + watchDirectory }); } } @@ -652,7 +649,7 @@ interface Array {}` const realpath = this.realpath(path); if (path !== realpath) { - return this.getRealFsEntry(isFsEntry, this.toPath(realpath)); + return this.getRealFsEntry(isFsEntry, realpath as Path); } return undefined; From f885cd971eb31b67d95dfb2eca91888353263afc Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 28 Mar 2018 18:37:07 -0700 Subject: [PATCH 47/75] Do not watch child directories of the sym link folders Fixes #22668 --- src/compiler/sys.ts | 31 +++++++++------- src/harness/unittests/tscWatchMode.ts | 44 +++++++++++++++++++++++ src/harness/virtualFileSystemWithWatch.ts | 11 +++--- 3 files changed, 70 insertions(+), 16 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index f459515301c..b2818918af8 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -337,6 +337,7 @@ namespace ts { getAccessileSortedChildDirectories(path: string): ReadonlyArray; directoryExists(dir: string): boolean; filePathComparer: Comparer; + realpath(s: string): string; } /** @@ -392,9 +393,12 @@ namespace ts { function watchChildDirectories(parentDir: string, existingChildWatches: ChildWatches, callback: DirectoryWatcherCallback): ChildWatches { let newChildWatches: DirectoryWatcher[] | undefined; enumerateInsertsAndDeletes( - host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : emptyArray, + host.directoryExists(parentDir) ? mapDefined(host.getAccessileSortedChildDirectories(parentDir), child => { + const childFullName = getNormalizedAbsolutePath(child, parentDir); + return host.filePathComparer(childFullName, host.realpath(childFullName)) === Comparison.EqualTo ? childFullName : undefined; + }) : emptyArray, existingChildWatches, - (child, childWatcher) => host.filePathComparer(getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName), + (child, childWatcher) => host.filePathComparer(child, childWatcher.dirName), createAndAddChildDirectoryWatcher, closeFileWatcher, addChildDirectoryWatcher @@ -406,7 +410,7 @@ namespace ts { * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName: string) { - const result = createDirectoryWatcher(getNormalizedAbsolutePath(childName, parentDir), callback); + const result = createDirectoryWatcher(childName, callback); addChildDirectoryWatcher(result); } @@ -601,14 +605,7 @@ namespace ts { exit(exitCode?: number): void { process.exit(exitCode); }, - realpath(path: string): string { - try { - return _fs.realpathSync(path); - } - catch { - return path; - } - }, + realpath, debugMode: some(process.execArgv, arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)), tryEnableSourceMapsForHost() { try { @@ -700,7 +697,8 @@ namespace ts { filePathComparer: useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, directoryExists, getAccessileSortedChildDirectories: path => getAccessibleFileSystemEntries(path).directories, - watchDirectory + watchDirectory, + realpath }); return (directoryName, callback, recursive) => { @@ -1043,6 +1041,15 @@ namespace ts { return filter(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory)); } + function realpath(path: string): string { + try { + return _fs.realpathSync(path); + } + catch { + return path; + } + } + function getModifiedTime(path: string) { try { return _fs.statSync(path).mtime; diff --git a/src/harness/unittests/tscWatchMode.ts b/src/harness/unittests/tscWatchMode.ts index e056153518a..999201029de 100644 --- a/src/harness/unittests/tscWatchMode.ts +++ b/src/harness/unittests/tscWatchMode.ts @@ -2358,6 +2358,50 @@ declare module "fs" { it("uses non recursive dynamic polling when renaming file in subfolder", () => { verifyRenamingFileInSubFolder(TestFSWithWatch.Tsc_WatchDirectory.DynamicPolling); }); + + it("when there are symlinks to folders in recursive folders", () => { + const cwd = "/home/user/projects/myproject"; + const file1: FileOrFolder = { + path: `${cwd}/src/file.ts`, + content: `import * as a from "a"` + }; + const tsconfig: FileOrFolder = { + path: `${cwd}/tsconfig.json`, + content: `{ "compilerOptions": { "extendedDiagnostics": true, "traceResolution": true }}` + }; + const realA: FileOrFolder = { + path: `${cwd}/node_modules/reala/index.d.ts`, + content: `export {}` + }; + const realB: FileOrFolder = { + path: `${cwd}/node_modules/realb/index.d.ts`, + content: `export {}` + }; + const symLinkA: FileOrFolder = { + path: `${cwd}/node_modules/a`, + symLink: `${cwd}/node_modules/reala` + }; + const symLinkB: FileOrFolder = { + path: `${cwd}/node_modules/b`, + symLink: `${cwd}/node_modules/realb` + }; + const symLinkBInA: FileOrFolder = { + path: `${cwd}/node_modules/reala/node_modules/b`, + symLink: `${cwd}/node_modules/b` + }; + const symLinkAInB: FileOrFolder = { + path: `${cwd}/node_modules/realb/node_modules/a`, + symLink: `${cwd}/node_modules/a` + }; + const files = [file1, tsconfig, realA, realB, symLinkA, symLinkB, symLinkBInA, symLinkAInB]; + const environmentVariables = createMap(); + environmentVariables.set("TSC_WATCHDIRECTORY", TestFSWithWatch.Tsc_WatchDirectory.NonRecursiveWatchDirectory); + const host = createWatchedSystem(files, { environmentVariables, currentDirectory: cwd }); + createWatchOfConfigFile("tsconfig.json", host); + checkWatchedDirectories(host, emptyArray, /*recursive*/ true); + checkWatchedDirectories(host, [cwd, `${cwd}/node_modules`, `${cwd}/node_modules/@types`, `${cwd}/node_modules/reala`, `${cwd}/node_modules/realb`, + `${cwd}/node_modules/reala/node_modules`, `${cwd}/node_modules/realb/node_modules`, `${cwd}/src`], /*recursive*/ false); + }); }); }); } diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index cd5f5cf1b18..21f16ab579d 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -314,7 +314,8 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory + watchDirectory, + realpath: s => this.realpath(s) }); } else if (tscWatchDirectory === Tsc_WatchDirectory.NonRecursiveWatchDirectory) { @@ -323,7 +324,8 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory + watchDirectory, + realpath: s => this.realpath(s) }); } else if (tscWatchDirectory === Tsc_WatchDirectory.DynamicPolling) { @@ -333,7 +335,8 @@ interface Array {}` directoryExists: path => this.directoryExists(path), getAccessileSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, - watchDirectory + watchDirectory, + realpath: s => this.realpath(s) }); } } @@ -649,7 +652,7 @@ interface Array {}` const realpath = this.realpath(path); if (path !== realpath) { - return this.getRealFsEntry(isFsEntry, realpath as Path); + return this.getRealFsEntry(isFsEntry, this.toPath(realpath)); } return undefined; From 57e28dfb4f57045bede2670f972bde6b8e00b248 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 07:54:20 -0700 Subject: [PATCH 48/75] Remove unnecessary test (#22962) --- src/compiler/checker.ts | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8850e83a808..fe29a7a3f13 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22501,19 +22501,17 @@ namespace ts { function checkForOfStatement(node: ForOfStatement): void { checkGrammarForInOrForOfStatement(node); - if (node.kind === SyntaxKind.ForOfStatement) { - if (node.awaitModifier) { - const functionFlags = getFunctionFlags(getContainingFunction(node)); - if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Async)) === FunctionFlags.Async && languageVersion < ScriptTarget.ESNext) { - // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper - checkExternalEmitHelpers(node, ExternalEmitHelpers.ForAwaitOfIncludes); - } - } - else if (compilerOptions.downlevelIteration && languageVersion < ScriptTarget.ES2015) { - // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled - checkExternalEmitHelpers(node, ExternalEmitHelpers.ForOfIncludes); + if (node.awaitModifier) { + const functionFlags = getFunctionFlags(getContainingFunction(node)); + if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Async)) === FunctionFlags.Async && languageVersion < ScriptTarget.ESNext) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, ExternalEmitHelpers.ForAwaitOfIncludes); } } + else if (compilerOptions.downlevelIteration && languageVersion < ScriptTarget.ES2015) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, ExternalEmitHelpers.ForOfIncludes); + } // 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 From d8bf95ff108314fc343931abf7e593c6dd705c7c Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 29 Mar 2018 09:13:03 -0700 Subject: [PATCH 49/75] PR feedback --- src/compiler/sys.ts | 8 +++++--- src/harness/virtualFileSystemWithWatch.ts | 6 +++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index b2818918af8..8c2612155e4 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -334,7 +334,7 @@ namespace ts { /*@internal*/ export interface RecursiveDirectoryWatcherHost { watchDirectory: HostWatchDirectory; - getAccessileSortedChildDirectories(path: string): ReadonlyArray; + getAccessibleSortedChildDirectories(path: string): ReadonlyArray; directoryExists(dir: string): boolean; filePathComparer: Comparer; realpath(s: string): string; @@ -393,8 +393,10 @@ namespace ts { function watchChildDirectories(parentDir: string, existingChildWatches: ChildWatches, callback: DirectoryWatcherCallback): ChildWatches { let newChildWatches: DirectoryWatcher[] | undefined; enumerateInsertsAndDeletes( - host.directoryExists(parentDir) ? mapDefined(host.getAccessileSortedChildDirectories(parentDir), child => { + host.directoryExists(parentDir) ? mapDefined(host.getAccessibleSortedChildDirectories(parentDir), child => { const childFullName = getNormalizedAbsolutePath(child, parentDir); + // Filter our the symbolic link directories since those arent included in recursive watch + // which is same behaviour when recursive: true is passed to fs.watch return host.filePathComparer(childFullName, host.realpath(childFullName)) === Comparison.EqualTo ? childFullName : undefined; }) : emptyArray, existingChildWatches, @@ -696,7 +698,7 @@ namespace ts { const watchDirectoryRecursively = createRecursiveDirectoryWatcher({ filePathComparer: useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, directoryExists, - getAccessileSortedChildDirectories: path => getAccessibleFileSystemEntries(path).directories, + getAccessibleSortedChildDirectories: path => getAccessibleFileSystemEntries(path).directories, watchDirectory, realpath }); diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 21f16ab579d..81232fb63f4 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -312,7 +312,7 @@ interface Array {}` const watchDirectory: HostWatchDirectory = (directory, cb) => this.watchFile(directory, () => cb(directory), PollingInterval.Medium); this.customRecursiveWatchDirectory = createRecursiveDirectoryWatcher({ directoryExists: path => this.directoryExists(path), - getAccessileSortedChildDirectories: path => this.getDirectories(path), + getAccessibleSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, watchDirectory, realpath: s => this.realpath(s) @@ -322,7 +322,7 @@ interface Array {}` const watchDirectory: HostWatchDirectory = (directory, cb) => this.watchDirectory(directory, fileName => cb(fileName), /*recursive*/ false); this.customRecursiveWatchDirectory = createRecursiveDirectoryWatcher({ directoryExists: path => this.directoryExists(path), - getAccessileSortedChildDirectories: path => this.getDirectories(path), + getAccessibleSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, watchDirectory, realpath: s => this.realpath(s) @@ -333,7 +333,7 @@ interface Array {}` const watchDirectory: HostWatchDirectory = (directory, cb) => watchFile(directory, () => cb(directory), PollingInterval.Medium); this.customRecursiveWatchDirectory = createRecursiveDirectoryWatcher({ directoryExists: path => this.directoryExists(path), - getAccessileSortedChildDirectories: path => this.getDirectories(path), + getAccessibleSortedChildDirectories: path => this.getDirectories(path), filePathComparer: this.useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive, watchDirectory, realpath: s => this.realpath(s) From eca3d68eb4ed0bea6660de623aef4a36cc03dc4a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 29 Mar 2018 09:39:23 -0700 Subject: [PATCH 50/75] `@typedef` supports nested `@property` names (#22967) Previously it did not, because this capability is not documented on usejsdoc.org. However, several people requested this feature. --- src/compiler/parser.ts | 22 ++++++---- .../reference/typedefTagNested.symbols | 39 ++++++++++++++++ .../reference/typedefTagNested.types | 44 +++++++++++++++++++ .../conformance/jsdoc/typedefTagNested.ts | 32 ++++++++++++++ 4 files changed, 128 insertions(+), 9 deletions(-) create mode 100644 tests/baselines/reference/typedefTagNested.symbols create mode 100644 tests/baselines/reference/typedefTagNested.types create mode 100644 tests/cases/conformance/jsdoc/typedefTagNested.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 182995a3881..2442b79a3d7 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -6497,7 +6497,7 @@ namespace ts { const result = target === PropertyLikeParse.Parameter ? createNode(SyntaxKind.JSDocParameterTag, atToken.pos) : createNode(SyntaxKind.JSDocPropertyTag, atToken.pos); - const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -6511,15 +6511,17 @@ namespace ts { return finishNode(result); } - function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression, name: EntityName) { + function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression, name: EntityName, target: PropertyLikeParse) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { const typeLiteralExpression = createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos()); - let child: JSDocParameterTag | false; + let child: JSDocPropertyLikeTag | JSDocTypeTag | false; let jsdocTypeLiteral: JSDocTypeLiteral; const start = scanner.getStartPos(); - let children: JSDocParameterTag[]; - while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.Parameter, name))) { - children = append(children, child); + let children: JSDocPropertyLikeTag[]; + while (child = tryParse(() => parseChildParameterOrPropertyTag(target, name))) { + if (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) { + children = append(children, child); + } } if (children) { jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); @@ -6623,7 +6625,7 @@ namespace ts { let jsdocTypeLiteral: JSDocTypeLiteral; let childTypeTag: JSDocTypeTag; const start = scanner.getStartPos(); - while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.Property))) { + while (child = tryParse(() => parseChildPropertyTag())) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); } @@ -6683,8 +6685,10 @@ namespace ts { return a.escapedText === b.escapedText; } - function parseChildParameterOrPropertyTag(target: PropertyLikeParse.Property): JSDocTypeTag | JSDocPropertyTag | false; - function parseChildParameterOrPropertyTag(target: PropertyLikeParse.Parameter, name: EntityName): JSDocParameterTag | false; + function parseChildPropertyTag() { + return parseChildParameterOrPropertyTag(PropertyLikeParse.Property) as JSDocTypeTag | JSDocPropertyTag | false; + } + function parseChildParameterOrPropertyTag(target: PropertyLikeParse, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { let canParseTag = true; let seenAsterisk = false; diff --git a/tests/baselines/reference/typedefTagNested.symbols b/tests/baselines/reference/typedefTagNested.symbols new file mode 100644 index 00000000000..41ea2faf0b0 --- /dev/null +++ b/tests/baselines/reference/typedefTagNested.symbols @@ -0,0 +1,39 @@ +=== tests/cases/conformance/jsdoc/a.js === +/** @typedef {Object} App + * @property {string} name + * @property {Object} icons + * @property {string} icons.image32 + * @property {string} icons.image64 + */ +var ex; +>ex : Symbol(ex, Decl(a.js, 6, 3)) + +/** @type {App} */ +const app = { +>app : Symbol(app, Decl(a.js, 9, 5)) + + name: 'name', +>name : Symbol(name, Decl(a.js, 9, 13)) + + icons: { +>icons : Symbol(icons, Decl(a.js, 10, 17)) + + image32: 'x.png', +>image32 : Symbol(image32, Decl(a.js, 11, 12)) + + image64: 'y.png', +>image64 : Symbol(image64, Decl(a.js, 12, 25)) + } +} + +/** @typedef {Object} Opp + * @property {string} name + * @property {Object} oops + * @property {string} horrible + * @type {string} idea + */ + +/** @type {Opp} */ +var mistake; +>mistake : Symbol(mistake, Decl(a.js, 25, 3)) + diff --git a/tests/baselines/reference/typedefTagNested.types b/tests/baselines/reference/typedefTagNested.types new file mode 100644 index 00000000000..6fe8c251205 --- /dev/null +++ b/tests/baselines/reference/typedefTagNested.types @@ -0,0 +1,44 @@ +=== tests/cases/conformance/jsdoc/a.js === +/** @typedef {Object} App + * @property {string} name + * @property {Object} icons + * @property {string} icons.image32 + * @property {string} icons.image64 + */ +var ex; +>ex : any + +/** @type {App} */ +const app = { +>app : { name: string; icons: { image32: string; image64: string; }; } +>{ name: 'name', icons: { image32: 'x.png', image64: 'y.png', }} : { name: string; icons: { image32: string; image64: string; }; } + + name: 'name', +>name : string +>'name' : "name" + + icons: { +>icons : { image32: string; image64: string; } +>{ image32: 'x.png', image64: 'y.png', } : { image32: string; image64: string; } + + image32: 'x.png', +>image32 : string +>'x.png' : "x.png" + + image64: 'y.png', +>image64 : string +>'y.png' : "y.png" + } +} + +/** @typedef {Object} Opp + * @property {string} name + * @property {Object} oops + * @property {string} horrible + * @type {string} idea + */ + +/** @type {Opp} */ +var mistake; +>mistake : { name: string; oops: { horrible: string; }; } + diff --git a/tests/cases/conformance/jsdoc/typedefTagNested.ts b/tests/cases/conformance/jsdoc/typedefTagNested.ts new file mode 100644 index 00000000000..a66ff7aa424 --- /dev/null +++ b/tests/cases/conformance/jsdoc/typedefTagNested.ts @@ -0,0 +1,32 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @strict: true +// @Filename: a.js + +/** @typedef {Object} App + * @property {string} name + * @property {Object} icons + * @property {string} icons.image32 + * @property {string} icons.image64 + */ +var ex; + +/** @type {App} */ +const app = { + name: 'name', + icons: { + image32: 'x.png', + image64: 'y.png', + } +} + +/** @typedef {Object} Opp + * @property {string} name + * @property {Object} oops + * @property {string} horrible + * @type {string} idea + */ + +/** @type {Opp} */ +var mistake; From 65659d7297e7ab6060f06f0c6924d4f0c6f71763 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 10:01:21 -0700 Subject: [PATCH 51/75] Don't allow to iterate over 'never' (#22964) * Don't allow to iterate over 'never' * Include type in error message --- src/compiler/checker.ts | 18 +++++++++++++----- src/compiler/diagnosticMessages.json | 4 ++-- .../reference/YieldExpression6_es6.errors.txt | 4 ++-- .../reference/YieldExpression6_es6.types | 4 ++-- tests/baselines/reference/for-of14.errors.txt | 4 ++-- .../reference/generatorTypeCheck21.errors.txt | 4 ++-- .../iterableArrayPattern21.errors.txt | 4 ++-- .../iterableArrayPattern22.errors.txt | 4 ++-- .../iterableArrayPattern23.errors.txt | 4 ++-- .../iterableArrayPattern24.errors.txt | 4 ++-- .../iteratorSpreadInArray8.errors.txt | 4 ++-- .../reference/neverTypeErrors1.errors.txt | 10 ++++++++-- tests/baselines/reference/neverTypeErrors1.js | 8 +++++++- .../reference/neverTypeErrors1.symbols | 5 +++++ .../baselines/reference/neverTypeErrors1.types | 6 ++++++ .../reference/neverTypeErrors2.errors.txt | 10 ++++++++-- tests/baselines/reference/neverTypeErrors2.js | 8 +++++++- .../reference/neverTypeErrors2.symbols | 5 +++++ .../baselines/reference/neverTypeErrors2.types | 6 ++++++ .../types.asyncGenerators.esnext.2.errors.txt | 12 ++++++------ .../types.forAwait.esnext.2.errors.txt | 16 ++++++++-------- .../types.forAwait.esnext.3.errors.txt | 16 ++++++++-------- .../types/never/neverTypeErrors1.ts | 4 +++- .../types/never/neverTypeErrors2.ts | 4 +++- 24 files changed, 113 insertions(+), 55 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fe29a7a3f13..c579fadf9a0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22627,7 +22627,12 @@ namespace ts { * 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: Type, errorNode: Node, allowStringInput: boolean, allowAsyncIterables: boolean, checkAssignability: boolean): Type { + function getIteratedTypeOrElementType(inputType: Type, errorNode: Node, allowStringInput: boolean, allowAsyncIterables: boolean, checkAssignability: boolean): Type | undefined { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); + return undefined; + } + const uplevelIteration = languageVersion >= ScriptTarget.ES2015; const downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; @@ -22794,11 +22799,8 @@ namespace ts { const signatures = methodType && getSignaturesOfType(methodType, SignatureKind.Call); if (!some(signatures)) { if (errorNode) { - error(errorNode, - allowAsyncIterables - ? Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator - : Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); // only report on the first error + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); errorNode = undefined; } return undefined; @@ -22821,6 +22823,12 @@ namespace ts { } } + function reportTypeNotIterableError(errorNode: Node, type: Type, allowAsyncIterables: boolean): void { + error(errorNode, allowAsyncIterables + ? Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } + /** * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on * Iterators instead of Iterables. Here is the structure: diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index ea067001377..f0ce19ea1b3 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1668,7 +1668,7 @@ "category": "Error", "code": 2487 }, - "Type must have a '[Symbol.iterator]()' method that returns an iterator.": { + "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator.": { "category": "Error", "code": 2488 }, @@ -1732,7 +1732,7 @@ "category": "Error", "code": 2503 }, - "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator.": { + "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator.": { "category": "Error", "code": 2504 }, diff --git a/tests/baselines/reference/YieldExpression6_es6.errors.txt b/tests/baselines/reference/YieldExpression6_es6.errors.txt index b8c0967864c..db93ba256cb 100644 --- a/tests/baselines/reference/YieldExpression6_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression6_es6.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts(2,9): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts(2,9): error TS2488: Type '() => any' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts (1 errors) ==== function* foo() { yield*foo ~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +!!! error TS2488: Type '() => any' must have a '[Symbol.iterator]()' method that returns an iterator. } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression6_es6.types b/tests/baselines/reference/YieldExpression6_es6.types index c30fc64c8ad..c3f813c55a1 100644 --- a/tests/baselines/reference/YieldExpression6_es6.types +++ b/tests/baselines/reference/YieldExpression6_es6.types @@ -1,8 +1,8 @@ === tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts === function* foo() { ->foo : () => IterableIterator +>foo : () => any yield*foo >yield*foo : any ->foo : () => IterableIterator +>foo : () => any } diff --git a/tests/baselines/reference/for-of14.errors.txt b/tests/baselines/reference/for-of14.errors.txt index d4ec79620d9..bc8d4478834 100644 --- a/tests/baselines/reference/for-of14.errors.txt +++ b/tests/baselines/reference/for-of14.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/for-ofStatements/for-of14.ts(8,11): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/es6/for-ofStatements/for-of14.ts(8,11): error TS2488: Type 'StringIterator' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/for-ofStatements/for-of14.ts (1 errors) ==== @@ -11,4 +11,4 @@ tests/cases/conformance/es6/for-ofStatements/for-of14.ts(8,11): error TS2488: Ty var v: string; for (v of new StringIterator) { } // Should fail because the iterator is not iterable ~~~~~~~~~~~~~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file +!!! error TS2488: Type 'StringIterator' must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck21.errors.txt b/tests/baselines/reference/generatorTypeCheck21.errors.txt index 0ef66aa1bd7..b40c4750d04 100644 --- a/tests/baselines/reference/generatorTypeCheck21.errors.txt +++ b/tests/baselines/reference/generatorTypeCheck21.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck21.ts(5,13): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck21.ts(5,13): error TS2488: Type 'Bar' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck21.ts (1 errors) ==== @@ -8,5 +8,5 @@ tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck21.ts(5,13): erro yield; yield * new Bar; ~~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +!!! error TS2488: Type 'Bar' must have a '[Symbol.iterator]()' method that returns an iterator. } \ No newline at end of file diff --git a/tests/baselines/reference/iterableArrayPattern21.errors.txt b/tests/baselines/reference/iterableArrayPattern21.errors.txt index 7e853c90b24..4e05beb27f8 100644 --- a/tests/baselines/reference/iterableArrayPattern21.errors.txt +++ b/tests/baselines/reference/iterableArrayPattern21.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/destructuring/iterableArrayPattern21.ts(1,5): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/es6/destructuring/iterableArrayPattern21.ts(1,5): error TS2488: Type '{ 0: string; 1: boolean; }' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/destructuring/iterableArrayPattern21.ts (1 errors) ==== var [a, b] = { 0: "", 1: true }; ~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file +!!! error TS2488: Type '{ 0: string; 1: boolean; }' must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file diff --git a/tests/baselines/reference/iterableArrayPattern22.errors.txt b/tests/baselines/reference/iterableArrayPattern22.errors.txt index 3e40e4fd602..513c25221da 100644 --- a/tests/baselines/reference/iterableArrayPattern22.errors.txt +++ b/tests/baselines/reference/iterableArrayPattern22.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/destructuring/iterableArrayPattern22.ts(1,5): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/es6/destructuring/iterableArrayPattern22.ts(1,5): error TS2488: Type '{ 0: string; 1: boolean; }' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/destructuring/iterableArrayPattern22.ts (1 errors) ==== var [...a] = { 0: "", 1: true }; ~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file +!!! error TS2488: Type '{ 0: string; 1: boolean; }' must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file diff --git a/tests/baselines/reference/iterableArrayPattern23.errors.txt b/tests/baselines/reference/iterableArrayPattern23.errors.txt index 1df5d909aed..ad25ad2fb42 100644 --- a/tests/baselines/reference/iterableArrayPattern23.errors.txt +++ b/tests/baselines/reference/iterableArrayPattern23.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/es6/destructuring/iterableArrayPattern23.ts(2,1): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/es6/destructuring/iterableArrayPattern23.ts(2,1): error TS2488: Type '{ 0: string; 1: true; }' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/destructuring/iterableArrayPattern23.ts (1 errors) ==== var a: string, b: boolean; [a, b] = { 0: "", 1: true }; ~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file +!!! error TS2488: Type '{ 0: string; 1: true; }' must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file diff --git a/tests/baselines/reference/iterableArrayPattern24.errors.txt b/tests/baselines/reference/iterableArrayPattern24.errors.txt index e954c59f2ea..f4edf39d3b5 100644 --- a/tests/baselines/reference/iterableArrayPattern24.errors.txt +++ b/tests/baselines/reference/iterableArrayPattern24.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/es6/destructuring/iterableArrayPattern24.ts(2,1): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/es6/destructuring/iterableArrayPattern24.ts(2,1): error TS2488: Type '{ 0: string; 1: true; }' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/destructuring/iterableArrayPattern24.ts (1 errors) ==== var a: string, b: boolean[]; [a, ...b] = { 0: "", 1: true }; ~~~~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file +!!! error TS2488: Type '{ 0: string; 1: true; }' must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInArray8.errors.txt b/tests/baselines/reference/iteratorSpreadInArray8.errors.txt index 1f8c9629424..b7194fe44d0 100644 --- a/tests/baselines/reference/iteratorSpreadInArray8.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInArray8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/spread/iteratorSpreadInArray8.ts(10,17): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/es6/spread/iteratorSpreadInArray8.ts(10,17): error TS2488: Type 'SymbolIterator' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/spread/iteratorSpreadInArray8.ts (1 errors) ==== @@ -13,4 +13,4 @@ tests/cases/conformance/es6/spread/iteratorSpreadInArray8.ts(10,17): error TS248 var array = [...new SymbolIterator]; ~~~~~~~~~~~~~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file +!!! error TS2488: Type 'SymbolIterator' must have a '[Symbol.iterator]()' method that returns an iterator. \ No newline at end of file diff --git a/tests/baselines/reference/neverTypeErrors1.errors.txt b/tests/baselines/reference/neverTypeErrors1.errors.txt index 56233fb6101..e0746084de0 100644 --- a/tests/baselines/reference/neverTypeErrors1.errors.txt +++ b/tests/baselines/reference/neverTypeErrors1.errors.txt @@ -8,9 +8,10 @@ tests/cases/conformance/types/never/neverTypeErrors1.ts(9,5): error TS2349: Cann tests/cases/conformance/types/never/neverTypeErrors1.ts(13,5): error TS2322: Type 'undefined' is not assignable to type 'never'. tests/cases/conformance/types/never/neverTypeErrors1.ts(17,5): error TS2322: Type '1' is not assignable to type 'never'. tests/cases/conformance/types/never/neverTypeErrors1.ts(20,16): error TS2534: A function returning 'never' cannot have a reachable end point. +tests/cases/conformance/types/never/neverTypeErrors1.ts(23,17): error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator. -==== tests/cases/conformance/types/never/neverTypeErrors1.ts (10 errors) ==== +==== tests/cases/conformance/types/never/neverTypeErrors1.ts (11 errors) ==== function f1() { let x: never; x = 1; @@ -51,4 +52,9 @@ tests/cases/conformance/types/never/neverTypeErrors1.ts(20,16): error TS2534: A function f4(): never { ~~~~~ !!! error TS2534: A function returning 'never' cannot have a reachable end point. - } \ No newline at end of file + } + + for (const n of f4()) {} + ~~~~ +!!! error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator. + \ No newline at end of file diff --git a/tests/baselines/reference/neverTypeErrors1.js b/tests/baselines/reference/neverTypeErrors1.js index 4bbe131cd05..f05a3ce1c61 100644 --- a/tests/baselines/reference/neverTypeErrors1.js +++ b/tests/baselines/reference/neverTypeErrors1.js @@ -19,7 +19,10 @@ function f3(): never { } function f4(): never { -} +} + +for (const n of f4()) {} + //// [neverTypeErrors1.js] function f1() { @@ -40,3 +43,6 @@ function f3() { } function f4() { } +for (var _i = 0, _a = f4(); _i < _a.length; _i++) { + var n = _a[_i]; +} diff --git a/tests/baselines/reference/neverTypeErrors1.symbols b/tests/baselines/reference/neverTypeErrors1.symbols index eee8e493144..f565a4bf7b5 100644 --- a/tests/baselines/reference/neverTypeErrors1.symbols +++ b/tests/baselines/reference/neverTypeErrors1.symbols @@ -43,3 +43,8 @@ function f3(): never { function f4(): never { >f4 : Symbol(f4, Decl(neverTypeErrors1.ts, 17, 1)) } + +for (const n of f4()) {} +>n : Symbol(n, Decl(neverTypeErrors1.ts, 22, 10)) +>f4 : Symbol(f4, Decl(neverTypeErrors1.ts, 17, 1)) + diff --git a/tests/baselines/reference/neverTypeErrors1.types b/tests/baselines/reference/neverTypeErrors1.types index fe21a8c5ba2..89dbf92e8f5 100644 --- a/tests/baselines/reference/neverTypeErrors1.types +++ b/tests/baselines/reference/neverTypeErrors1.types @@ -56,3 +56,9 @@ function f3(): never { function f4(): never { >f4 : () => never } + +for (const n of f4()) {} +>n : any +>f4() : never +>f4 : () => never + diff --git a/tests/baselines/reference/neverTypeErrors2.errors.txt b/tests/baselines/reference/neverTypeErrors2.errors.txt index eb24ac8251c..4f5845917c5 100644 --- a/tests/baselines/reference/neverTypeErrors2.errors.txt +++ b/tests/baselines/reference/neverTypeErrors2.errors.txt @@ -8,9 +8,10 @@ tests/cases/conformance/types/never/neverTypeErrors2.ts(9,5): error TS2349: Cann tests/cases/conformance/types/never/neverTypeErrors2.ts(13,5): error TS2322: Type 'undefined' is not assignable to type 'never'. tests/cases/conformance/types/never/neverTypeErrors2.ts(17,5): error TS2322: Type '1' is not assignable to type 'never'. tests/cases/conformance/types/never/neverTypeErrors2.ts(20,16): error TS2534: A function returning 'never' cannot have a reachable end point. +tests/cases/conformance/types/never/neverTypeErrors2.ts(23,17): error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator. -==== tests/cases/conformance/types/never/neverTypeErrors2.ts (10 errors) ==== +==== tests/cases/conformance/types/never/neverTypeErrors2.ts (11 errors) ==== function f1() { let x: never; x = 1; @@ -51,4 +52,9 @@ tests/cases/conformance/types/never/neverTypeErrors2.ts(20,16): error TS2534: A function f4(): never { ~~~~~ !!! error TS2534: A function returning 'never' cannot have a reachable end point. - } \ No newline at end of file + } + + for (const n of f4()) {} + ~~~~ +!!! error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator. + \ No newline at end of file diff --git a/tests/baselines/reference/neverTypeErrors2.js b/tests/baselines/reference/neverTypeErrors2.js index 940c4df5556..dfe9f32b627 100644 --- a/tests/baselines/reference/neverTypeErrors2.js +++ b/tests/baselines/reference/neverTypeErrors2.js @@ -19,7 +19,10 @@ function f3(): never { } function f4(): never { -} +} + +for (const n of f4()) {} + //// [neverTypeErrors2.js] function f1() { @@ -40,3 +43,6 @@ function f3() { } function f4() { } +for (var _i = 0, _a = f4(); _i < _a.length; _i++) { + var n = _a[_i]; +} diff --git a/tests/baselines/reference/neverTypeErrors2.symbols b/tests/baselines/reference/neverTypeErrors2.symbols index 17433391576..ec6b0086ee7 100644 --- a/tests/baselines/reference/neverTypeErrors2.symbols +++ b/tests/baselines/reference/neverTypeErrors2.symbols @@ -43,3 +43,8 @@ function f3(): never { function f4(): never { >f4 : Symbol(f4, Decl(neverTypeErrors2.ts, 17, 1)) } + +for (const n of f4()) {} +>n : Symbol(n, Decl(neverTypeErrors2.ts, 22, 10)) +>f4 : Symbol(f4, Decl(neverTypeErrors2.ts, 17, 1)) + diff --git a/tests/baselines/reference/neverTypeErrors2.types b/tests/baselines/reference/neverTypeErrors2.types index 9e45bf1aeba..510f32506bb 100644 --- a/tests/baselines/reference/neverTypeErrors2.types +++ b/tests/baselines/reference/neverTypeErrors2.types @@ -56,3 +56,9 @@ function f3(): never { function f4(): never { >f4 : () => never } + +for (const n of f4()) {} +>n : any +>f4() : never +>f4 : () => never + diff --git a/tests/baselines/reference/types.asyncGenerators.esnext.2.errors.txt b/tests/baselines/reference/types.asyncGenerators.esnext.2.errors.txt index a6a0243ded6..3d28ddb505a 100644 --- a/tests/baselines/reference/types.asyncGenerators.esnext.2.errors.txt +++ b/tests/baselines/reference/types.asyncGenerators.esnext.2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts(2,12): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. -tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts(8,12): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts(2,12): error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts(8,12): error TS2504: Type 'Promise' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts(10,7): error TS2322: Type '() => AsyncIterableIterator' is not assignable to type '() => AsyncIterableIterator'. Type 'AsyncIterableIterator' is not assignable to type 'AsyncIterableIterator'. Type 'string' is not assignable to type 'number'. @@ -45,14 +45,14 @@ tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts( Type '(value?: any) => Promise>' is not assignable to type '(value?: any) => IteratorResult'. Type 'Promise>' is not assignable to type 'IteratorResult'. Property 'done' is missing in type 'Promise>'. -tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts(74,12): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts(74,12): error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. ==== tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts (24 errors) ==== async function * inferReturnType1() { yield* {}; ~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } async function * inferReturnType2() { yield* inferReturnType2(); @@ -60,7 +60,7 @@ tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts( async function * inferReturnType3() { yield* Promise.resolve([1, 2]); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type 'Promise' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } const assignability1: () => AsyncIterableIterator = async function * () { ~~~~~~~~~~~~~~ @@ -194,5 +194,5 @@ tests/cases/conformance/types/asyncGenerators/types.asyncGenerators.esnext.2.ts( async function * yieldStar() { yield* {}; ~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } \ No newline at end of file diff --git a/tests/baselines/reference/types.forAwait.esnext.2.errors.txt b/tests/baselines/reference/types.forAwait.esnext.2.errors.txt index 367dc5a282f..530743d9825 100644 --- a/tests/baselines/reference/types.forAwait.esnext.2.errors.txt +++ b/tests/baselines/reference/types.forAwait.esnext.2.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(6,27): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. -tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(8,21): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(6,27): error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(8,21): error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(10,16): error TS2322: Type 'number' is not assignable to type 'string'. tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(12,16): error TS2322: Type 'number' is not assignable to type 'string'. -tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(14,21): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. -tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(16,15): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(14,21): error TS2488: Type 'AsyncIterable' must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(16,15): error TS2488: Type 'AsyncIterable' must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts (6 errors) ==== @@ -14,11 +14,11 @@ tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(16,15): error let z: string; for await (const x of {}) { ~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } for await (y of {}) { ~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } for await (z of asyncIterable) { ~ @@ -30,10 +30,10 @@ tests/cases/conformance/types/forAwait/types.forAwait.esnext.2.ts(16,15): error } for (const x of asyncIterable) { ~~~~~~~~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +!!! error TS2488: Type 'AsyncIterable' must have a '[Symbol.iterator]()' method that returns an iterator. } for (y of asyncIterable) { ~~~~~~~~~~~~~ -!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. +!!! error TS2488: Type 'AsyncIterable' must have a '[Symbol.iterator]()' method that returns an iterator. } } \ No newline at end of file diff --git a/tests/baselines/reference/types.forAwait.esnext.3.errors.txt b/tests/baselines/reference/types.forAwait.esnext.3.errors.txt index 234e2eb0751..baf8c76b24a 100644 --- a/tests/baselines/reference/types.forAwait.esnext.3.errors.txt +++ b/tests/baselines/reference/types.forAwait.esnext.3.errors.txt @@ -1,8 +1,8 @@ error TS2318: Cannot find global type 'AsyncIterableIterator'. -tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(3,27): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. -tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(5,21): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. -tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(10,27): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. -tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(12,21): error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(3,27): error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(5,21): error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(10,27): error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(12,21): error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. !!! error TS2318: Cannot find global type 'AsyncIterableIterator'. @@ -11,21 +11,21 @@ tests/cases/conformance/types/forAwait/types.forAwait.esnext.3.ts(12,21): error let y: number; for await (const x of {}) { ~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } for await (y of {}) { ~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } } async function* f2() { let y: number; for await (const x of {}) { ~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } for await (y of {}) { ~~ -!!! error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator. +!!! error TS2504: Type '{}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator. } } \ No newline at end of file diff --git a/tests/cases/conformance/types/never/neverTypeErrors1.ts b/tests/cases/conformance/types/never/neverTypeErrors1.ts index deab74c6690..20c9daf9e3b 100644 --- a/tests/cases/conformance/types/never/neverTypeErrors1.ts +++ b/tests/cases/conformance/types/never/neverTypeErrors1.ts @@ -18,4 +18,6 @@ function f3(): never { } function f4(): never { -} \ No newline at end of file +} + +for (const n of f4()) {} diff --git a/tests/cases/conformance/types/never/neverTypeErrors2.ts b/tests/cases/conformance/types/never/neverTypeErrors2.ts index 2c637580d00..66f12d7d322 100644 --- a/tests/cases/conformance/types/never/neverTypeErrors2.ts +++ b/tests/cases/conformance/types/never/neverTypeErrors2.ts @@ -20,4 +20,6 @@ function f3(): never { } function f4(): never { -} \ No newline at end of file +} + +for (const n of f4()) {} From ac97987ee00f4f6c5eb44c3f76abc2677c99f785 Mon Sep 17 00:00:00 2001 From: Dhruv Rajvanshi Date: Thu, 29 Mar 2018 22:59:58 +0530 Subject: [PATCH 52/75] Allow strict mode reserved keywords in qualified type names; Fixes 22785 --- src/compiler/utilities.ts | 4 ++-- .../strictModeEnumMemberNameReserved.js | 15 +++++++++++++++ .../strictModeEnumMemberNameReserved.symbols | 17 +++++++++++++++++ .../strictModeEnumMemberNameReserved.types | 19 +++++++++++++++++++ .../strictModeReservedWord.errors.txt | 17 +---------------- .../strictModeEnumMemberNameReserved.ts | 6 ++++++ 6 files changed, 60 insertions(+), 18 deletions(-) create mode 100644 tests/baselines/reference/strictModeEnumMemberNameReserved.js create mode 100644 tests/baselines/reference/strictModeEnumMemberNameReserved.symbols create mode 100644 tests/baselines/reference/strictModeEnumMemberNameReserved.types create mode 100644 tests/cases/compiler/strictModeEnumMemberNameReserved.ts diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 1cc3add43e3..4f9dcf69310 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2059,12 +2059,12 @@ namespace ts { // Name in member declaration or property name in property access return (parent).name === node; case SyntaxKind.QualifiedName: - // Name on right hand side of dot in a type query + // Name on right hand side of dot in a type query or type reference if ((parent).right === node) { while (parent.kind === SyntaxKind.QualifiedName) { parent = parent.parent; } - return parent.kind === SyntaxKind.TypeQuery; + return parent.kind === SyntaxKind.TypeQuery || parent.kind === SyntaxKind.TypeReference; } return false; case SyntaxKind.BindingElement: diff --git a/tests/baselines/reference/strictModeEnumMemberNameReserved.js b/tests/baselines/reference/strictModeEnumMemberNameReserved.js new file mode 100644 index 00000000000..1dd89af1686 --- /dev/null +++ b/tests/baselines/reference/strictModeEnumMemberNameReserved.js @@ -0,0 +1,15 @@ +//// [strictModeEnumMemberNameReserved.ts] +"use strict"; +enum E { + static +} + +const x1: E.static = E.static; + +//// [strictModeEnumMemberNameReserved.js] +"use strict"; +var E; +(function (E) { + E[E["static"] = 0] = "static"; +})(E || (E = {})); +var x1 = E.static; diff --git a/tests/baselines/reference/strictModeEnumMemberNameReserved.symbols b/tests/baselines/reference/strictModeEnumMemberNameReserved.symbols new file mode 100644 index 00000000000..282c5ebab4e --- /dev/null +++ b/tests/baselines/reference/strictModeEnumMemberNameReserved.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/strictModeEnumMemberNameReserved.ts === +"use strict"; +enum E { +>E : Symbol(E, Decl(strictModeEnumMemberNameReserved.ts, 0, 13)) + + static +>static : Symbol(E.static, Decl(strictModeEnumMemberNameReserved.ts, 1, 8)) +} + +const x1: E.static = E.static; +>x1 : Symbol(x1, Decl(strictModeEnumMemberNameReserved.ts, 5, 5)) +>E : Symbol(E, Decl(strictModeEnumMemberNameReserved.ts, 0, 13)) +>static : Symbol(E.static, Decl(strictModeEnumMemberNameReserved.ts, 1, 8)) +>E.static : Symbol(E.static, Decl(strictModeEnumMemberNameReserved.ts, 1, 8)) +>E : Symbol(E, Decl(strictModeEnumMemberNameReserved.ts, 0, 13)) +>static : Symbol(E.static, Decl(strictModeEnumMemberNameReserved.ts, 1, 8)) + diff --git a/tests/baselines/reference/strictModeEnumMemberNameReserved.types b/tests/baselines/reference/strictModeEnumMemberNameReserved.types new file mode 100644 index 00000000000..867df395ced --- /dev/null +++ b/tests/baselines/reference/strictModeEnumMemberNameReserved.types @@ -0,0 +1,19 @@ +=== tests/cases/compiler/strictModeEnumMemberNameReserved.ts === +"use strict"; +>"use strict" : "use strict" + +enum E { +>E : E + + static +>static : E +} + +const x1: E.static = E.static; +>x1 : E +>E : any +>static : E +>E.static : E +>E : typeof E +>static : E + diff --git a/tests/baselines/reference/strictModeReservedWord.errors.txt b/tests/baselines/reference/strictModeReservedWord.errors.txt index f2f74c81a93..87f73c5780a 100644 --- a/tests/baselines/reference/strictModeReservedWord.errors.txt +++ b/tests/baselines/reference/strictModeReservedWord.errors.txt @@ -28,22 +28,17 @@ tests/cases/compiler/strictModeReservedWord.ts(19,21): error TS1212: Identifier tests/cases/compiler/strictModeReservedWord.ts(19,21): error TS2503: Cannot find namespace 'private'. tests/cases/compiler/strictModeReservedWord.ts(20,22): error TS1212: Identifier expected. 'private' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(20,22): error TS2503: Cannot find namespace 'private'. -tests/cases/compiler/strictModeReservedWord.ts(20,30): error TS1212: Identifier expected. 'package' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(21,22): error TS1212: Identifier expected. 'private' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(21,22): error TS2503: Cannot find namespace 'private'. -tests/cases/compiler/strictModeReservedWord.ts(21,30): error TS1212: Identifier expected. 'package' is a reserved word in strict mode. -tests/cases/compiler/strictModeReservedWord.ts(21,38): error TS1212: Identifier expected. 'protected' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(22,9): error TS2300: Duplicate identifier 'b'. tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS1212: Identifier expected. 'interface' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS2503: Cannot find namespace 'interface'. -tests/cases/compiler/strictModeReservedWord.ts(22,22): error TS1212: Identifier expected. 'package' is a reserved word in strict mode. -tests/cases/compiler/strictModeReservedWord.ts(22,30): error TS1212: Identifier expected. 'implements' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(23,5): error TS2552: Cannot find name 'ublic'. Did you mean 'public'? tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS1212: Identifier expected. 'static' is a reserved word in strict mode. tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -==== tests/cases/compiler/strictModeReservedWord.ts (43 errors) ==== +==== tests/cases/compiler/strictModeReservedWord.ts (38 errors) ==== let let = 10; ~~~ !!! error TS2480: 'let' is not allowed to be used as a name in 'let' or 'const' declarations. @@ -124,17 +119,11 @@ tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invok !!! error TS1212: Identifier expected. 'private' is a reserved word in strict mode. ~~~~~~~ !!! error TS2503: Cannot find namespace 'private'. - ~~~~~~~ -!!! error TS1212: Identifier expected. 'package' is a reserved word in strict mode. function foo2(x: private.package.protected) { } ~~~~~~~ !!! error TS1212: Identifier expected. 'private' is a reserved word in strict mode. ~~~~~~~ !!! error TS2503: Cannot find namespace 'private'. - ~~~~~~~ -!!! error TS1212: Identifier expected. 'package' is a reserved word in strict mode. - ~~~~~~~~~ -!!! error TS1212: Identifier expected. 'protected' is a reserved word in strict mode. let b: interface.package.implements.B; ~ !!! error TS2300: Duplicate identifier 'b'. @@ -142,10 +131,6 @@ tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invok !!! error TS1212: Identifier expected. 'interface' is a reserved word in strict mode. ~~~~~~~~~ !!! error TS2503: Cannot find namespace 'interface'. - ~~~~~~~ -!!! error TS1212: Identifier expected. 'package' is a reserved word in strict mode. - ~~~~~~~~~~ -!!! error TS1212: Identifier expected. 'implements' is a reserved word in strict mode. ublic(); ~~~~~ !!! error TS2552: Cannot find name 'ublic'. Did you mean 'public'? diff --git a/tests/cases/compiler/strictModeEnumMemberNameReserved.ts b/tests/cases/compiler/strictModeEnumMemberNameReserved.ts new file mode 100644 index 00000000000..a41985b16f8 --- /dev/null +++ b/tests/cases/compiler/strictModeEnumMemberNameReserved.ts @@ -0,0 +1,6 @@ +"use strict"; +enum E { + static +} + +const x1: E.static = E.static; \ No newline at end of file From 5c491333823d59d48d4f6376cfd59a68176c8553 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 11:01:05 -0700 Subject: [PATCH 53/75] Add regression tests documenting current behavior of #14121 (#22748) --- ...tAssignmentMembersVisibleInAugmentation.js | 39 +++++++++++++++++++ ...gnmentMembersVisibleInAugmentation.symbols | 36 +++++++++++++++++ ...signmentMembersVisibleInAugmentation.types | 36 +++++++++++++++++ ...tAssignmentMembersVisibleInAugmentation.ts | 19 +++++++++ 4 files changed, 130 insertions(+) create mode 100644 tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.js create mode 100644 tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.symbols create mode 100644 tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.types create mode 100644 tests/cases/compiler/exportAssignmentMembersVisibleInAugmentation.ts diff --git a/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.js b/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.js new file mode 100644 index 00000000000..8690fecc969 --- /dev/null +++ b/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.js @@ -0,0 +1,39 @@ +//// [tests/cases/compiler/exportAssignmentMembersVisibleInAugmentation.ts] //// + +//// [index.d.ts] +export = foo; +declare namespace foo { + export type T = number; +} + +//// [a.ts] +import * as foo from "foo"; +declare module "foo" { + export function f(): T; // OK +} + +//// [b.ts] +import * as foo from "foo"; +declare module "foo" { + export function g(): foo.T; // OK +} + + +//// [a.js] +"use strict"; +exports.__esModule = true; +//// [b.js] +"use strict"; +exports.__esModule = true; + + +//// [a.d.ts] +declare module "foo" { + function f(): T; +} +export {}; +//// [b.d.ts] +import * as foo from "foo"; +declare module "foo" { + function g(): foo.T; +} diff --git a/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.symbols b/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.symbols new file mode 100644 index 00000000000..a5cf5aa514c --- /dev/null +++ b/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.symbols @@ -0,0 +1,36 @@ +=== /node_modules/foo/index.d.ts === +export = foo; +>foo : Symbol(foo, Decl(index.d.ts, 0, 13)) + +declare namespace foo { +>foo : Symbol(foo, Decl(index.d.ts, 0, 13), Decl(a.ts, 0, 27), Decl(b.ts, 0, 27)) + + export type T = number; +>T : Symbol(T, Decl(index.d.ts, 1, 23)) +} + +=== /a.ts === +import * as foo from "foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 6)) + +declare module "foo" { +>"foo" : Symbol(foo, Decl(index.d.ts, 0, 13), Decl(a.ts, 0, 27), Decl(b.ts, 0, 27)) + + export function f(): T; // OK +>f : Symbol(f, Decl(a.ts, 1, 22)) +>T : Symbol(T, Decl(index.d.ts, 1, 23)) +} + +=== /b.ts === +import * as foo from "foo"; +>foo : Symbol(foo, Decl(b.ts, 0, 6)) + +declare module "foo" { +>"foo" : Symbol(foo, Decl(index.d.ts, 0, 13), Decl(a.ts, 0, 27), Decl(b.ts, 0, 27)) + + export function g(): foo.T; // OK +>g : Symbol(g, Decl(b.ts, 1, 22)) +>foo : Symbol(foo, Decl(b.ts, 0, 6)) +>T : Symbol(T, Decl(index.d.ts, 1, 23)) +} + diff --git a/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.types b/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.types new file mode 100644 index 00000000000..74efa10e4d2 --- /dev/null +++ b/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.types @@ -0,0 +1,36 @@ +=== /node_modules/foo/index.d.ts === +export = foo; +>foo : any + +declare namespace foo { +>foo : typeof foo + + export type T = number; +>T : number +} + +=== /a.ts === +import * as foo from "foo"; +>foo : typeof foo + +declare module "foo" { +>"foo" : typeof foo + + export function f(): T; // OK +>f : () => number +>T : number +} + +=== /b.ts === +import * as foo from "foo"; +>foo : typeof foo + +declare module "foo" { +>"foo" : typeof foo + + export function g(): foo.T; // OK +>g : () => number +>foo : any +>T : number +} + diff --git a/tests/cases/compiler/exportAssignmentMembersVisibleInAugmentation.ts b/tests/cases/compiler/exportAssignmentMembersVisibleInAugmentation.ts new file mode 100644 index 00000000000..72ac174b044 --- /dev/null +++ b/tests/cases/compiler/exportAssignmentMembersVisibleInAugmentation.ts @@ -0,0 +1,19 @@ +// @declaration: true + +// @Filename: /node_modules/foo/index.d.ts +export = foo; +declare namespace foo { + export type T = number; +} + +// @Filename: /a.ts +import * as foo from "foo"; +declare module "foo" { + export function f(): T; // OK +} + +// @Filename: /b.ts +import * as foo from "foo"; +declare module "foo" { + export function g(): foo.T; // OK +} From 6c517ef276dea8cc88e83d6d1bd5fe938413e4f6 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 11:03:33 -0700 Subject: [PATCH 54/75] Dont let an import that doesnt need helpers override one that does (#22966) --- src/compiler/transformers/utilities.ts | 2 +- .../esModuleInteropImportTSLibHasImport.js | 39 ++++++++++++++++++ ...sModuleInteropImportTSLibHasImport.symbols | 33 +++++++++++++++ .../esModuleInteropImportTSLibHasImport.types | 41 +++++++++++++++++++ .../esModuleInteropImportTSLibHasImport.ts | 20 +++++++++ 5 files changed, 134 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/esModuleInteropImportTSLibHasImport.js create mode 100644 tests/baselines/reference/esModuleInteropImportTSLibHasImport.symbols create mode 100644 tests/baselines/reference/esModuleInteropImportTSLibHasImport.types create mode 100644 tests/cases/compiler/esModuleInteropImportTSLibHasImport.ts diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts index c64c1d169b8..55adeba0b76 100644 --- a/src/compiler/transformers/utilities.ts +++ b/src/compiler/transformers/utilities.ts @@ -60,7 +60,7 @@ namespace ts { // import * as x from "mod" // import { x, y } from "mod" externalImports.push(node); - hasImportStarOrImportDefault = getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; case SyntaxKind.ImportEqualsDeclaration: diff --git a/tests/baselines/reference/esModuleInteropImportTSLibHasImport.js b/tests/baselines/reference/esModuleInteropImportTSLibHasImport.js new file mode 100644 index 00000000000..a4fa39fc8b7 --- /dev/null +++ b/tests/baselines/reference/esModuleInteropImportTSLibHasImport.js @@ -0,0 +1,39 @@ +//// [tests/cases/compiler/esModuleInteropImportTSLibHasImport.ts] //// + +//// [types.d.ts] +declare module "tslib" { export const __exportStar: any; export const __importDefault: any; export const __importStar: any; } +//// [username.ts] +export const username = () => 'username'; +//// [index.ts] +export * from './username'; +//// [hello.ts] +const sayHello = (name?: string) => void (`Hello, ${name}!`); + +export default sayHello; +//// [index.ts] +import sayHello from "./hello"; +import { username } from './utils'; + +sayHello(username()); + +//// [username.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.username = () => 'username'; +//// [index.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./username"), exports); +//// [hello.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const sayHello = (name) => void (`Hello, ${name}!`); +exports.default = sayHello; +//// [index.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const hello_1 = tslib_1.__importDefault(require("./hello")); +const utils_1 = require("./utils"); +hello_1.default(utils_1.username()); diff --git a/tests/baselines/reference/esModuleInteropImportTSLibHasImport.symbols b/tests/baselines/reference/esModuleInteropImportTSLibHasImport.symbols new file mode 100644 index 00000000000..0c200f3b5ad --- /dev/null +++ b/tests/baselines/reference/esModuleInteropImportTSLibHasImport.symbols @@ -0,0 +1,33 @@ +=== tests/cases/compiler/types.d.ts === +declare module "tslib" { export const __exportStar: any; export const __importDefault: any; export const __importStar: any; } +>"tslib" : Symbol("tslib", Decl(types.d.ts, 0, 0)) +>__exportStar : Symbol(__exportStar, Decl(types.d.ts, 0, 37)) +>__importDefault : Symbol(__importDefault, Decl(types.d.ts, 0, 69)) +>__importStar : Symbol(__importStar, Decl(types.d.ts, 0, 104)) + +=== tests/cases/compiler/utils/username.ts === +export const username = () => 'username'; +>username : Symbol(username, Decl(username.ts, 0, 12)) + +=== tests/cases/compiler/utils/index.ts === +export * from './username'; +No type information for this code.=== tests/cases/compiler/hello.ts === +const sayHello = (name?: string) => void (`Hello, ${name}!`); +>sayHello : Symbol(sayHello, Decl(hello.ts, 0, 5)) +>name : Symbol(name, Decl(hello.ts, 0, 18)) +>name : Symbol(name, Decl(hello.ts, 0, 18)) + +export default sayHello; +>sayHello : Symbol(sayHello, Decl(hello.ts, 0, 5)) + +=== tests/cases/compiler/index.ts === +import sayHello from "./hello"; +>sayHello : Symbol(sayHello, Decl(index.ts, 0, 6)) + +import { username } from './utils'; +>username : Symbol(username, Decl(index.ts, 1, 8)) + +sayHello(username()); +>sayHello : Symbol(sayHello, Decl(index.ts, 0, 6)) +>username : Symbol(username, Decl(index.ts, 1, 8)) + diff --git a/tests/baselines/reference/esModuleInteropImportTSLibHasImport.types b/tests/baselines/reference/esModuleInteropImportTSLibHasImport.types new file mode 100644 index 00000000000..00802b78291 --- /dev/null +++ b/tests/baselines/reference/esModuleInteropImportTSLibHasImport.types @@ -0,0 +1,41 @@ +=== tests/cases/compiler/types.d.ts === +declare module "tslib" { export const __exportStar: any; export const __importDefault: any; export const __importStar: any; } +>"tslib" : typeof "tslib" +>__exportStar : any +>__importDefault : any +>__importStar : any + +=== tests/cases/compiler/utils/username.ts === +export const username = () => 'username'; +>username : () => string +>() => 'username' : () => string +>'username' : "username" + +=== tests/cases/compiler/utils/index.ts === +export * from './username'; +No type information for this code.=== tests/cases/compiler/hello.ts === +const sayHello = (name?: string) => void (`Hello, ${name}!`); +>sayHello : (name?: string) => any +>(name?: string) => void (`Hello, ${name}!`) : (name?: string) => any +>name : string +>void (`Hello, ${name}!`) : undefined +>(`Hello, ${name}!`) : string +>`Hello, ${name}!` : string +>name : string + +export default sayHello; +>sayHello : (name?: string) => any + +=== tests/cases/compiler/index.ts === +import sayHello from "./hello"; +>sayHello : (name?: string) => any + +import { username } from './utils'; +>username : () => string + +sayHello(username()); +>sayHello(username()) : any +>sayHello : (name?: string) => any +>username() : string +>username : () => string + diff --git a/tests/cases/compiler/esModuleInteropImportTSLibHasImport.ts b/tests/cases/compiler/esModuleInteropImportTSLibHasImport.ts new file mode 100644 index 00000000000..b7f6ce748c3 --- /dev/null +++ b/tests/cases/compiler/esModuleInteropImportTSLibHasImport.ts @@ -0,0 +1,20 @@ +// @esModuleInterop: true +// @importHelpers: true +// @noEmitHelpers: true +// @target: es2017 +// @module: commonjs +// @filename: types.d.ts +declare module "tslib" { export const __exportStar: any; export const __importDefault: any; export const __importStar: any; } +// @filename: utils/username.ts +export const username = () => 'username'; +// @filename: utils/index.ts +export * from './username'; +// @filename: hello.ts +const sayHello = (name?: string) => void (`Hello, ${name}!`); + +export default sayHello; +// @filename: index.ts +import sayHello from "./hello"; +import { username } from './utils'; + +sayHello(username()); \ No newline at end of file From 866c542522656e9ca9c62a73696ea3b8d28e67f5 Mon Sep 17 00:00:00 2001 From: Dhruv Rajvanshi Date: Fri, 30 Mar 2018 00:00:18 +0530 Subject: [PATCH 55/75] Adding trailing newline to a baseline test file --- tests/baselines/reference/strictModeEnumMemberNameReserved.js | 3 ++- tests/cases/compiler/strictModeEnumMemberNameReserved.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/baselines/reference/strictModeEnumMemberNameReserved.js b/tests/baselines/reference/strictModeEnumMemberNameReserved.js index 1dd89af1686..89e1a656b7b 100644 --- a/tests/baselines/reference/strictModeEnumMemberNameReserved.js +++ b/tests/baselines/reference/strictModeEnumMemberNameReserved.js @@ -4,7 +4,8 @@ enum E { static } -const x1: E.static = E.static; +const x1: E.static = E.static; + //// [strictModeEnumMemberNameReserved.js] "use strict"; diff --git a/tests/cases/compiler/strictModeEnumMemberNameReserved.ts b/tests/cases/compiler/strictModeEnumMemberNameReserved.ts index a41985b16f8..ee9305e92a4 100644 --- a/tests/cases/compiler/strictModeEnumMemberNameReserved.ts +++ b/tests/cases/compiler/strictModeEnumMemberNameReserved.ts @@ -3,4 +3,4 @@ enum E { static } -const x1: E.static = E.static; \ No newline at end of file +const x1: E.static = E.static; From a9aca81601ee62cc6ceb53d5c9332e817a4e216d Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 11:39:30 -0700 Subject: [PATCH 56/75] Error on `for (const x in never)` (#22988) * Error on `for (const x in never)` * Update diagnostic * Provide argument to diagnostic --- src/compiler/checker.ts | 4 +- src/compiler/diagnosticMessages.json | 2 +- .../reference/for-inStatements.errors.txt | 4 +- .../for-inStatementsInvalid.errors.txt | 44 +++++++++---------- tests/baselines/reference/forIn2.errors.txt | 4 +- .../reference/forInStatement2.errors.txt | 4 +- .../reference/neverTypeErrors1.errors.txt | 6 ++- tests/baselines/reference/neverTypeErrors1.js | 2 + .../reference/neverTypeErrors1.symbols | 4 ++ .../reference/neverTypeErrors1.types | 5 +++ .../reference/neverTypeErrors2.errors.txt | 6 ++- tests/baselines/reference/neverTypeErrors2.js | 2 + .../reference/neverTypeErrors2.symbols | 4 ++ .../reference/neverTypeErrors2.types | 5 +++ .../reference/symbolType13.errors.txt | 8 ++-- .../types/never/neverTypeErrors1.ts | 1 + .../types/never/neverTypeErrors2.ts | 1 + 17 files changed, 69 insertions(+), 37 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c579fadf9a0..b59395fe87c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22590,8 +22590,8 @@ namespace 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, TypeFlags.NonPrimitive | TypeFlags.InstantiableNonPrimitive)) { - error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); + if (rightType === neverType || !isTypeAssignableToKind(rightType, TypeFlags.NonPrimitive | TypeFlags.InstantiableNonPrimitive)) { + error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index f0ce19ea1b3..5674e6dce0c 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1372,7 +1372,7 @@ "category": "Error", "code": 2406 }, - "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.": { + "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'.": { "category": "Error", "code": 2407 }, diff --git a/tests/baselines/reference/for-inStatements.errors.txt b/tests/baselines/reference/for-inStatements.errors.txt index c5ca29d2150..2ae4cdb79f0 100644 --- a/tests/baselines/reference/for-inStatements.errors.txt +++ b/tests/baselines/reference/for-inStatements.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(33,18): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(50,18): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. -tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(79,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(79,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'Color.Blue'. ==== tests/cases/conformance/statements/for-inStatements/for-inStatements.ts (3 errors) ==== @@ -88,5 +88,5 @@ tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(79,15): for (var x in Color) { } for (var x in Color.Blue) { } ~~~~~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'Color.Blue'. \ No newline at end of file diff --git a/tests/baselines/reference/for-inStatementsInvalid.errors.txt b/tests/baselines/reference/for-inStatementsInvalid.errors.txt index f98349973a3..3d7dd1c79f3 100644 --- a/tests/baselines/reference/for-inStatementsInvalid.errors.txt +++ b/tests/baselines/reference/for-inStatementsInvalid.errors.txt @@ -2,19 +2,19 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(2 tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(5,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(8,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(10,10): error TS2404: The left-hand side of a 'for...in' statement cannot use a type annotation. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(13,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(17,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(18,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(19,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(20,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(22,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(29,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(13,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'void'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(17,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(18,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(19,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(20,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(22,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(29,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(31,18): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(38,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(46,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(38,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(46,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(48,18): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(51,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(62,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(51,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(62,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. ==== tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts (17 errors) ==== @@ -40,26 +40,26 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6 function fn(): void { } for (var x in fn()) { } ~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'void'. var c : string, d:string, e; for (var x in c || d) { } ~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. for (var x in e ? c : d) { } ~~~~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. for (var x in 42 ? c : d) { } ~~~~~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. for (var x in '' ? c : d) { } ~~~~~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. for (var x in 42 ? d[x] : c[x]) { } for (var x in c[23]) { } ~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. for (var x in ((x: T) => x)) { } for (var x in function (x: string, y: number) { return x + y }) { } @@ -68,7 +68,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6 biz() : number{ for (var x in this.biz()) { } ~~~~~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. for (var x in this.biz) { } for (var x in this) { } ~ @@ -81,7 +81,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6 for (var x in this.baz) { } for (var x in this.baz()) { } ~~~~~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. return null; } @@ -91,7 +91,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6 boz() { for (var x in this.biz()) { } ~~~~~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. for (var x in this.biz) { } for (var x in this) { } ~ @@ -100,7 +100,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6 for (var x in super.biz) { } for (var x in super.biz()) { } ~~~~~~~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. return null; } } @@ -113,5 +113,5 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6 for (var x in i[42]) { } ~~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/forIn2.errors.txt b/tests/baselines/reference/forIn2.errors.txt index f6a0b34e3e6..7bf5f95e4a0 100644 --- a/tests/baselines/reference/forIn2.errors.txt +++ b/tests/baselines/reference/forIn2.errors.txt @@ -1,8 +1,8 @@ -tests/cases/compiler/forIn2.ts(1,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/compiler/forIn2.ts(1,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '1'. ==== tests/cases/compiler/forIn2.ts (1 errors) ==== for (var i in 1) { ~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '1'. } \ No newline at end of file diff --git a/tests/baselines/reference/forInStatement2.errors.txt b/tests/baselines/reference/forInStatement2.errors.txt index 575936eab5e..5ab7742707b 100644 --- a/tests/baselines/reference/forInStatement2.errors.txt +++ b/tests/baselines/reference/forInStatement2.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/forInStatement2.ts(2,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/compiler/forInStatement2.ts(2,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. ==== tests/cases/compiler/forInStatement2.ts (1 errors) ==== var expr: number; for (var a in expr) { ~~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/neverTypeErrors1.errors.txt b/tests/baselines/reference/neverTypeErrors1.errors.txt index e0746084de0..c0dd83fb1cc 100644 --- a/tests/baselines/reference/neverTypeErrors1.errors.txt +++ b/tests/baselines/reference/neverTypeErrors1.errors.txt @@ -9,9 +9,10 @@ tests/cases/conformance/types/never/neverTypeErrors1.ts(13,5): error TS2322: Typ tests/cases/conformance/types/never/neverTypeErrors1.ts(17,5): error TS2322: Type '1' is not assignable to type 'never'. tests/cases/conformance/types/never/neverTypeErrors1.ts(20,16): error TS2534: A function returning 'never' cannot have a reachable end point. tests/cases/conformance/types/never/neverTypeErrors1.ts(23,17): error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/types/never/neverTypeErrors1.ts(24,17): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'never'. -==== tests/cases/conformance/types/never/neverTypeErrors1.ts (11 errors) ==== +==== tests/cases/conformance/types/never/neverTypeErrors1.ts (12 errors) ==== function f1() { let x: never; x = 1; @@ -57,4 +58,7 @@ tests/cases/conformance/types/never/neverTypeErrors1.ts(23,17): error TS2488: Ty for (const n of f4()) {} ~~~~ !!! error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator. + for (const n in f4()) {} + ~~~~ +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'never'. \ No newline at end of file diff --git a/tests/baselines/reference/neverTypeErrors1.js b/tests/baselines/reference/neverTypeErrors1.js index f05a3ce1c61..751975019ba 100644 --- a/tests/baselines/reference/neverTypeErrors1.js +++ b/tests/baselines/reference/neverTypeErrors1.js @@ -22,6 +22,7 @@ function f4(): never { } for (const n of f4()) {} +for (const n in f4()) {} //// [neverTypeErrors1.js] @@ -46,3 +47,4 @@ function f4() { for (var _i = 0, _a = f4(); _i < _a.length; _i++) { var n = _a[_i]; } +for (var n in f4()) { } diff --git a/tests/baselines/reference/neverTypeErrors1.symbols b/tests/baselines/reference/neverTypeErrors1.symbols index f565a4bf7b5..6c545be1d61 100644 --- a/tests/baselines/reference/neverTypeErrors1.symbols +++ b/tests/baselines/reference/neverTypeErrors1.symbols @@ -48,3 +48,7 @@ for (const n of f4()) {} >n : Symbol(n, Decl(neverTypeErrors1.ts, 22, 10)) >f4 : Symbol(f4, Decl(neverTypeErrors1.ts, 17, 1)) +for (const n in f4()) {} +>n : Symbol(n, Decl(neverTypeErrors1.ts, 23, 10)) +>f4 : Symbol(f4, Decl(neverTypeErrors1.ts, 17, 1)) + diff --git a/tests/baselines/reference/neverTypeErrors1.types b/tests/baselines/reference/neverTypeErrors1.types index 89dbf92e8f5..8fab8212f66 100644 --- a/tests/baselines/reference/neverTypeErrors1.types +++ b/tests/baselines/reference/neverTypeErrors1.types @@ -62,3 +62,8 @@ for (const n of f4()) {} >f4() : never >f4 : () => never +for (const n in f4()) {} +>n : string +>f4() : never +>f4 : () => never + diff --git a/tests/baselines/reference/neverTypeErrors2.errors.txt b/tests/baselines/reference/neverTypeErrors2.errors.txt index 4f5845917c5..b81323cbfbc 100644 --- a/tests/baselines/reference/neverTypeErrors2.errors.txt +++ b/tests/baselines/reference/neverTypeErrors2.errors.txt @@ -9,9 +9,10 @@ tests/cases/conformance/types/never/neverTypeErrors2.ts(13,5): error TS2322: Typ tests/cases/conformance/types/never/neverTypeErrors2.ts(17,5): error TS2322: Type '1' is not assignable to type 'never'. tests/cases/conformance/types/never/neverTypeErrors2.ts(20,16): error TS2534: A function returning 'never' cannot have a reachable end point. tests/cases/conformance/types/never/neverTypeErrors2.ts(23,17): error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator. +tests/cases/conformance/types/never/neverTypeErrors2.ts(24,17): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'never'. -==== tests/cases/conformance/types/never/neverTypeErrors2.ts (11 errors) ==== +==== tests/cases/conformance/types/never/neverTypeErrors2.ts (12 errors) ==== function f1() { let x: never; x = 1; @@ -57,4 +58,7 @@ tests/cases/conformance/types/never/neverTypeErrors2.ts(23,17): error TS2488: Ty for (const n of f4()) {} ~~~~ !!! error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator. + for (const n in f4()) {} + ~~~~ +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'never'. \ No newline at end of file diff --git a/tests/baselines/reference/neverTypeErrors2.js b/tests/baselines/reference/neverTypeErrors2.js index dfe9f32b627..17a8a9eba98 100644 --- a/tests/baselines/reference/neverTypeErrors2.js +++ b/tests/baselines/reference/neverTypeErrors2.js @@ -22,6 +22,7 @@ function f4(): never { } for (const n of f4()) {} +for (const n in f4()) {} //// [neverTypeErrors2.js] @@ -46,3 +47,4 @@ function f4() { for (var _i = 0, _a = f4(); _i < _a.length; _i++) { var n = _a[_i]; } +for (var n in f4()) { } diff --git a/tests/baselines/reference/neverTypeErrors2.symbols b/tests/baselines/reference/neverTypeErrors2.symbols index ec6b0086ee7..3a450b60efd 100644 --- a/tests/baselines/reference/neverTypeErrors2.symbols +++ b/tests/baselines/reference/neverTypeErrors2.symbols @@ -48,3 +48,7 @@ for (const n of f4()) {} >n : Symbol(n, Decl(neverTypeErrors2.ts, 22, 10)) >f4 : Symbol(f4, Decl(neverTypeErrors2.ts, 17, 1)) +for (const n in f4()) {} +>n : Symbol(n, Decl(neverTypeErrors2.ts, 23, 10)) +>f4 : Symbol(f4, Decl(neverTypeErrors2.ts, 17, 1)) + diff --git a/tests/baselines/reference/neverTypeErrors2.types b/tests/baselines/reference/neverTypeErrors2.types index 510f32506bb..5bfae1f5201 100644 --- a/tests/baselines/reference/neverTypeErrors2.types +++ b/tests/baselines/reference/neverTypeErrors2.types @@ -62,3 +62,8 @@ for (const n of f4()) {} >f4() : never >f4 : () => never +for (const n in f4()) {} +>n : string +>f4() : never +>f4 : () => never + diff --git a/tests/baselines/reference/symbolType13.errors.txt b/tests/baselines/reference/symbolType13.errors.txt index 68981d0072b..9f1688fe935 100644 --- a/tests/baselines/reference/symbolType13.errors.txt +++ b/tests/baselines/reference/symbolType13.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/Symbols/symbolType13.ts(4,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. -tests/cases/conformance/es6/Symbols/symbolType13.ts(5,11): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/conformance/es6/Symbols/symbolType13.ts(6,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/conformance/es6/Symbols/symbolType13.ts(5,11): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'symbol'. +tests/cases/conformance/es6/Symbols/symbolType13.ts(6,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'symbol'. ==== tests/cases/conformance/es6/Symbols/symbolType13.ts (3 errors) ==== @@ -12,7 +12,7 @@ tests/cases/conformance/es6/Symbols/symbolType13.ts(6,15): error TS2407: The rig !!! error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. for (x in s) { } ~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'symbol'. for (var y in s) { } ~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. \ No newline at end of file +!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'symbol'. \ No newline at end of file diff --git a/tests/cases/conformance/types/never/neverTypeErrors1.ts b/tests/cases/conformance/types/never/neverTypeErrors1.ts index 20c9daf9e3b..44435d5203d 100644 --- a/tests/cases/conformance/types/never/neverTypeErrors1.ts +++ b/tests/cases/conformance/types/never/neverTypeErrors1.ts @@ -21,3 +21,4 @@ function f4(): never { } for (const n of f4()) {} +for (const n in f4()) {} diff --git a/tests/cases/conformance/types/never/neverTypeErrors2.ts b/tests/cases/conformance/types/never/neverTypeErrors2.ts index 66f12d7d322..c9c37dcb15d 100644 --- a/tests/cases/conformance/types/never/neverTypeErrors2.ts +++ b/tests/cases/conformance/types/never/neverTypeErrors2.ts @@ -23,3 +23,4 @@ function f4(): never { } for (const n of f4()) {} +for (const n in f4()) {} From e4a73f39817be98a30b9852f5248cbbbf27abd59 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 12:28:37 -0700 Subject: [PATCH 57/75] Assert argument is provided to diagnostic (#22992) --- src/compiler/core.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 6df0a8d4997..b08d897b35c 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1570,10 +1570,10 @@ namespace ts { } } - export function formatStringFromArgs(text: string, args: { [index: number]: string; }, baseIndex?: number): string { + export function formatStringFromArgs(text: string, args: ArrayLike, baseIndex?: number): string { baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, (_match, index?) => args[+index + baseIndex]); + return text.replace(/{(\d+)}/g, (_match, index?: string) => Debug.assertDefined(args[+index + baseIndex])); } export let localizedDiagnosticMessages: MapLike; From 51d44b609758b33e07e87e16eca2062bfeb9c20d Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 12:36:42 -0700 Subject: [PATCH 58/75] Move JSX props support check and make syntactic (#22970) * Move JSX props support check and make syntactic * Make parameter required --- src/compiler/checker.ts | 48 +++++++++---------- .../tsxElementResolution12.errors.txt | 8 +++- .../tsxNoTypeAnnotatedSFC.errors.txt | 14 ++++++ .../reference/tsxNoTypeAnnotatedSFC.js | 19 ++++++++ .../reference/tsxNoTypeAnnotatedSFC.symbols | 16 +++++++ .../reference/tsxNoTypeAnnotatedSFC.types | 20 ++++++++ ...tsxSpreadAttributesResolution17.errors.txt | 25 ++++++++++ .../cases/compiler/tsxNoTypeAnnotatedSFC.tsx | 9 ++++ 8 files changed, 132 insertions(+), 27 deletions(-) create mode 100644 tests/baselines/reference/tsxNoTypeAnnotatedSFC.errors.txt create mode 100644 tests/baselines/reference/tsxNoTypeAnnotatedSFC.js create mode 100644 tests/baselines/reference/tsxNoTypeAnnotatedSFC.symbols create mode 100644 tests/baselines/reference/tsxNoTypeAnnotatedSFC.types create mode 100644 tests/baselines/reference/tsxSpreadAttributesResolution17.errors.txt create mode 100644 tests/cases/compiler/tsxNoTypeAnnotatedSFC.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b59395fe87c..dbbee348cd9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14767,7 +14767,7 @@ namespace ts { return propsType; } - function getJsxPropsTypeFromClassType(hostClassType: Type, isJs: boolean, context: Node) { + function getJsxPropsTypeFromClassType(hostClassType: Type, isJs: boolean, context: JsxOpeningLikeElement, reportErrors: boolean) { if (isTypeAny(hostClassType)) { return hostClassType; } @@ -14786,6 +14786,9 @@ namespace ts { if (!attributesType) { // There is no property named 'props' on this instance type + if (reportErrors && !!length(context.attributes.properties)) { + error(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(propsName)); + } return emptyObjectType; } else if (isTypeAny(attributesType)) { @@ -14816,10 +14819,10 @@ namespace ts { } } - function getJsxPropsTypeFromConstructSignature(sig: Signature, isJs: boolean, context: Node) { + function getJsxPropsTypeFromConstructSignature(sig: Signature, isJs: boolean, context: JsxOpeningLikeElement) { const hostClassType = getReturnTypeOfSignature(sig); if (hostClassType) { - return getJsxPropsTypeFromClassType(hostClassType, isJs, context); + return getJsxPropsTypeFromClassType(hostClassType, isJs, context, /*reportErrors*/ false); } return getJsxPropsTypeFromCallSignature(sig, context); } @@ -15857,7 +15860,7 @@ namespace ts { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - return getJsxPropsTypeFromClassType(elemInstanceType, isInJavaScriptFile(openingLikeElement), openingLikeElement); + return getJsxPropsTypeFromClassType(elemInstanceType, isInJavaScriptFile(openingLikeElement), openingLikeElement, /*reportErrors*/ true); } /** @@ -16062,28 +16065,21 @@ namespace ts { // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". const sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); - // 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) || getPropertiesOfType(sourceAttributesType).length > 0)) { - error(openingLikeElement, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement)))); - } - else { - // 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 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)) { - continue; - } - const attrName = attribute.name; - 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; - } + // 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 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)) { + continue; + } + const attrName = attribute.name; + 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; } } } diff --git a/tests/baselines/reference/tsxElementResolution12.errors.txt b/tests/baselines/reference/tsxElementResolution12.errors.txt index ac9758acfb6..63b39aea1f9 100644 --- a/tests/baselines/reference/tsxElementResolution12.errors.txt +++ b/tests/baselines/reference/tsxElementResolution12.errors.txt @@ -1,11 +1,13 @@ tests/cases/conformance/jsx/file.tsx(23,1): error TS2607: JSX element class does not support attributes because it does not have a 'pr' property. +tests/cases/conformance/jsx/file.tsx(23,7): error TS2339: Property 'x' does not exist on type '{}'. tests/cases/conformance/jsx/file.tsx(25,1): error TS2607: JSX element class does not support attributes because it does not have a 'pr' property. +tests/cases/conformance/jsx/file.tsx(26,1): error TS2607: JSX element class does not support attributes because it does not have a 'pr' property. tests/cases/conformance/jsx/file.tsx(33,7): error TS2322: Type '{ x: string; }' is not assignable to type '{ x: number; }'. Types of property 'x' are incompatible. Type 'string' is not assignable to type 'number'. -==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (5 errors) ==== declare module JSX { interface Element { } interface ElementAttributesProperty { pr: any; } @@ -31,11 +33,15 @@ tests/cases/conformance/jsx/file.tsx(33,7): error TS2322: Type '{ x: string; }' ; // Error ~~~~~~~~~~~~~~~ !!! error TS2607: JSX element class does not support attributes because it does not have a 'pr' property. + ~~~~~~ +!!! error TS2339: Property 'x' does not exist on type '{}'. var attributes: any; ; // Error ~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2607: JSX element class does not support attributes because it does not have a 'pr' property. ; // OK + ~~~~~~~~~~~~~~~~ +!!! error TS2607: JSX element class does not support attributes because it does not have a 'pr' property. interface Obj4type { new(n: string): { x: number; pr: { x: number; } }; diff --git a/tests/baselines/reference/tsxNoTypeAnnotatedSFC.errors.txt b/tests/baselines/reference/tsxNoTypeAnnotatedSFC.errors.txt new file mode 100644 index 00000000000..6415843f8a0 --- /dev/null +++ b/tests/baselines/reference/tsxNoTypeAnnotatedSFC.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/tsxNoTypeAnnotatedSFC.tsx(2,24): error TS2307: Cannot find module 'react'. + + +==== tests/cases/compiler/tsxNoTypeAnnotatedSFC.tsx (1 errors) ==== + // not _actually_ making react available in this test to regression test #22948 + import * as React from 'react'; + ~~~~~~~ +!!! error TS2307: Cannot find module 'react'. + + const Test123 = () =>
; + + function testComponent(props) { + return ; + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxNoTypeAnnotatedSFC.js b/tests/baselines/reference/tsxNoTypeAnnotatedSFC.js new file mode 100644 index 00000000000..6834f9e7880 --- /dev/null +++ b/tests/baselines/reference/tsxNoTypeAnnotatedSFC.js @@ -0,0 +1,19 @@ +//// [tsxNoTypeAnnotatedSFC.tsx] +// not _actually_ making react available in this test to regression test #22948 +import * as React from 'react'; + +const Test123 = () =>
; + +function testComponent(props) { + return ; +} + +//// [tsxNoTypeAnnotatedSFC.jsx] +"use strict"; +exports.__esModule = true; +// not _actually_ making react available in this test to regression test #22948 +var React = require("react"); +var Test123 = function () { return
; }; +function testComponent(props) { + return ; +} diff --git a/tests/baselines/reference/tsxNoTypeAnnotatedSFC.symbols b/tests/baselines/reference/tsxNoTypeAnnotatedSFC.symbols new file mode 100644 index 00000000000..5b626acf5ea --- /dev/null +++ b/tests/baselines/reference/tsxNoTypeAnnotatedSFC.symbols @@ -0,0 +1,16 @@ +=== tests/cases/compiler/tsxNoTypeAnnotatedSFC.tsx === +// not _actually_ making react available in this test to regression test #22948 +import * as React from 'react'; +>React : Symbol(React, Decl(tsxNoTypeAnnotatedSFC.tsx, 1, 6)) + +const Test123 = () =>
; +>Test123 : Symbol(Test123, Decl(tsxNoTypeAnnotatedSFC.tsx, 3, 5)) + +function testComponent(props) { +>testComponent : Symbol(testComponent, Decl(tsxNoTypeAnnotatedSFC.tsx, 3, 29)) +>props : Symbol(props, Decl(tsxNoTypeAnnotatedSFC.tsx, 5, 23)) + + return ; +>Test123 : Symbol(Test123, Decl(tsxNoTypeAnnotatedSFC.tsx, 3, 5)) +>props : Symbol(props, Decl(tsxNoTypeAnnotatedSFC.tsx, 5, 23)) +} diff --git a/tests/baselines/reference/tsxNoTypeAnnotatedSFC.types b/tests/baselines/reference/tsxNoTypeAnnotatedSFC.types new file mode 100644 index 00000000000..120029734d3 --- /dev/null +++ b/tests/baselines/reference/tsxNoTypeAnnotatedSFC.types @@ -0,0 +1,20 @@ +=== tests/cases/compiler/tsxNoTypeAnnotatedSFC.tsx === +// not _actually_ making react available in this test to regression test #22948 +import * as React from 'react'; +>React : any + +const Test123 = () =>
; +>Test123 : () => any +>() =>
: () => any +>
: any +>div : any + +function testComponent(props) { +>testComponent : (props: any) => any +>props : any + + return ; +> : any +>Test123 : () => any +>props : any +} diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution17.errors.txt b/tests/baselines/reference/tsxSpreadAttributesResolution17.errors.txt new file mode 100644 index 00000000000..b57d6e3586b --- /dev/null +++ b/tests/baselines/reference/tsxSpreadAttributesResolution17.errors.txt @@ -0,0 +1,25 @@ +tests/cases/conformance/jsx/file.tsx(18,21): error TS2607: JSX element class does not support attributes because it does not have a 'props' property. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + declare global { + namespace JSX { + interface Element {} + interface ElementAttributesProperty { props: {} } + } + } + declare var React: any; + + export class Empty extends React.Component<{}, {}> { + render() { + return
Hello
; + } + } + + declare const obj: { a: number | undefined } | undefined; + + // OK + let unionedSpread = ; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2607: JSX element class does not support attributes because it does not have a 'props' property. + \ No newline at end of file diff --git a/tests/cases/compiler/tsxNoTypeAnnotatedSFC.tsx b/tests/cases/compiler/tsxNoTypeAnnotatedSFC.tsx new file mode 100644 index 00000000000..ccaebb18f52 --- /dev/null +++ b/tests/cases/compiler/tsxNoTypeAnnotatedSFC.tsx @@ -0,0 +1,9 @@ +// @jsx: preserve +// not _actually_ making react available in this test to regression test #22948 +import * as React from 'react'; + +const Test123 = () =>
; + +function testComponent(props) { + return ; +} \ No newline at end of file From 3365272f6900a833abee91b427379736fe935d83 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 12:46:31 -0700 Subject: [PATCH 59/75] Dont follow aliases when looking for default exported symbol (#22995) --- src/compiler/checker.ts | 4 +- .../reference/systemDefaultImportCallable.js | 33 ++++++++++++++ .../systemDefaultImportCallable.symbols | 39 ++++++++++++++++ .../systemDefaultImportCallable.types | 45 +++++++++++++++++++ .../compiler/systemDefaultImportCallable.ts | 15 +++++++ 5 files changed, 134 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/systemDefaultImportCallable.js create mode 100644 tests/baselines/reference/systemDefaultImportCallable.symbols create mode 100644 tests/baselines/reference/systemDefaultImportCallable.types create mode 100644 tests/cases/compiler/systemDefaultImportCallable.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dbbee348cd9..43425f0d42b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1741,8 +1741,8 @@ namespace ts { // Declaration files (and ambient modules) if (!file || file.isDeclarationFile) { // Definitely cannot have a synthetic default if they have a syntactic default member specified - const defaultExportSymbol = resolveExportByName(moduleSymbol, InternalSymbolName.Default, dontResolveAlias); - if (defaultExportSymbol && defaultExportSymbol.valueDeclaration && isSyntacticDefault(defaultExportSymbol.valueDeclaration)) { + const defaultExportSymbol = resolveExportByName(moduleSymbol, InternalSymbolName.Default, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration + if (defaultExportSymbol && some(defaultExportSymbol.declarations, isSyntacticDefault)) { 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 diff --git a/tests/baselines/reference/systemDefaultImportCallable.js b/tests/baselines/reference/systemDefaultImportCallable.js new file mode 100644 index 00000000000..4fc6f2158df --- /dev/null +++ b/tests/baselines/reference/systemDefaultImportCallable.js @@ -0,0 +1,33 @@ +//// [tests/cases/compiler/systemDefaultImportCallable.ts] //// + +//// [core-js.d.ts] +declare module core { + var String: { + repeat(text: string, count: number): string; + }; +} +declare module "core-js/fn/string/repeat" { + var repeat: typeof core.String.repeat; + export default repeat; +} +//// [greeter.ts] +import repeat from "core-js/fn/string/repeat"; + +const _: string = repeat(new Date().toUTCString() + " ", 2); + +//// [greeter.js] +System.register(["core-js/fn/string/repeat"], function (exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; + var repeat_1, _; + return { + setters: [ + function (repeat_1_1) { + repeat_1 = repeat_1_1; + } + ], + execute: function () { + _ = repeat_1["default"](new Date().toUTCString() + " ", 2); + } + }; +}); diff --git a/tests/baselines/reference/systemDefaultImportCallable.symbols b/tests/baselines/reference/systemDefaultImportCallable.symbols new file mode 100644 index 00000000000..f9935272c55 --- /dev/null +++ b/tests/baselines/reference/systemDefaultImportCallable.symbols @@ -0,0 +1,39 @@ +=== tests/cases/compiler/core-js.d.ts === +declare module core { +>core : Symbol(core, Decl(core-js.d.ts, 0, 0)) + + var String: { +>String : Symbol(String, Decl(core-js.d.ts, 1, 7)) + + repeat(text: string, count: number): string; +>repeat : Symbol(repeat, Decl(core-js.d.ts, 1, 17)) +>text : Symbol(text, Decl(core-js.d.ts, 2, 15)) +>count : Symbol(count, Decl(core-js.d.ts, 2, 28)) + + }; +} +declare module "core-js/fn/string/repeat" { +>"core-js/fn/string/repeat" : Symbol("core-js/fn/string/repeat", Decl(core-js.d.ts, 4, 1)) + + var repeat: typeof core.String.repeat; +>repeat : Symbol(repeat, Decl(core-js.d.ts, 6, 7)) +>core.String.repeat : Symbol(repeat, Decl(core-js.d.ts, 1, 17)) +>core.String : Symbol(core.String, Decl(core-js.d.ts, 1, 7)) +>core : Symbol(core, Decl(core-js.d.ts, 0, 0)) +>String : Symbol(core.String, Decl(core-js.d.ts, 1, 7)) +>repeat : Symbol(repeat, Decl(core-js.d.ts, 1, 17)) + + export default repeat; +>repeat : Symbol(repeat, Decl(core-js.d.ts, 6, 7)) +} +=== tests/cases/compiler/greeter.ts === +import repeat from "core-js/fn/string/repeat"; +>repeat : Symbol(repeat, Decl(greeter.ts, 0, 6)) + +const _: string = repeat(new Date().toUTCString() + " ", 2); +>_ : Symbol(_, Decl(greeter.ts, 2, 5)) +>repeat : Symbol(repeat, Decl(greeter.ts, 0, 6)) +>new Date().toUTCString : Symbol(Date.toUTCString, Decl(lib.d.ts, --, --)) +>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>toUTCString : Symbol(Date.toUTCString, Decl(lib.d.ts, --, --)) + diff --git a/tests/baselines/reference/systemDefaultImportCallable.types b/tests/baselines/reference/systemDefaultImportCallable.types new file mode 100644 index 00000000000..878a1f879d1 --- /dev/null +++ b/tests/baselines/reference/systemDefaultImportCallable.types @@ -0,0 +1,45 @@ +=== tests/cases/compiler/core-js.d.ts === +declare module core { +>core : typeof core + + var String: { +>String : { repeat(text: string, count: number): string; } + + repeat(text: string, count: number): string; +>repeat : (text: string, count: number) => string +>text : string +>count : number + + }; +} +declare module "core-js/fn/string/repeat" { +>"core-js/fn/string/repeat" : typeof "core-js/fn/string/repeat" + + var repeat: typeof core.String.repeat; +>repeat : (text: string, count: number) => string +>core.String.repeat : (text: string, count: number) => string +>core.String : { repeat(text: string, count: number): string; } +>core : typeof core +>String : { repeat(text: string, count: number): string; } +>repeat : (text: string, count: number) => string + + export default repeat; +>repeat : (text: string, count: number) => string +} +=== tests/cases/compiler/greeter.ts === +import repeat from "core-js/fn/string/repeat"; +>repeat : (text: string, count: number) => string + +const _: string = repeat(new Date().toUTCString() + " ", 2); +>_ : string +>repeat(new Date().toUTCString() + " ", 2) : string +>repeat : (text: string, count: number) => string +>new Date().toUTCString() + " " : string +>new Date().toUTCString() : string +>new Date().toUTCString : () => string +>new Date() : Date +>Date : DateConstructor +>toUTCString : () => string +>" " : " " +>2 : 2 + diff --git a/tests/cases/compiler/systemDefaultImportCallable.ts b/tests/cases/compiler/systemDefaultImportCallable.ts new file mode 100644 index 00000000000..a0ea02823c3 --- /dev/null +++ b/tests/cases/compiler/systemDefaultImportCallable.ts @@ -0,0 +1,15 @@ +// @module: system +// @filename: core-js.d.ts +declare module core { + var String: { + repeat(text: string, count: number): string; + }; +} +declare module "core-js/fn/string/repeat" { + var repeat: typeof core.String.repeat; + export default repeat; +} +// @filename: greeter.ts +import repeat from "core-js/fn/string/repeat"; + +const _: string = repeat(new Date().toUTCString() + " ", 2); \ No newline at end of file From 51a4fe6d20aec536294ac55c453b657389ac6d17 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 12:50:29 -0700 Subject: [PATCH 60/75] Handle ts-only declaration export aliases in system transformer (#22919) * handle ts declarations export alises in system transformer * Retain end of declaration marker --- src/compiler/transformers/module/system.ts | 6 ++++ .../reference/systemNamespaceAliasEmit.js | 34 +++++++++++++++++++ .../systemNamespaceAliasEmit.symbols | 26 ++++++++++++++ .../reference/systemNamespaceAliasEmit.types | 27 +++++++++++++++ .../compiler/systemNamespaceAliasEmit.ts | 11 ++++++ 5 files changed, 104 insertions(+) create mode 100644 tests/baselines/reference/systemNamespaceAliasEmit.js create mode 100644 tests/baselines/reference/systemNamespaceAliasEmit.symbols create mode 100644 tests/baselines/reference/systemNamespaceAliasEmit.types create mode 100644 tests/cases/compiler/systemNamespaceAliasEmit.ts diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index d4bae723052..ca55cb3a9d1 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -913,6 +913,12 @@ namespace ts { delete deferredExports[id]; return append(statements, node); } + else { + const original = getOriginalNode(node); + if (isModuleOrEnumDeclaration(original)) { + return append(appendExportsOfDeclaration(statements, original), node); + } + } return node; } diff --git a/tests/baselines/reference/systemNamespaceAliasEmit.js b/tests/baselines/reference/systemNamespaceAliasEmit.js new file mode 100644 index 00000000000..923b7db875a --- /dev/null +++ b/tests/baselines/reference/systemNamespaceAliasEmit.js @@ -0,0 +1,34 @@ +//// [systemNamespaceAliasEmit.ts] +namespace ns { + const value = 1; +} + +enum AnEnum { + ONE, + TWO +} + +export {ns, AnEnum, ns as FooBar, AnEnum as BarEnum}; + +//// [systemNamespaceAliasEmit.js] +System.register([], function (exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; + var ns, AnEnum; + return { + setters: [], + execute: function () { + (function (ns) { + var value = 1; + })(ns || (ns = {})); + exports_1("ns", ns); + exports_1("FooBar", ns); + (function (AnEnum) { + AnEnum[AnEnum["ONE"] = 0] = "ONE"; + AnEnum[AnEnum["TWO"] = 1] = "TWO"; + })(AnEnum || (AnEnum = {})); + exports_1("AnEnum", AnEnum); + exports_1("BarEnum", AnEnum); + } + }; +}); diff --git a/tests/baselines/reference/systemNamespaceAliasEmit.symbols b/tests/baselines/reference/systemNamespaceAliasEmit.symbols new file mode 100644 index 00000000000..89ac66a624d --- /dev/null +++ b/tests/baselines/reference/systemNamespaceAliasEmit.symbols @@ -0,0 +1,26 @@ +=== tests/cases/compiler/systemNamespaceAliasEmit.ts === +namespace ns { +>ns : Symbol(ns, Decl(systemNamespaceAliasEmit.ts, 0, 0)) + + const value = 1; +>value : Symbol(value, Decl(systemNamespaceAliasEmit.ts, 1, 9)) +} + +enum AnEnum { +>AnEnum : Symbol(AnEnum, Decl(systemNamespaceAliasEmit.ts, 2, 1)) + + ONE, +>ONE : Symbol(BarEnum.ONE, Decl(systemNamespaceAliasEmit.ts, 4, 13)) + + TWO +>TWO : Symbol(BarEnum.TWO, Decl(systemNamespaceAliasEmit.ts, 5, 8)) +} + +export {ns, AnEnum, ns as FooBar, AnEnum as BarEnum}; +>ns : Symbol(ns, Decl(systemNamespaceAliasEmit.ts, 9, 8)) +>AnEnum : Symbol(AnEnum, Decl(systemNamespaceAliasEmit.ts, 9, 11)) +>ns : Symbol(FooBar, Decl(systemNamespaceAliasEmit.ts, 9, 19)) +>FooBar : Symbol(FooBar, Decl(systemNamespaceAliasEmit.ts, 9, 19)) +>AnEnum : Symbol(BarEnum, Decl(systemNamespaceAliasEmit.ts, 9, 33)) +>BarEnum : Symbol(BarEnum, Decl(systemNamespaceAliasEmit.ts, 9, 33)) + diff --git a/tests/baselines/reference/systemNamespaceAliasEmit.types b/tests/baselines/reference/systemNamespaceAliasEmit.types new file mode 100644 index 00000000000..ba82550b050 --- /dev/null +++ b/tests/baselines/reference/systemNamespaceAliasEmit.types @@ -0,0 +1,27 @@ +=== tests/cases/compiler/systemNamespaceAliasEmit.ts === +namespace ns { +>ns : typeof ns + + const value = 1; +>value : 1 +>1 : 1 +} + +enum AnEnum { +>AnEnum : AnEnum + + ONE, +>ONE : AnEnum.ONE + + TWO +>TWO : AnEnum.TWO +} + +export {ns, AnEnum, ns as FooBar, AnEnum as BarEnum}; +>ns : typeof ns +>AnEnum : typeof AnEnum +>ns : typeof ns +>FooBar : typeof ns +>AnEnum : typeof AnEnum +>BarEnum : typeof AnEnum + diff --git a/tests/cases/compiler/systemNamespaceAliasEmit.ts b/tests/cases/compiler/systemNamespaceAliasEmit.ts new file mode 100644 index 00000000000..3672c557e24 --- /dev/null +++ b/tests/cases/compiler/systemNamespaceAliasEmit.ts @@ -0,0 +1,11 @@ +// @module: system +namespace ns { + const value = 1; +} + +enum AnEnum { + ONE, + TWO +} + +export {ns, AnEnum, ns as FooBar, AnEnum as BarEnum}; \ No newline at end of file From d5a7dc1053430179212921645ecaae193041dbe6 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 12:54:17 -0700 Subject: [PATCH 61/75] fixAddMissingMember: Remove special-casing for 'this' (#22987) * fixAddMissingMember: Remove special-casing for 'this' * Update type of 'call' --- src/services/codefixes/fixAddMissingMember.ts | 47 +++++-------------- src/services/completions.ts | 11 ++--- src/services/utilities.ts | 4 ++ 3 files changed, 21 insertions(+), 41 deletions(-) diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index d8df415a4de..9a3b4854351 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -46,7 +46,7 @@ namespace ts.codefix { }, }); - interface Info { token: Identifier; classDeclaration: ClassLikeDeclaration; makeStatic: boolean; classDeclarationSourceFile: SourceFile; inJs: boolean; call: CallExpression; } + interface Info { token: Identifier; classDeclaration: ClassLikeDeclaration; makeStatic: boolean; classDeclarationSourceFile: SourceFile; inJs: boolean; call: CallExpression | undefined; } function getInfo(tokenSourceFile: SourceFile, tokenPos: number, checker: TypeChecker): Info | undefined { // The identifier of the missing property. eg: // this.missing = 1; @@ -56,45 +56,22 @@ namespace ts.codefix { return undefined; } - const classAndMakeStatic = getClassAndMakeStatic(token, checker); - if (!classAndMakeStatic) { - return undefined; - } - const { classDeclaration, makeStatic } = classAndMakeStatic; + const { parent } = token; + if (!isPropertyAccessExpression(parent)) return undefined; + + const leftExpressionType = skipConstraint(checker.getTypeAtLocation(parent.expression)); + const { symbol } = leftExpressionType; + const classDeclaration = symbol && symbol.declarations && find(symbol.declarations, isClassLike); + if (!classDeclaration) return undefined; + + const makeStatic = (leftExpressionType as TypeReference).target !== checker.getDeclaredTypeOfSymbol(symbol); const classDeclarationSourceFile = classDeclaration.getSourceFile(); - const inJs = isInJavaScriptFile(classDeclarationSourceFile); - const call = tryCast(token.parent.parent, isCallExpression); + const inJs = isSourceFileJavaScript(classDeclarationSourceFile); + const call = tryCast(parent.parent, isCallExpression); return { token, classDeclaration, makeStatic, classDeclarationSourceFile, inJs, call }; } - function getClassAndMakeStatic(token: Node, checker: TypeChecker): { readonly classDeclaration: ClassLikeDeclaration, readonly makeStatic: boolean } | undefined { - const { parent } = token; - if (!isPropertyAccessExpression(parent)) { - return undefined; - } - - if (parent.expression.kind === SyntaxKind.ThisKeyword) { - const containingClassMemberDeclaration = getThisContainer(token, /*includeArrowFunctions*/ false); - if (!isClassElement(containingClassMemberDeclaration)) { - return undefined; - } - const classDeclaration = containingClassMemberDeclaration.parent; - // Property accesses on `this` in a static method are accesses of a static member. - return isClassLike(classDeclaration) ? { classDeclaration, makeStatic: hasModifier(containingClassMemberDeclaration, ModifierFlags.Static) } : undefined; - } - else { - const leftExpressionType = checker.getTypeAtLocation(parent.expression); - const { symbol } = leftExpressionType; - if (!(symbol && 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) }; - } - } - 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)); return changes.length === 0 ? undefined diff --git a/src/services/completions.ts b/src/services/completions.ts index 4284de589bc..a83ca166956 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -462,13 +462,12 @@ namespace ts.Completions { return type && { kind: StringLiteralCompletionKind.Properties, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; } - function getStringLiteralTypes(type: Type, typeChecker: TypeChecker, uniques = createMap()): ReadonlyArray { - if (type && type.flags & TypeFlags.TypeParameter) { - type = type.getConstraint(); - } - return type && type.flags & TypeFlags.Union + function getStringLiteralTypes(type: Type | undefined, typeChecker: TypeChecker, uniques = createMap()): ReadonlyArray | undefined { + if (!type) return emptyArray; + type = skipConstraint(type); + return type.flags & TypeFlags.Union ? flatMap((type).types, t => getStringLiteralTypes(t, typeChecker, uniques)) - : type && type.flags & TypeFlags.StringLiteral && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, (type as StringLiteralType).value) + : type.flags & TypeFlags.StringLiteral && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, (type as StringLiteralType).value) ? [type as StringLiteralType] : emptyArray; } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index bd32b1a9a4f..0ee06139ea1 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1216,6 +1216,10 @@ namespace ts { } return result; } + + export function skipConstraint(type: Type): Type { + return type.flags & TypeFlags.TypeParameter ? type.getConstraint() : type; + } } // Display-part writer helpers From 9d713b6db6fd89674a1cdc7274badc2ff4bfabdb Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 13:12:23 -0700 Subject: [PATCH 62/75] Error on rest parameter with trailing comma (#22262) * Error on rest parameter with trailing comma * Error on binding patterns and improve error location --- src/compiler/checker.ts | 12 ++++--- src/compiler/diagnosticMessages.json | 4 +++ ...trailingCommasInBindingPatterns.errors.txt | 21 ++++++++++++ .../trailingCommasInBindingPatterns.js | 23 +++++++++++++ .../trailingCommasInBindingPatterns.symbols | 17 ++++++++++ .../trailingCommasInBindingPatterns.types | 28 +++++++++++++++ ...nFunctionParametersAndArguments.errors.txt | 34 +++++++++++++++++++ .../unusedLocalsAndObjectSpread2.errors.txt | 10 +++--- .../reference/unusedLocalsAndObjectSpread2.js | 6 ++-- .../unusedLocalsAndObjectSpread2.symbols | 6 ++-- .../unusedLocalsAndObjectSpread2.types | 6 ++-- .../compiler/unusedLocalsAndObjectSpread2.ts | 6 ++-- .../es7/trailingCommasInBindingPatterns.ts | 5 +++ 13 files changed, 156 insertions(+), 22 deletions(-) create mode 100644 tests/baselines/reference/trailingCommasInBindingPatterns.errors.txt create mode 100644 tests/baselines/reference/trailingCommasInBindingPatterns.js create mode 100644 tests/baselines/reference/trailingCommasInBindingPatterns.symbols create mode 100644 tests/baselines/reference/trailingCommasInBindingPatterns.types create mode 100644 tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.errors.txt create mode 100644 tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 43425f0d42b..0ccaccb546b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19164,6 +19164,7 @@ namespace ts { function checkObjectLiteralAssignment(node: ObjectLiteralExpression, sourceType: Type): Type { const properties = node.properties; + checkGrammarForDisallowedTrailingComma(properties, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } @@ -19222,6 +19223,8 @@ namespace ts { } function checkArrayLiteralAssignment(node: ArrayLiteralExpression, sourceType: Type, checkMode?: CheckMode): Type { + const elements = node.elements; + checkGrammarForDisallowedTrailingComma(elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); if (languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Read); } @@ -19230,7 +19233,6 @@ namespace ts { // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). const elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - const elements = node.elements; for (let i = 0; i < elements.length; i++) { checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); } @@ -26500,11 +26502,9 @@ namespace ts { return grammarErrorOnNode(asyncModifier, Diagnostics._0_modifier_cannot_be_used_here, "async"); } - function checkGrammarForDisallowedTrailingComma(list: NodeArray): boolean { + function checkGrammarForDisallowedTrailingComma(list: NodeArray, diag = Diagnostics.Trailing_comma_not_allowed): boolean { if (list && list.hasTrailingComma) { - const start = list.end - ",".length; - const end = list.end; - return grammarErrorAtPos(list[0], start, end - start, Diagnostics.Trailing_comma_not_allowed); + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); } } @@ -26526,6 +26526,7 @@ namespace ts { if (i !== (parameterCount - 1)) { return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); } + checkGrammarForDisallowedTrailingComma(parameters, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); if (isBindingPattern(parameter.name)) { return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); @@ -27140,6 +27141,7 @@ namespace ts { if (node !== last(elements)) { return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } + checkGrammarForDisallowedTrailingComma(elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); if (node.name.kind === SyntaxKind.ArrayBindingPattern || node.name.kind === SyntaxKind.ObjectBindingPattern) { return grammarErrorOnNode(node.name, Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 5674e6dce0c..2e3377b08eb 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -27,6 +27,10 @@ "category": "Error", "code": 1012 }, + "A rest parameter or binding pattern may not have a trailing comma.": { + "category": "Error", + "code": 1013 + }, "A rest parameter must be last in a parameter list.": { "category": "Error", "code": 1014 diff --git a/tests/baselines/reference/trailingCommasInBindingPatterns.errors.txt b/tests/baselines/reference/trailingCommasInBindingPatterns.errors.txt new file mode 100644 index 00000000000..e337e1aefac --- /dev/null +++ b/tests/baselines/reference/trailingCommasInBindingPatterns.errors.txt @@ -0,0 +1,21 @@ +tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts(1,12): error TS1013: A rest parameter or binding pattern may not have a trailing comma. +tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts(2,12): error TS1013: A rest parameter or binding pattern may not have a trailing comma. +tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts(4,7): error TS1013: A rest parameter or binding pattern may not have a trailing comma. +tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts(5,7): error TS1013: A rest parameter or binding pattern may not have a trailing comma. + + +==== tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts (4 errors) ==== + const [...a,] = []; + ~ +!!! error TS1013: A rest parameter or binding pattern may not have a trailing comma. + const {...b,} = {}; + ~ +!!! error TS1013: A rest parameter or binding pattern may not have a trailing comma. + let c, d; + ([...c,] = []); + ~ +!!! error TS1013: A rest parameter or binding pattern may not have a trailing comma. + ({...d,} = {}); + ~ +!!! error TS1013: A rest parameter or binding pattern may not have a trailing comma. + \ No newline at end of file diff --git a/tests/baselines/reference/trailingCommasInBindingPatterns.js b/tests/baselines/reference/trailingCommasInBindingPatterns.js new file mode 100644 index 00000000000..e26a93ccae7 --- /dev/null +++ b/tests/baselines/reference/trailingCommasInBindingPatterns.js @@ -0,0 +1,23 @@ +//// [trailingCommasInBindingPatterns.ts] +const [...a,] = []; +const {...b,} = {}; +let c, d; +([...c,] = []); +({...d,} = {}); + + +//// [trailingCommasInBindingPatterns.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var a = [].slice(0); +var b = __rest({}, []); +var c, d; +(c = [].slice(0)); +(d = __rest({}, [])); diff --git a/tests/baselines/reference/trailingCommasInBindingPatterns.symbols b/tests/baselines/reference/trailingCommasInBindingPatterns.symbols new file mode 100644 index 00000000000..c4c49175ca8 --- /dev/null +++ b/tests/baselines/reference/trailingCommasInBindingPatterns.symbols @@ -0,0 +1,17 @@ +=== tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts === +const [...a,] = []; +>a : Symbol(a, Decl(trailingCommasInBindingPatterns.ts, 0, 7)) + +const {...b,} = {}; +>b : Symbol(b, Decl(trailingCommasInBindingPatterns.ts, 1, 7)) + +let c, d; +>c : Symbol(c, Decl(trailingCommasInBindingPatterns.ts, 2, 3)) +>d : Symbol(d, Decl(trailingCommasInBindingPatterns.ts, 2, 6)) + +([...c,] = []); +>c : Symbol(c, Decl(trailingCommasInBindingPatterns.ts, 2, 3)) + +({...d,} = {}); +>d : Symbol(d, Decl(trailingCommasInBindingPatterns.ts, 2, 6)) + diff --git a/tests/baselines/reference/trailingCommasInBindingPatterns.types b/tests/baselines/reference/trailingCommasInBindingPatterns.types new file mode 100644 index 00000000000..aee6d21ad5f --- /dev/null +++ b/tests/baselines/reference/trailingCommasInBindingPatterns.types @@ -0,0 +1,28 @@ +=== tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts === +const [...a,] = []; +>a : any[] +>[] : undefined[] + +const {...b,} = {}; +>b : {} +>{} : {} + +let c, d; +>c : any +>d : any + +([...c,] = []); +>([...c,] = []) : undefined[] +>[...c,] = [] : undefined[] +>[...c,] : undefined[] +>...c : any +>c : any +>[] : undefined[] + +({...d,} = {}); +>({...d,} = {}) : {} +>{...d,} = {} : {} +>{...d,} : any +>d : any +>{} : {} + diff --git a/tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.errors.txt b/tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.errors.txt new file mode 100644 index 00000000000..6511b4f0264 --- /dev/null +++ b/tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.errors.txt @@ -0,0 +1,34 @@ +tests/cases/conformance/es7/trailingCommasInFunctionParametersAndArguments.ts(5,20): error TS1013: A rest parameter or binding pattern may not have a trailing comma. + + +==== tests/cases/conformance/es7/trailingCommasInFunctionParametersAndArguments.ts (1 errors) ==== + function f1(x,) {} + + f1(1,); + + function f2(...args,) {} + ~ +!!! error TS1013: A rest parameter or binding pattern may not have a trailing comma. + + f2(...[],); + + // Not confused by overloads + declare function f3(x, ): number; + declare function f3(x, y,): string; + + f3(1,); + f3(1, 2,); + + // Works for constructors too + class X { + constructor(a,) { } + // See trailingCommasInGetter.ts + set x(value,) { } + } + interface Y { + new(x,); + (x,); + } + + new X(1,); + \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread2.errors.txt b/tests/baselines/reference/unusedLocalsAndObjectSpread2.errors.txt index d4205782ef9..b980b86a61d 100644 --- a/tests/baselines/reference/unusedLocalsAndObjectSpread2.errors.txt +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread2.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(5,3): error TS6133: 'rest' is declared but its value is never read. tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(8,1): error TS6133: 'foo' is declared but its value is never read. -tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(12,5): error TS6133: 'rest' is declared but its value is never read. +tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(12,9): error TS6133: 'rest' is declared but its value is never read. ==== tests/cases/compiler/unusedLocalsAndObjectSpread2.ts (3 errors) ==== @@ -8,7 +8,7 @@ tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(12,5): error TS6133: 'rest' const { children, // here! active: _a, // here! - ...rest, + ...rest ~~~~~~~ !!! error TS6133: 'rest' is declared but its value is never read. } = props; @@ -19,10 +19,10 @@ tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(12,5): error TS6133: 'rest' const { children, active: _a, - ...rest, - ~~~~~~~ + ...rest + ~~~~~~~ !!! error TS6133: 'rest' is declared but its value is never read. - } = props; + } = props; } export const asdf = 123; \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread2.js b/tests/baselines/reference/unusedLocalsAndObjectSpread2.js index b7d1b8b106f..39061c7431c 100644 --- a/tests/baselines/reference/unusedLocalsAndObjectSpread2.js +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread2.js @@ -3,15 +3,15 @@ declare let props: any; const { children, // here! active: _a, // here! - ...rest, + ...rest } = props; function foo() { const { children, active: _a, - ...rest, - } = props; + ...rest + } = props; } export const asdf = 123; diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread2.symbols b/tests/baselines/reference/unusedLocalsAndObjectSpread2.symbols index 168b1f3434e..841b8d0a99f 100644 --- a/tests/baselines/reference/unusedLocalsAndObjectSpread2.symbols +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread2.symbols @@ -9,7 +9,7 @@ const { active: _a, // here! >_a : Symbol(_a, Decl(unusedLocalsAndObjectSpread2.ts, 2, 13)) - ...rest, + ...rest >rest : Symbol(rest, Decl(unusedLocalsAndObjectSpread2.ts, 3, 15)) } = props; @@ -25,10 +25,10 @@ function foo() { active: _a, >_a : Symbol(_a, Decl(unusedLocalsAndObjectSpread2.ts, 9, 17)) - ...rest, + ...rest >rest : Symbol(rest, Decl(unusedLocalsAndObjectSpread2.ts, 10, 19)) - } = props; + } = props; >props : Symbol(props, Decl(unusedLocalsAndObjectSpread2.ts, 0, 11)) } diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread2.types b/tests/baselines/reference/unusedLocalsAndObjectSpread2.types index 7b79b80b96e..d620d14a05e 100644 --- a/tests/baselines/reference/unusedLocalsAndObjectSpread2.types +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread2.types @@ -10,7 +10,7 @@ const { >active : any >_a : any - ...rest, + ...rest >rest : any } = props; @@ -27,10 +27,10 @@ function foo() { >active : any >_a : any - ...rest, + ...rest >rest : any - } = props; + } = props; >props : any } diff --git a/tests/cases/compiler/unusedLocalsAndObjectSpread2.ts b/tests/cases/compiler/unusedLocalsAndObjectSpread2.ts index e55c2042a41..bc7aa1216a9 100644 --- a/tests/cases/compiler/unusedLocalsAndObjectSpread2.ts +++ b/tests/cases/compiler/unusedLocalsAndObjectSpread2.ts @@ -4,15 +4,15 @@ declare let props: any; const { children, // here! active: _a, // here! - ...rest, + ...rest } = props; function foo() { const { children, active: _a, - ...rest, - } = props; + ...rest + } = props; } export const asdf = 123; \ No newline at end of file diff --git a/tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts b/tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts new file mode 100644 index 00000000000..db1935f2659 --- /dev/null +++ b/tests/cases/conformance/es7/trailingCommasInBindingPatterns.ts @@ -0,0 +1,5 @@ +const [...a,] = []; +const {...b,} = {}; +let c, d; +([...c,] = []); +({...d,} = {}); From 64ee623fd65addc9c2fcfee248827abb9519c75c Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 13:34:07 -0700 Subject: [PATCH 63/75] NodeBuilder only preserves parameter modifiers for constructors (#22706) --- src/compiler/checker.ts | 7 +- .../reference/ArrowFunctionExpression1.types | 4 +- .../baselines/reference/ParameterList4.types | 2 +- .../baselines/reference/ParameterList5.types | 2 +- .../baselines/reference/ParameterList6.types | 2 +- ...ClassDeclarationDoesntPrintWithReadonly.js | 51 +++++++++++++ ...DeclarationDoesntPrintWithReadonly.symbols | 14 ++++ ...ssDeclarationDoesntPrintWithReadonly.types | 15 ++++ ...thAccessibilityModifiersOnParameters.types | 74 +++++++++---------- ...thAccessibilityModifiersOnParameters.types | 4 +- ...hAccessibilityModifiersOnParameters2.types | 4 +- .../parameterPropertyOutsideConstructor.types | 2 +- .../parserArrowFunctionExpression1.types | 4 +- .../reference/parserParameterList4.types | 2 +- .../reference/parserParameterList5.types | 2 +- .../reference/parserParameterList6.types | 2 +- .../reference/readonlyInAmbientClass.types | 2 +- .../readonlyInNonPropertyParameters.types | 4 +- .../thisTypeInFunctionsNegative.types | 2 +- ...ClassDeclarationDoesntPrintWithReadonly.ts | 8 ++ 20 files changed, 148 insertions(+), 59 deletions(-) create mode 100644 tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js create mode 100644 tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.symbols create mode 100644 tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.types create mode 100644 tests/cases/compiler/anonymousClassDeclarationDoesntPrintWithReadonly.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0ccaccb546b..8ad3cac2ae1 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3393,7 +3393,8 @@ namespace ts { else { typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter, context)); } - const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter, context)); + + const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter, context, kind === SyntaxKind.Constructor)); if (signature.thisParameter) { const thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -3433,7 +3434,7 @@ namespace ts { return createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol: Symbol, context: NodeBuilderContext): ParameterDeclaration { + function symbolToParameterDeclaration(parameterSymbol: Symbol, context: NodeBuilderContext, preserveModifierFlags?: boolean): ParameterDeclaration { const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter); Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); @@ -3443,7 +3444,7 @@ namespace ts { } const parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - const modifiers = !(context.flags & NodeBuilderFlags.OmitParameterModifiers) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(getSynthesizedClone); + const modifiers = !(context.flags & NodeBuilderFlags.OmitParameterModifiers) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(getSynthesizedClone); const dotDotDotToken = !parameterDeclaration || isRestParameter(parameterDeclaration) ? createToken(SyntaxKind.DotDotDotToken) : undefined; const name = parameterDeclaration ? parameterDeclaration.name ? diff --git a/tests/baselines/reference/ArrowFunctionExpression1.types b/tests/baselines/reference/ArrowFunctionExpression1.types index c62b1c198b1..122f949c3c3 100644 --- a/tests/baselines/reference/ArrowFunctionExpression1.types +++ b/tests/baselines/reference/ArrowFunctionExpression1.types @@ -1,6 +1,6 @@ === tests/cases/compiler/ArrowFunctionExpression1.ts === var v = (public x: string) => { }; ->v : (public x: string) => void ->(public x: string) => { } : (public x: string) => void +>v : (x: string) => void +>(public x: string) => { } : (x: string) => void >x : string diff --git a/tests/baselines/reference/ParameterList4.types b/tests/baselines/reference/ParameterList4.types index 5d947f15c4b..4c354abb68a 100644 --- a/tests/baselines/reference/ParameterList4.types +++ b/tests/baselines/reference/ParameterList4.types @@ -1,5 +1,5 @@ === tests/cases/compiler/ParameterList4.ts === function F(public A) { ->F : (public A: any) => void +>F : (A: any) => void >A : any } diff --git a/tests/baselines/reference/ParameterList5.types b/tests/baselines/reference/ParameterList5.types index 3c07e99bb48..57b80d0d807 100644 --- a/tests/baselines/reference/ParameterList5.types +++ b/tests/baselines/reference/ParameterList5.types @@ -1,6 +1,6 @@ === tests/cases/compiler/ParameterList5.ts === function A(): (public B) => C { ->A : () => (public B: any) => any +>A : () => (B: any) => any >B : any >C : No type information available! } diff --git a/tests/baselines/reference/ParameterList6.types b/tests/baselines/reference/ParameterList6.types index 26947a4a23f..c514041ce27 100644 --- a/tests/baselines/reference/ParameterList6.types +++ b/tests/baselines/reference/ParameterList6.types @@ -3,7 +3,7 @@ class C { >C : C constructor(C: (public A) => any) { ->C : (public A: any) => any +>C : (A: any) => any >A : any } } diff --git a/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js new file mode 100644 index 00000000000..1ecab30597a --- /dev/null +++ b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js @@ -0,0 +1,51 @@ +//// [anonymousClassDeclarationDoesntPrintWithReadonly.ts] +export class X { + constructor(readonly a: number) { } +} + +export function y() { + return class extends X { } +} + +//// [anonymousClassDeclarationDoesntPrintWithReadonly.js] +"use strict"; +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 __()); + }; +})(); +exports.__esModule = true; +var X = /** @class */ (function () { + function X(a) { + this.a = a; + } + return X; +}()); +exports.X = X; +function y() { + return /** @class */ (function (_super) { + __extends(class_1, _super); + function class_1() { + return _super !== null && _super.apply(this, arguments) || this; + } + return class_1; + }(X)); +} +exports.y = y; + + +//// [anonymousClassDeclarationDoesntPrintWithReadonly.d.ts] +export declare class X { + readonly a: number; + constructor(a: number); +} +export declare function y(): { + new (a: number): { + readonly a: number; + }; +}; diff --git a/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.symbols b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.symbols new file mode 100644 index 00000000000..b450e1b3b83 --- /dev/null +++ b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.symbols @@ -0,0 +1,14 @@ +=== tests/cases/compiler/anonymousClassDeclarationDoesntPrintWithReadonly.ts === +export class X { +>X : Symbol(X, Decl(anonymousClassDeclarationDoesntPrintWithReadonly.ts, 0, 0)) + + constructor(readonly a: number) { } +>a : Symbol(X.a, Decl(anonymousClassDeclarationDoesntPrintWithReadonly.ts, 1, 16)) +} + +export function y() { +>y : Symbol(y, Decl(anonymousClassDeclarationDoesntPrintWithReadonly.ts, 2, 1)) + + return class extends X { } +>X : Symbol(X, Decl(anonymousClassDeclarationDoesntPrintWithReadonly.ts, 0, 0)) +} diff --git a/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.types b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.types new file mode 100644 index 00000000000..f84a4418f14 --- /dev/null +++ b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.types @@ -0,0 +1,15 @@ +=== tests/cases/compiler/anonymousClassDeclarationDoesntPrintWithReadonly.ts === +export class X { +>X : X + + constructor(readonly a: number) { } +>a : number +} + +export function y() { +>y : () => typeof (Anonymous class) + + return class extends X { } +>class extends X { } : typeof (Anonymous class) +>X : X +} diff --git a/tests/baselines/reference/callSignaturesWithAccessibilityModifiersOnParameters.types b/tests/baselines/reference/callSignaturesWithAccessibilityModifiersOnParameters.types index af074b5faa0..80f8e6445d5 100644 --- a/tests/baselines/reference/callSignaturesWithAccessibilityModifiersOnParameters.types +++ b/tests/baselines/reference/callSignaturesWithAccessibilityModifiersOnParameters.types @@ -2,32 +2,32 @@ // Call signature parameters do not allow accessibility modifiers function foo(public x, private y) { } ->foo : (public x: any, private y: any) => void +>foo : (x: any, y: any) => void >x : any >y : any var f = function foo(public x, private y) { } ->f : (public x: any, private y: any) => void ->function foo(public x, private y) { } : (public x: any, private y: any) => void ->foo : (public x: any, private y: any) => void +>f : (x: any, y: any) => void +>function foo(public x, private y) { } : (x: any, y: any) => void +>foo : (x: any, y: any) => void >x : any >y : any var f2 = function (public x, private y) { } ->f2 : (public x: any, private y: any) => void ->function (public x, private y) { } : (public x: any, private y: any) => void +>f2 : (x: any, y: any) => void +>function (public x, private y) { } : (x: any, y: any) => void >x : any >y : any var f3 = (x, private y) => { } ->f3 : (x: any, private y: any) => void ->(x, private y) => { } : (x: any, private y: any) => void +>f3 : (x: any, y: any) => void +>(x, private y) => { } : (x: any, y: any) => void >x : any >y : any var f4 = (public x: T, y: T) => { } ->f4 : (public x: T, y: T) => void ->(public x: T, y: T) => { } : (public x: T, y: T) => void +>f4 : (x: T, y: T) => void +>(public x: T, y: T) => { } : (x: T, y: T) => void >T : T >x : T >T : T @@ -35,32 +35,32 @@ var f4 = (public x: T, y: T) => { } >T : T function foo2(private x: string, public y: number) { } ->foo2 : (private x: string, public y: number) => void +>foo2 : (x: string, y: number) => void >x : string >y : number var f5 = function foo(private x: string, public y: number) { } ->f5 : (private x: string, public y: number) => void ->function foo(private x: string, public y: number) { } : (private x: string, public y: number) => void ->foo : (private x: string, public y: number) => void +>f5 : (x: string, y: number) => void +>function foo(private x: string, public y: number) { } : (x: string, y: number) => void +>foo : (x: string, y: number) => void >x : string >y : number var f6 = function (private x: string, public y: number) { } ->f6 : (private x: string, public y: number) => void ->function (private x: string, public y: number) { } : (private x: string, public y: number) => void +>f6 : (x: string, y: number) => void +>function (private x: string, public y: number) { } : (x: string, y: number) => void >x : string >y : number var f7 = (private x: string, public y: number) => { } ->f7 : (private x: string, public y: number) => void ->(private x: string, public y: number) => { } : (private x: string, public y: number) => void +>f7 : (x: string, y: number) => void +>(private x: string, public y: number) => { } : (x: string, y: number) => void >x : string >y : number var f8 = (private x: T, public y: T) => { } ->f8 : (private x: T, public y: T) => void ->(private x: T, public y: T) => { } : (private x: T, public y: T) => void +>f8 : (x: T, y: T) => void +>(private x: T, public y: T) => { } : (x: T, y: T) => void >T : T >x : T >T : T @@ -71,17 +71,17 @@ class C { >C : C foo(public x, private y) { } ->foo : (public x: any, private y: any) => void +>foo : (x: any, y: any) => void >x : any >y : any foo2(public x: number, private y: string) { } ->foo2 : (public x: number, private y: string) => void +>foo2 : (x: number, y: string) => void >x : number >y : string foo3(public x: T, private y: T) { } ->foo3 : (public x: T, private y: T) => void +>foo3 : (x: T, y: T) => void >T : T >x : T >T : T @@ -101,17 +101,17 @@ interface I { >y : number foo(private x, public y); ->foo : { (private x: any, public y: any): any; (public x: number, y: string): any; } +>foo : { (x: any, y: any): any; (x: number, y: string): any; } >x : any >y : any foo(public x: number, y: string); ->foo : { (private x: any, public y: any): any; (public x: number, y: string): any; } +>foo : { (x: any, y: any): any; (x: number, y: string): any; } >x : number >y : string foo3(x: T, private y: T); ->foo3 : (x: T, private y: T) => any +>foo3 : (x: T, y: T) => any >T : T >x : T >T : T @@ -120,39 +120,39 @@ interface I { } var a: { ->a : { foo(public x: any, private y: any): any; foo2(private x: number, public y: string): any; } +>a : { foo(x: any, y: any): any; foo2(x: number, y: string): any; } foo(public x, private y); ->foo : (public x: any, private y: any) => any +>foo : (x: any, y: any) => any >x : any >y : any foo2(private x: number, public y: string); ->foo2 : (private x: number, public y: string) => any +>foo2 : (x: number, y: string) => any >x : number >y : string }; var b = { ->b : { foo(public x: any, y: any): void; a: (x: number, private y: string) => void; b: (public x: T, private y: T) => void; } ->{ foo(public x, y) { }, a: function foo(x: number, private y: string) { }, b: (public x: T, private y: T) => { }} : { foo(public x: any, y: any): void; a: (x: number, private y: string) => void; b: (public x: T, private y: T) => void; } +>b : { foo(x: any, y: any): void; a: (x: number, y: string) => void; b: (x: T, y: T) => void; } +>{ foo(public x, y) { }, a: function foo(x: number, private y: string) { }, b: (public x: T, private y: T) => { }} : { foo(x: any, y: any): void; a: (x: number, y: string) => void; b: (x: T, y: T) => void; } foo(public x, y) { }, ->foo : (public x: any, y: any) => void +>foo : (x: any, y: any) => void >x : any >y : any a: function foo(x: number, private y: string) { }, ->a : (x: number, private y: string) => void ->function foo(x: number, private y: string) { } : (x: number, private y: string) => void ->foo : (x: number, private y: string) => void +>a : (x: number, y: string) => void +>function foo(x: number, private y: string) { } : (x: number, y: string) => void +>foo : (x: number, y: string) => void >x : number >y : string b: (public x: T, private y: T) => { } ->b : (public x: T, private y: T) => void ->(public x: T, private y: T) => { } : (public x: T, private y: T) => void +>b : (x: T, y: T) => void +>(public x: T, private y: T) => { } : (x: T, y: T) => void >T : T >x : T >T : T diff --git a/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters.types b/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters.types index 3a96cf9534e..5cd0929de86 100644 --- a/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters.types +++ b/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters.types @@ -38,14 +38,14 @@ interface I2 { } var a: { ->a : new (public x: any) => any +>a : new (x: any) => any new (public x); >x : any } var b: { ->b : new (private x: any) => any +>b : new (x: any) => any new (private x); >x : any diff --git a/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters2.types b/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters2.types index 79483d55eb1..98058e6b0f4 100644 --- a/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters2.types +++ b/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters2.types @@ -54,7 +54,7 @@ interface I2 { } var a: { ->a : { new (public x: any): any; new (public y: any): any; } +>a : { new (x: any): any; new (y: any): any; } new (public x); >x : any @@ -64,7 +64,7 @@ var a: { } var b: { ->b : { new (private x: any): any; new (private y: any): any; } +>b : { new (x: any): any; new (y: any): any; } new (private x); >x : any diff --git a/tests/baselines/reference/parameterPropertyOutsideConstructor.types b/tests/baselines/reference/parameterPropertyOutsideConstructor.types index c6d2d5888d6..179dd5735aa 100644 --- a/tests/baselines/reference/parameterPropertyOutsideConstructor.types +++ b/tests/baselines/reference/parameterPropertyOutsideConstructor.types @@ -3,7 +3,7 @@ class C { >C : C foo(public x) { ->foo : (public x: any) => void +>foo : (x: any) => void >x : any } } diff --git a/tests/baselines/reference/parserArrowFunctionExpression1.types b/tests/baselines/reference/parserArrowFunctionExpression1.types index 98a3f85b4d2..925c0269f30 100644 --- a/tests/baselines/reference/parserArrowFunctionExpression1.types +++ b/tests/baselines/reference/parserArrowFunctionExpression1.types @@ -1,6 +1,6 @@ === tests/cases/conformance/parser/ecmascript5/ArrowFunctionExpressions/parserArrowFunctionExpression1.ts === var v = (public x: string) => { }; ->v : (public x: string) => void ->(public x: string) => { } : (public x: string) => void +>v : (x: string) => void +>(public x: string) => { } : (x: string) => void >x : string diff --git a/tests/baselines/reference/parserParameterList4.types b/tests/baselines/reference/parserParameterList4.types index 24a10507fbd..2e9afe7874f 100644 --- a/tests/baselines/reference/parserParameterList4.types +++ b/tests/baselines/reference/parserParameterList4.types @@ -1,5 +1,5 @@ === tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList4.ts === function F(public A) { ->F : (public A: any) => void +>F : (A: any) => void >A : any } diff --git a/tests/baselines/reference/parserParameterList5.types b/tests/baselines/reference/parserParameterList5.types index 9604bd76144..afe73c6f6c6 100644 --- a/tests/baselines/reference/parserParameterList5.types +++ b/tests/baselines/reference/parserParameterList5.types @@ -1,6 +1,6 @@ === tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList5.ts === function A(): (public B) => C { ->A : () => (public B: any) => any +>A : () => (B: any) => any >B : any >C : No type information available! } diff --git a/tests/baselines/reference/parserParameterList6.types b/tests/baselines/reference/parserParameterList6.types index bbd21a71247..10b08ba19da 100644 --- a/tests/baselines/reference/parserParameterList6.types +++ b/tests/baselines/reference/parserParameterList6.types @@ -3,7 +3,7 @@ class C { >C : C constructor(C: (public A) => any) { ->C : (public A: any) => any +>C : (A: any) => any >A : any } } diff --git a/tests/baselines/reference/readonlyInAmbientClass.types b/tests/baselines/reference/readonlyInAmbientClass.types index 12f582cf8b0..633f98274da 100644 --- a/tests/baselines/reference/readonlyInAmbientClass.types +++ b/tests/baselines/reference/readonlyInAmbientClass.types @@ -6,6 +6,6 @@ declare class C{ >x : number method(readonly x: number); ->method : (readonly x: number) => any +>method : (x: number) => any >x : number } diff --git a/tests/baselines/reference/readonlyInNonPropertyParameters.types b/tests/baselines/reference/readonlyInNonPropertyParameters.types index c24e2aad6ca..0088f580074 100644 --- a/tests/baselines/reference/readonlyInNonPropertyParameters.types +++ b/tests/baselines/reference/readonlyInNonPropertyParameters.types @@ -4,7 +4,7 @@ class X { >X : X method(readonly x: number) {} ->method : (readonly x: number) => void +>method : (x: number) => void >x : number set x(readonly value: number) {} @@ -12,7 +12,7 @@ class X { >value : number } (readonly x) => 0; ->(readonly x) => 0 : (readonly x: any) => number +>(readonly x) => 0 : (x: any) => number >x : any >0 : 0 diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.types b/tests/baselines/reference/thisTypeInFunctionsNegative.types index a5a8db3e2ee..1625497fb16 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.types +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.types @@ -725,7 +725,7 @@ function notFirst(a: number, this: C): number { return this.n; } ///// parse errors ///// function modifiers(async this: C): number { return this.n; } ->modifiers : (async : any, this: C) => number +>modifiers : (: any, this: C) => number > : any >this : C >C : C diff --git a/tests/cases/compiler/anonymousClassDeclarationDoesntPrintWithReadonly.ts b/tests/cases/compiler/anonymousClassDeclarationDoesntPrintWithReadonly.ts new file mode 100644 index 00000000000..a4803ef9950 --- /dev/null +++ b/tests/cases/compiler/anonymousClassDeclarationDoesntPrintWithReadonly.ts @@ -0,0 +1,8 @@ +// @declaration: true +export class X { + constructor(readonly a: number) { } +} + +export function y() { + return class extends X { } +} \ No newline at end of file From 411c59a8ef43254f9c1d3e39c8c8ce47debd68f6 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 13:38:36 -0700 Subject: [PATCH 64/75] Copy comments from inferred types to generated nodes (#22730) --- src/compiler/checker.ts | 8 ++ .../declarationEmitRetainsJsdocyComments.js | 122 ++++++++++++++++++ ...clarationEmitRetainsJsdocyComments.symbols | 65 ++++++++++ ...declarationEmitRetainsJsdocyComments.types | 71 ++++++++++ .../declarationEmitRetainsJsdocyComments.ts | 44 +++++++ 5 files changed, 310 insertions(+) create mode 100644 tests/baselines/reference/declarationEmitRetainsJsdocyComments.js create mode 100644 tests/baselines/reference/declarationEmitRetainsJsdocyComments.symbols create mode 100644 tests/baselines/reference/declarationEmitRetainsJsdocyComments.types create mode 100644 tests/cases/compiler/declarationEmitRetainsJsdocyComments.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8ad3cac2ae1..bf6c22c42af 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3324,6 +3324,10 @@ namespace ts { const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } typeElements.push(methodDeclaration); } } @@ -3340,6 +3344,10 @@ namespace ts { optionalToken, propertyTypeNode, /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } typeElements.push(propertySignature); } } diff --git a/tests/baselines/reference/declarationEmitRetainsJsdocyComments.js b/tests/baselines/reference/declarationEmitRetainsJsdocyComments.js new file mode 100644 index 00000000000..0d1a3ba6cb9 --- /dev/null +++ b/tests/baselines/reference/declarationEmitRetainsJsdocyComments.js @@ -0,0 +1,122 @@ +//// [declarationEmitRetainsJsdocyComments.ts] +/** + * comment1 + * @param p + */ +export const foo = (p: string) => { + return { + /** + * comment2 + * @param s + */ + bar: (s: number) => {}, + /** + * comment3 + * @param s + */ + bar2(s: number) {}, + } +} + +export class Foo { + /** + * comment4 + * @param s + */ + bar(s: number) { + } +} + +export let { + /** + * comment5 + */ + someMethod +} = null as any; + +declare global { + interface ExtFunc { + /** + * comment6 + */ + someMethod(collection: any[]): boolean; + } +} + + +//// [declarationEmitRetainsJsdocyComments.js] +"use strict"; +exports.__esModule = true; +/** + * comment1 + * @param p + */ +exports.foo = function (p) { + return { + /** + * comment2 + * @param s + */ + bar: function (s) { }, + /** + * comment3 + * @param s + */ + bar2: function (s) { } + }; +}; +var Foo = /** @class */ (function () { + function Foo() { + } + /** + * comment4 + * @param s + */ + Foo.prototype.bar = function (s) { + }; + return Foo; +}()); +exports.Foo = Foo; +/** +* comment5 +*/ +exports.someMethod = null.someMethod; + + +//// [declarationEmitRetainsJsdocyComments.d.ts] +/** + * comment1 + * @param p + */ +export declare const foo: (p: string) => { + /** + * comment2 + * @param s + */ + bar: (s: number) => void; + /** + * comment3 + * @param s + */ + bar2(s: number): void; +}; +export declare class Foo { + /** + * comment4 + * @param s + */ + bar(s: number): void; +} +export declare let +/** +* comment5 +*/ +someMethod: any; +declare global { + interface ExtFunc { + /** + * comment6 + */ + someMethod(collection: any[]): boolean; + } +} diff --git a/tests/baselines/reference/declarationEmitRetainsJsdocyComments.symbols b/tests/baselines/reference/declarationEmitRetainsJsdocyComments.symbols new file mode 100644 index 00000000000..6e0a6a5158d --- /dev/null +++ b/tests/baselines/reference/declarationEmitRetainsJsdocyComments.symbols @@ -0,0 +1,65 @@ +=== tests/cases/compiler/declarationEmitRetainsJsdocyComments.ts === +/** + * comment1 + * @param p + */ +export const foo = (p: string) => { +>foo : Symbol(foo, Decl(declarationEmitRetainsJsdocyComments.ts, 4, 12)) +>p : Symbol(p, Decl(declarationEmitRetainsJsdocyComments.ts, 4, 20)) + + return { + /** + * comment2 + * @param s + */ + bar: (s: number) => {}, +>bar : Symbol(bar, Decl(declarationEmitRetainsJsdocyComments.ts, 5, 12)) +>s : Symbol(s, Decl(declarationEmitRetainsJsdocyComments.ts, 10, 14)) + + /** + * comment3 + * @param s + */ + bar2(s: number) {}, +>bar2 : Symbol(bar2, Decl(declarationEmitRetainsJsdocyComments.ts, 10, 31)) +>s : Symbol(s, Decl(declarationEmitRetainsJsdocyComments.ts, 15, 13)) + } +} + +export class Foo { +>Foo : Symbol(Foo, Decl(declarationEmitRetainsJsdocyComments.ts, 17, 1)) + + /** + * comment4 + * @param s + */ + bar(s: number) { +>bar : Symbol(Foo.bar, Decl(declarationEmitRetainsJsdocyComments.ts, 19, 18)) +>s : Symbol(s, Decl(declarationEmitRetainsJsdocyComments.ts, 24, 8)) + } +} + +export let { + /** + * comment5 + */ + someMethod +>someMethod : Symbol(someMethod, Decl(declarationEmitRetainsJsdocyComments.ts, 28, 12)) + +} = null as any; + +declare global { +>global : Symbol(global, Decl(declarationEmitRetainsJsdocyComments.ts, 33, 16)) + + interface ExtFunc { +>ExtFunc : Symbol(ExtFunc, Decl(declarationEmitRetainsJsdocyComments.ts, 35, 16)) + + /** + * comment6 + */ + someMethod(collection: any[]): boolean; +>someMethod : Symbol(ExtFunc.someMethod, Decl(declarationEmitRetainsJsdocyComments.ts, 36, 23)) +>collection : Symbol(collection, Decl(declarationEmitRetainsJsdocyComments.ts, 40, 19)) + } +} + diff --git a/tests/baselines/reference/declarationEmitRetainsJsdocyComments.types b/tests/baselines/reference/declarationEmitRetainsJsdocyComments.types new file mode 100644 index 00000000000..9487667d18c --- /dev/null +++ b/tests/baselines/reference/declarationEmitRetainsJsdocyComments.types @@ -0,0 +1,71 @@ +=== tests/cases/compiler/declarationEmitRetainsJsdocyComments.ts === +/** + * comment1 + * @param p + */ +export const foo = (p: string) => { +>foo : (p: string) => { bar: (s: number) => void; bar2(s: number): void; } +>(p: string) => { return { /** * comment2 * @param s */ bar: (s: number) => {}, /** * comment3 * @param s */ bar2(s: number) {}, }} : (p: string) => { bar: (s: number) => void; bar2(s: number): void; } +>p : string + + return { +>{ /** * comment2 * @param s */ bar: (s: number) => {}, /** * comment3 * @param s */ bar2(s: number) {}, } : { bar: (s: number) => void; bar2(s: number): void; } + + /** + * comment2 + * @param s + */ + bar: (s: number) => {}, +>bar : (s: number) => void +>(s: number) => {} : (s: number) => void +>s : number + + /** + * comment3 + * @param s + */ + bar2(s: number) {}, +>bar2 : (s: number) => void +>s : number + } +} + +export class Foo { +>Foo : Foo + + /** + * comment4 + * @param s + */ + bar(s: number) { +>bar : (s: number) => void +>s : number + } +} + +export let { + /** + * comment5 + */ + someMethod +>someMethod : any + +} = null as any; +>null as any : any +>null : null + +declare global { +>global : any + + interface ExtFunc { +>ExtFunc : ExtFunc + + /** + * comment6 + */ + someMethod(collection: any[]): boolean; +>someMethod : (collection: any[]) => boolean +>collection : any[] + } +} + diff --git a/tests/cases/compiler/declarationEmitRetainsJsdocyComments.ts b/tests/cases/compiler/declarationEmitRetainsJsdocyComments.ts new file mode 100644 index 00000000000..53901083758 --- /dev/null +++ b/tests/cases/compiler/declarationEmitRetainsJsdocyComments.ts @@ -0,0 +1,44 @@ +// @declaration: true +/** + * comment1 + * @param p + */ +export const foo = (p: string) => { + return { + /** + * comment2 + * @param s + */ + bar: (s: number) => {}, + /** + * comment3 + * @param s + */ + bar2(s: number) {}, + } +} + +export class Foo { + /** + * comment4 + * @param s + */ + bar(s: number) { + } +} + +export let { + /** + * comment5 + */ + someMethod +} = null as any; + +declare global { + interface ExtFunc { + /** + * comment6 + */ + someMethod(collection: any[]): boolean; + } +} From 509a53fea7dc5c7f31cc9216da64a8579c1c5948 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 13:42:26 -0700 Subject: [PATCH 65/75] Propagate CheckFlags.Late through instantiateSymbol (#22749) --- src/compiler/checker.ts | 2 +- ...ationEmitPrivateNameCausesError.errors.txt | 14 +++++++ .../declarationEmitPrivateNameCausesError.js | 40 +++++++++++++++++++ ...larationEmitPrivateNameCausesError.symbols | 22 ++++++++++ ...eclarationEmitPrivateNameCausesError.types | 25 ++++++++++++ .../declarationEmitPrivateNameCausesError.ts | 11 +++++ 6 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/declarationEmitPrivateNameCausesError.errors.txt create mode 100644 tests/baselines/reference/declarationEmitPrivateNameCausesError.js create mode 100644 tests/baselines/reference/declarationEmitPrivateNameCausesError.symbols create mode 100644 tests/baselines/reference/declarationEmitPrivateNameCausesError.types create mode 100644 tests/cases/compiler/declarationEmitPrivateNameCausesError.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index bf6c22c42af..7cfa500a326 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8922,7 +8922,7 @@ namespace 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. - const result = createSymbol(symbol.flags, symbol.escapedName, CheckFlags.Instantiated); + const result = createSymbol(symbol.flags, symbol.escapedName, CheckFlags.Instantiated | (getCheckFlags(symbol) & CheckFlags.Late)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; diff --git a/tests/baselines/reference/declarationEmitPrivateNameCausesError.errors.txt b/tests/baselines/reference/declarationEmitPrivateNameCausesError.errors.txt new file mode 100644 index 00000000000..0b6ba74a6f3 --- /dev/null +++ b/tests/baselines/reference/declarationEmitPrivateNameCausesError.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/file.ts(4,17): error TS4060: Return type of exported function has or is using private name 'IGNORE_EXTRA_VARIABLES'. + + +==== tests/cases/compiler/file.ts (1 errors) ==== + const IGNORE_EXTRA_VARIABLES = Symbol(); //Notice how this is unexported + + //This is exported + export function ignoreExtraVariables (ctor : CtorT) { + ~~~~~~~~~~~~~~~~~~~~ +!!! error TS4060: Return type of exported function has or is using private name 'IGNORE_EXTRA_VARIABLES'. + return class extends ctor { + [IGNORE_EXTRA_VARIABLES] = true; //An unexported constant is used + }; + } \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitPrivateNameCausesError.js b/tests/baselines/reference/declarationEmitPrivateNameCausesError.js new file mode 100644 index 00000000000..8f801e70bb4 --- /dev/null +++ b/tests/baselines/reference/declarationEmitPrivateNameCausesError.js @@ -0,0 +1,40 @@ +//// [file.ts] +const IGNORE_EXTRA_VARIABLES = Symbol(); //Notice how this is unexported + +//This is exported +export function ignoreExtraVariables (ctor : CtorT) { + return class extends ctor { + [IGNORE_EXTRA_VARIABLES] = true; //An unexported constant is used + }; +} + +//// [file.js] +"use strict"; +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 __()); + }; +})(); +exports.__esModule = true; +var IGNORE_EXTRA_VARIABLES = Symbol(); //Notice how this is unexported +//This is exported +function ignoreExtraVariables(ctor) { + return _a = /** @class */ (function (_super) { + __extends(class_1, _super); + function class_1() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this[_b] = true; //An unexported constant is used + return _this; + } + return class_1; + }(ctor)), + _b = IGNORE_EXTRA_VARIABLES, + _a; + var _b, _a; +} +exports.ignoreExtraVariables = ignoreExtraVariables; diff --git a/tests/baselines/reference/declarationEmitPrivateNameCausesError.symbols b/tests/baselines/reference/declarationEmitPrivateNameCausesError.symbols new file mode 100644 index 00000000000..51f158bb985 --- /dev/null +++ b/tests/baselines/reference/declarationEmitPrivateNameCausesError.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/file.ts === +const IGNORE_EXTRA_VARIABLES = Symbol(); //Notice how this is unexported +>IGNORE_EXTRA_VARIABLES : Symbol(IGNORE_EXTRA_VARIABLES, Decl(file.ts, 0, 5)) +>Symbol : Symbol(Symbol, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --)) + +//This is exported +export function ignoreExtraVariables (ctor : CtorT) { +>ignoreExtraVariables : Symbol(ignoreExtraVariables, Decl(file.ts, 0, 40)) +>CtorT : Symbol(CtorT, Decl(file.ts, 3, 37)) +>args : Symbol(args, Decl(file.ts, 3, 56)) +>ctor : Symbol(ctor, Decl(file.ts, 3, 77)) +>CtorT : Symbol(CtorT, Decl(file.ts, 3, 37)) + + return class extends ctor { +>ctor : Symbol(ctor, Decl(file.ts, 3, 77)) + + [IGNORE_EXTRA_VARIABLES] = true; //An unexported constant is used +>[IGNORE_EXTRA_VARIABLES] : Symbol((Anonymous class)[IGNORE_EXTRA_VARIABLES], Decl(file.ts, 4, 31)) +>IGNORE_EXTRA_VARIABLES : Symbol(IGNORE_EXTRA_VARIABLES, Decl(file.ts, 0, 5)) + + }; +} diff --git a/tests/baselines/reference/declarationEmitPrivateNameCausesError.types b/tests/baselines/reference/declarationEmitPrivateNameCausesError.types new file mode 100644 index 00000000000..e4b94eb99d1 --- /dev/null +++ b/tests/baselines/reference/declarationEmitPrivateNameCausesError.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/file.ts === +const IGNORE_EXTRA_VARIABLES = Symbol(); //Notice how this is unexported +>IGNORE_EXTRA_VARIABLES : unique symbol +>Symbol() : unique symbol +>Symbol : SymbolConstructor + +//This is exported +export function ignoreExtraVariables (ctor : CtorT) { +>ignoreExtraVariables : {}>(ctor: CtorT) => { new (...args: any[]): (Anonymous class); prototype: ignoreExtraVariables.(Anonymous class); } & CtorT +>CtorT : CtorT +>args : any[] +>ctor : CtorT +>CtorT : CtorT + + return class extends ctor { +>class extends ctor { [IGNORE_EXTRA_VARIABLES] = true; //An unexported constant is used } : { new (...args: any[]): (Anonymous class); prototype: ignoreExtraVariables.(Anonymous class); } & CtorT +>ctor : {} + + [IGNORE_EXTRA_VARIABLES] = true; //An unexported constant is used +>[IGNORE_EXTRA_VARIABLES] : boolean +>IGNORE_EXTRA_VARIABLES : unique symbol +>true : true + + }; +} diff --git a/tests/cases/compiler/declarationEmitPrivateNameCausesError.ts b/tests/cases/compiler/declarationEmitPrivateNameCausesError.ts new file mode 100644 index 00000000000..228f45c475f --- /dev/null +++ b/tests/cases/compiler/declarationEmitPrivateNameCausesError.ts @@ -0,0 +1,11 @@ +// @declaration: true +// @lib: es6 +// @filename: file.ts +const IGNORE_EXTRA_VARIABLES = Symbol(); //Notice how this is unexported + +//This is exported +export function ignoreExtraVariables (ctor : CtorT) { + return class extends ctor { + [IGNORE_EXTRA_VARIABLES] = true; //An unexported constant is used + }; +} \ No newline at end of file From 43a482f03fd9f6a220172c16d344b9d29a69e331 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 13:43:31 -0700 Subject: [PATCH 66/75] Emit amd-module and amd-dependency comments in emitter if printing declaration comments (#22740) * Emit amd-module and amd-dependency comments in emitter if printing declaration comments * Move code a bit * Move again --- src/compiler/emitter.ts | 15 ++++++ .../declarationEmitAmdModuleNameDirective.js | 49 +++++++++++++++++++ ...larationEmitAmdModuleNameDirective.symbols | 13 +++++ ...eclarationEmitAmdModuleNameDirective.types | 15 ++++++ .../declarationEmitAmdModuleNameDirective.ts | 9 ++++ 5 files changed, 101 insertions(+) create mode 100644 tests/baselines/reference/declarationEmitAmdModuleNameDirective.js create mode 100644 tests/baselines/reference/declarationEmitAmdModuleNameDirective.symbols create mode 100644 tests/baselines/reference/declarationEmitAmdModuleNameDirective.types create mode 100644 tests/cases/compiler/declarationEmitAmdModuleNameDirective.ts diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index b46ca852135..6fca3d897ac 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2481,6 +2481,21 @@ namespace ts { } function emitTripleSlashDirectives(files: ReadonlyArray, types: ReadonlyArray) { + if (currentSourceFile && currentSourceFile.moduleName) { + write(`/// `); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (const dep of currentSourceFile.amdDependencies) { + if (dep.name) { + write(`/// `); + } + else { + write(`/// `); + } + writeLine(); + } + } for (const directive of files) { write(`/// `); writeLine(); diff --git a/tests/baselines/reference/declarationEmitAmdModuleNameDirective.js b/tests/baselines/reference/declarationEmitAmdModuleNameDirective.js new file mode 100644 index 00000000000..eb7e0db489e --- /dev/null +++ b/tests/baselines/reference/declarationEmitAmdModuleNameDirective.js @@ -0,0 +1,49 @@ +//// [tests/cases/compiler/declarationEmitAmdModuleNameDirective.ts] //// + +//// [foo.ts] +/// +export const foo = 1; +//// [bar.ts] +/// +import {foo} from './foo'; +void foo; + +//// [foo.js] +(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("name_of_foo", ["require", "exports"], factory); + } +})(function (require, exports) { + "use strict"; + exports.__esModule = true; + /// + exports.foo = 1; +}); +//// [bar.js] +(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", "./foo", "name_of_foo"], factory); + } +})(function (require, exports, name_of_foo) { + "use strict"; + exports.__esModule = true; + /// + var foo_1 = require("name_of_foo"); + void foo_1.foo; +}); + + +//// [foo.d.ts] +/// +export declare const foo = 1; +//// [bar.d.ts] +/// +export {}; diff --git a/tests/baselines/reference/declarationEmitAmdModuleNameDirective.symbols b/tests/baselines/reference/declarationEmitAmdModuleNameDirective.symbols new file mode 100644 index 00000000000..f8100b8d250 --- /dev/null +++ b/tests/baselines/reference/declarationEmitAmdModuleNameDirective.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/foo.ts === +/// +export const foo = 1; +>foo : Symbol(foo, Decl(foo.ts, 1, 12)) + +=== tests/cases/compiler/bar.ts === +/// +import {foo} from './foo'; +>foo : Symbol(foo, Decl(bar.ts, 1, 8)) + +void foo; +>foo : Symbol(foo, Decl(bar.ts, 1, 8)) + diff --git a/tests/baselines/reference/declarationEmitAmdModuleNameDirective.types b/tests/baselines/reference/declarationEmitAmdModuleNameDirective.types new file mode 100644 index 00000000000..e2c710afa6e --- /dev/null +++ b/tests/baselines/reference/declarationEmitAmdModuleNameDirective.types @@ -0,0 +1,15 @@ +=== tests/cases/compiler/foo.ts === +/// +export const foo = 1; +>foo : 1 +>1 : 1 + +=== tests/cases/compiler/bar.ts === +/// +import {foo} from './foo'; +>foo : 1 + +void foo; +>void foo : undefined +>foo : 1 + diff --git a/tests/cases/compiler/declarationEmitAmdModuleNameDirective.ts b/tests/cases/compiler/declarationEmitAmdModuleNameDirective.ts new file mode 100644 index 00000000000..862e05f1726 --- /dev/null +++ b/tests/cases/compiler/declarationEmitAmdModuleNameDirective.ts @@ -0,0 +1,9 @@ +// @declaration: true +// @module: umd +// @filename: foo.ts +/// +export const foo = 1; +// @filename: bar.ts +/// +import {foo} from './foo'; +void foo; \ No newline at end of file From c861fa9202d7e5c3e30079cded2366271c02075e Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 13:48:24 -0700 Subject: [PATCH 67/75] Use 'map.get' instead of 'has' (#22998) --- src/compiler/checker.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7cfa500a326..89348b1b6c4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2503,11 +2503,8 @@ namespace ts { } const id = "" + getSymbolId(symbol); - let visitedSymbolTables: SymbolTable[]; - if (visitedSymbolTablesMap.has(id)) { - visitedSymbolTables = visitedSymbolTablesMap.get(id); - } - else { + let visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { visitedSymbolTablesMap.set(id, visitedSymbolTables = []); } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); From 3acafe5f4221469f27fcfea352101abbf87fa4ff Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 13:51:52 -0700 Subject: [PATCH 68/75] Consider property accesses in heritage clauses as type-space references for calculating type reference directives (#22746) --- src/compiler/checker.ts | 13 +++-- ...eclarationEmitHasTypesRefOnNamespaceUse.js | 52 +++++++++++++++++++ ...ationEmitHasTypesRefOnNamespaceUse.symbols | 15 ++++++ ...arationEmitHasTypesRefOnNamespaceUse.types | 15 ++++++ ...eclarationEmitHasTypesRefOnNamespaceUse.ts | 16 ++++++ 5 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.js create mode 100644 tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.symbols create mode 100644 tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.types create mode 100644 tests/cases/compiler/declarationEmitHasTypesRefOnNamespaceUse.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 89348b1b6c4..f8181198481 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -25982,18 +25982,23 @@ namespace ts { getJsxFactoryEntity: location => location ? (getJsxNamespace(location), (getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity }; + function isInHeritageClause(node: PropertyAccessEntityNameExpression) { + return node.parent && node.parent.kind === SyntaxKind.ExpressionWithTypeArguments && node.parent.parent && node.parent.parent.kind === SyntaxKind.HeritageClause; + } + // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node: EntityNameOrEntityNameExpression): string[] { // program does not have any files with type reference directives - bail out if (!fileToDirective) { return undefined; } - // property access can only be used as values + // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - const meaning = (node.kind === SyntaxKind.PropertyAccessExpression) || (node.kind === SyntaxKind.Identifier && isInTypeQuery(node)) - ? SymbolFlags.Value | SymbolFlags.ExportValue - : SymbolFlags.Type | SymbolFlags.Namespace; + let meaning = SymbolFlags.Type | SymbolFlags.Namespace; + if ((node.kind === SyntaxKind.Identifier && isInTypeQuery(node)) || (node.kind === SyntaxKind.PropertyAccessExpression && !isInHeritageClause(node))) { + meaning = SymbolFlags.Value | SymbolFlags.ExportValue; + } const symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; diff --git a/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.js b/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.js new file mode 100644 index 00000000000..c95366c765f --- /dev/null +++ b/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.js @@ -0,0 +1,52 @@ +//// [tests/cases/compiler/declarationEmitHasTypesRefOnNamespaceUse.ts] //// + +//// [dep.d.ts] +declare namespace NS { + interface Dep { + } +} +//// [package.json] +{ + "typings": "dep.d.ts" +} +//// [index.ts] +class Src implements NS.Dep { } + + +//// [index.js] +var Src = /** @class */ (function () { + function Src() { + } + return Src; +}()); + + +//// [index.d.ts] +/// +declare class Src implements NS.Dep { +} + + +//// [DtsFileErrors] + + +error TS2688: Cannot find type definition file for 'dep'. +/src/index.d.ts(1,23): error TS2688: Cannot find type definition file for 'dep'. +/src/index.d.ts(2,30): error TS2503: Cannot find namespace 'NS'. + + +!!! error TS2688: Cannot find type definition file for 'dep'. +==== /src/index.d.ts (2 errors) ==== + /// + ~~~ +!!! error TS2688: Cannot find type definition file for 'dep'. + declare class Src implements NS.Dep { + ~~ +!!! error TS2503: Cannot find namespace 'NS'. + } + +==== /deps/dep/dep.d.ts (0 errors) ==== + declare namespace NS { + interface Dep { + } + } \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.symbols b/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.symbols new file mode 100644 index 00000000000..cecacd39321 --- /dev/null +++ b/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.symbols @@ -0,0 +1,15 @@ +=== /src/index.ts === +class Src implements NS.Dep { } +>Src : Symbol(Src, Decl(index.ts, 0, 0)) +>NS.Dep : Symbol(NS.Dep, Decl(dep.d.ts, 0, 22)) +>NS : Symbol(NS, Decl(dep.d.ts, 0, 0)) +>Dep : Symbol(NS.Dep, Decl(dep.d.ts, 0, 22)) + +=== /deps/dep/dep.d.ts === +declare namespace NS { +>NS : Symbol(NS, Decl(dep.d.ts, 0, 0)) + + interface Dep { +>Dep : Symbol(Dep, Decl(dep.d.ts, 0, 22)) + } +} diff --git a/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.types b/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.types new file mode 100644 index 00000000000..33ae73c43d7 --- /dev/null +++ b/tests/baselines/reference/declarationEmitHasTypesRefOnNamespaceUse.types @@ -0,0 +1,15 @@ +=== /src/index.ts === +class Src implements NS.Dep { } +>Src : Src +>NS.Dep : any +>NS : any +>Dep : NS.Dep + +=== /deps/dep/dep.d.ts === +declare namespace NS { +>NS : any + + interface Dep { +>Dep : Dep + } +} diff --git a/tests/cases/compiler/declarationEmitHasTypesRefOnNamespaceUse.ts b/tests/cases/compiler/declarationEmitHasTypesRefOnNamespaceUse.ts new file mode 100644 index 00000000000..d95fbf3b64d --- /dev/null +++ b/tests/cases/compiler/declarationEmitHasTypesRefOnNamespaceUse.ts @@ -0,0 +1,16 @@ +// @declaration: true +// @types: dep +// @typeRoots: /deps +// @currentDirectory: / +// @noImplicitReferences: true +// @filename: /deps/dep/dep.d.ts +declare namespace NS { + interface Dep { + } +} +// @filename: /deps/dep/package.json +{ + "typings": "dep.d.ts" +} +// @filename: /src/index.ts +class Src implements NS.Dep { } From 793f4696a4b918dc35c103895b3c0dd3505163df Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 13:54:12 -0700 Subject: [PATCH 69/75] Fall back to check expression if resolving an export assigned entity name fails (#22928) * Fall back to check expression if resolving an export assigned entity name fails * Comments from code review * Add back in assertion * Remove nameNotFoundMessage check from resolveName isReferenced check (rely on just isUse instead) --- src/compiler/checker.ts | 25 ++++++++++++------- ...clarationEmitAliasFromIndirectFile.symbols | 1 + .../exportDefaultQualifiedNameNoError.js | 25 +++++++++++++++++++ .../exportDefaultQualifiedNameNoError.symbols | 17 +++++++++++++ .../exportDefaultQualifiedNameNoError.types | 19 ++++++++++++++ .../exportDefaultQualifiedNameNoError.ts | 6 +++++ 6 files changed, 84 insertions(+), 9 deletions(-) create mode 100644 tests/baselines/reference/exportDefaultQualifiedNameNoError.js create mode 100644 tests/baselines/reference/exportDefaultQualifiedNameNoError.symbols create mode 100644 tests/baselines/reference/exportDefaultQualifiedNameNoError.types create mode 100644 tests/cases/compiler/exportDefaultQualifiedNameNoError.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f8181198481..2639be7f16c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1432,7 +1432,7 @@ namespace ts { // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` 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 && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && noUnusedIdentifiers && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } @@ -1902,11 +1902,16 @@ namespace ts { resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } - function getTargetOfExportAssignment(node: ExportAssignment, dontResolveAlias: boolean): Symbol { - return resolveEntityName(node.expression, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, /*ignoreErrors*/ false, dontResolveAlias); + function getTargetOfExportAssignment(node: ExportAssignment, dontResolveAlias: boolean): Symbol | undefined { + const aliasLike = resolveEntityName(node.expression, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, /*ignoreErrors*/ true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(node.expression); + return getNodeLinks(node.expression).resolvedSymbol; } - function getTargetOfAliasDeclaration(node: Declaration, dontRecursivelyResolve?: boolean): Symbol { + function getTargetOfAliasDeclaration(node: Declaration, dontRecursivelyResolve?: boolean): Symbol | undefined { switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); @@ -25055,12 +25060,14 @@ namespace ts { } if (entityName.parent.kind === SyntaxKind.ExportAssignment && isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, - /*all meanings*/ SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression + const success = resolveEntityName(entityName, + /*all meanings*/ SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*ignoreErrors*/ true); + if (success && success !== unknownSymbol) { + return success; + } } - - if (entityName.kind !== SyntaxKind.PropertyAccessExpression && isInRightSideOfImportOrExportAssignment(entityName)) { - // Since we already checked for ExportAssignment, this really could only be an Import + else if (entityName.kind !== SyntaxKind.PropertyAccessExpression && isInRightSideOfImportOrExportAssignment(entityName)) { const importEqualsDeclaration = getAncestor(entityName, SyntaxKind.ImportEqualsDeclaration); Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); diff --git a/tests/baselines/reference/declarationEmitAliasFromIndirectFile.symbols b/tests/baselines/reference/declarationEmitAliasFromIndirectFile.symbols index 78dba37e97e..a6f76121e15 100644 --- a/tests/baselines/reference/declarationEmitAliasFromIndirectFile.symbols +++ b/tests/baselines/reference/declarationEmitAliasFromIndirectFile.symbols @@ -59,6 +59,7 @@ const fp = { l10ns: {} } as FlatpickrFn; >FlatpickrFn : Symbol(FlatpickrFn, Decl(app.ts, 0, 8)) export default fp.l10ns; +>fp.l10ns : Symbol(FlatpickrFn.l10ns, Decl(instance.d.ts, 1, 30)) >fp : Symbol(fp, Decl(app.ts, 1, 5)) >l10ns : Symbol(FlatpickrFn.l10ns, Decl(instance.d.ts, 1, 30)) diff --git a/tests/baselines/reference/exportDefaultQualifiedNameNoError.js b/tests/baselines/reference/exportDefaultQualifiedNameNoError.js new file mode 100644 index 00000000000..f0973d0716c --- /dev/null +++ b/tests/baselines/reference/exportDefaultQualifiedNameNoError.js @@ -0,0 +1,25 @@ +//// [tests/cases/compiler/exportDefaultQualifiedNameNoError.ts] //// + +//// [code.ts] +class C { static x = 0; }; +export default C.x; +//// [usage.ts] +import def from "./code"; +void def; + +//// [code.js] +"use strict"; +exports.__esModule = true; +var C = /** @class */ (function () { + function C() { + } + C.x = 0; + return C; +}()); +; +exports["default"] = C.x; +//// [usage.js] +"use strict"; +exports.__esModule = true; +var code_1 = require("./code"); +void code_1["default"]; diff --git a/tests/baselines/reference/exportDefaultQualifiedNameNoError.symbols b/tests/baselines/reference/exportDefaultQualifiedNameNoError.symbols new file mode 100644 index 00000000000..36b87d6fdcf --- /dev/null +++ b/tests/baselines/reference/exportDefaultQualifiedNameNoError.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/code.ts === +class C { static x = 0; }; +>C : Symbol(C, Decl(code.ts, 0, 0)) +>x : Symbol(C.x, Decl(code.ts, 0, 9)) + +export default C.x; +>C.x : Symbol(C.x, Decl(code.ts, 0, 9)) +>C : Symbol(C, Decl(code.ts, 0, 0)) +>x : Symbol(C.x, Decl(code.ts, 0, 9)) + +=== tests/cases/compiler/usage.ts === +import def from "./code"; +>def : Symbol(def, Decl(usage.ts, 0, 6)) + +void def; +>def : Symbol(def, Decl(usage.ts, 0, 6)) + diff --git a/tests/baselines/reference/exportDefaultQualifiedNameNoError.types b/tests/baselines/reference/exportDefaultQualifiedNameNoError.types new file mode 100644 index 00000000000..e9895c4443a --- /dev/null +++ b/tests/baselines/reference/exportDefaultQualifiedNameNoError.types @@ -0,0 +1,19 @@ +=== tests/cases/compiler/code.ts === +class C { static x = 0; }; +>C : C +>x : number +>0 : 0 + +export default C.x; +>C.x : number +>C : typeof C +>x : number + +=== tests/cases/compiler/usage.ts === +import def from "./code"; +>def : number + +void def; +>void def : undefined +>def : number + diff --git a/tests/cases/compiler/exportDefaultQualifiedNameNoError.ts b/tests/cases/compiler/exportDefaultQualifiedNameNoError.ts new file mode 100644 index 00000000000..2e8da0e4b7d --- /dev/null +++ b/tests/cases/compiler/exportDefaultQualifiedNameNoError.ts @@ -0,0 +1,6 @@ +// @filename: code.ts +class C { static x = 0; }; +export default C.x; +// @filename: usage.ts +import def from "./code"; +void def; \ No newline at end of file From 4309c0e7f8124a61937a170a0e702b96a2cbcac3 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 14:55:22 -0700 Subject: [PATCH 70/75] Fix bug: ClassDeclaration not guaranteed to be first declaration of a class (#22983) * Fix bug: ClassDeclaration not guaranteed to be first declaration of a class * fix test --- ...dMissingMember_classIsNotFirstDeclaration.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 tests/cases/fourslash/codeFixAddMissingMember_classIsNotFirstDeclaration.ts diff --git a/tests/cases/fourslash/codeFixAddMissingMember_classIsNotFirstDeclaration.ts b/tests/cases/fourslash/codeFixAddMissingMember_classIsNotFirstDeclaration.ts new file mode 100644 index 00000000000..2142c2e955c --- /dev/null +++ b/tests/cases/fourslash/codeFixAddMissingMember_classIsNotFirstDeclaration.ts @@ -0,0 +1,17 @@ +/// + +////interface C {} +////class C { +////} +////new C().x = 0; + +verify.codeFix({ + description: "Declare property 'x'", + index: 0, + newFileContent: +`interface C {} +class C { + x: number; +} +new C().x = 0;`, +}); From ea8904e33db38959139c7035c8afdea8d672a5c9 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 15:38:29 -0700 Subject: [PATCH 71/75] Propagate noDefaultLib comment into emitted declaration files (#23003) --- src/compiler/emitter.ts | 10 ++-- src/compiler/factory.ts | 7 +-- src/compiler/transformers/declarations.ts | 9 ++-- src/compiler/types.ts | 1 + .../reference/api/tsserverlibrary.d.ts | 2 +- tests/baselines/reference/api/typescript.d.ts | 2 +- ...BundlePreservesHasNoDefaultLibDirective.js | 48 +++++++++++++++++++ ...ePreservesHasNoDefaultLibDirective.symbols | 34 +++++++++++++ ...dlePreservesHasNoDefaultLibDirective.types | 34 +++++++++++++ ...onEmitPreservesHasNoDefaultLibDirective.js | 45 +++++++++++++++++ ...tPreservesHasNoDefaultLibDirective.symbols | 33 +++++++++++++ ...mitPreservesHasNoDefaultLibDirective.types | 33 +++++++++++++ ...BundlePreservesHasNoDefaultLibDirective.ts | 16 +++++++ ...onEmitPreservesHasNoDefaultLibDirective.ts | 13 +++++ 14 files changed, 276 insertions(+), 11 deletions(-) create mode 100644 tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.js create mode 100644 tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.symbols create mode 100644 tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.types create mode 100644 tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.js create mode 100644 tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.symbols create mode 100644 tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.types create mode 100644 tests/cases/compiler/declarationEmitBundlePreservesHasNoDefaultLibDirective.ts create mode 100644 tests/cases/compiler/declarationEmitPreservesHasNoDefaultLibDirective.ts diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 6fca3d897ac..23a74c8f1b7 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2473,14 +2473,18 @@ namespace ts { } function emitSyntheticTripleSlashReferencesIfNeeded(node: Bundle) { - emitTripleSlashDirectives(node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); } function emitTripleSlashDirectivesIfNeeded(node: SourceFile) { - if (node.isDeclarationFile) emitTripleSlashDirectives(node.referencedFiles, node.typeReferenceDirectives); + if (node.isDeclarationFile) emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); } - function emitTripleSlashDirectives(files: ReadonlyArray, types: ReadonlyArray) { + function emitTripleSlashDirectives(hasNoDefaultLib: boolean, files: ReadonlyArray, types: ReadonlyArray) { + if (hasNoDefaultLib) { + write(`/// `); + writeLine(); + } if (currentSourceFile && currentSourceFile.moduleName) { write(`/// `); writeLine(); diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index c64ce44dc6d..1b951c5b0b7 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2387,12 +2387,13 @@ namespace ts { // Top-level nodes - export function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]) { + export function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean) { if ( node.statements !== statements || (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || - (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib) ) { const updated = createSynthesizedNode(SyntaxKind.SourceFile); updated.flags |= node.flags; @@ -2404,11 +2405,11 @@ namespace ts { updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; - if (node.hasNoDefaultLib !== undefined) updated.hasNoDefaultLib = node.hasNoDefaultLib; if (node.languageVersion !== undefined) updated.languageVersion = node.languageVersion; if (node.scriptKind !== undefined) updated.scriptKind = node.scriptKind; if (node.externalModuleIndicator !== undefined) updated.externalModuleIndicator = node.externalModuleIndicator; diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 83128b9acb4..a7ecab0b4fe 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -135,9 +135,11 @@ namespace ts { if (node.kind === SyntaxKind.Bundle) { isBundledEmit = true; const refs = createMap(); + let hasNoDefaultLib = false; const bundle = createBundle(map(node.sourceFiles, sourceFile => { if (sourceFile.isDeclarationFile || isSourceFileJavaScript(sourceFile)) return; // Omit declaration files from bundle results, too + hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; possibleImports = undefined; @@ -154,16 +156,17 @@ namespace ts { [createModifier(SyntaxKind.DeclareKeyword)], createLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), createModuleBlock(setTextRange(createNodeArray(filterCandidateImports(statements)), sourceFile.statements)) - )], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + )], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); return newFile; } needsDeclare = true; const updated = visitNodes(sourceFile.statements, visitDeclarationStatements); - return updateSourceFileNode(sourceFile, updated, /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + return updateSourceFileNode(sourceFile, updated, /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); } )); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib; const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); const referenceVisitor = mapReferencesIntoArray(bundle.syntheticFileReferences as FileReference[], outputFilePath); refs.forEach(referenceVisitor); @@ -191,7 +194,7 @@ namespace ts { if (isExternalModule(node) && !resultHasExternalModuleIndicator) { combinedStatements = setTextRange(createNodeArray([...combinedStatements, createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined)]), combinedStatements); } - const updated = updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences()); + const updated = updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); return updated; function getFileReferencesForUsedTypeReferences() { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 801d44e2012..83b3dde7aa7 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2590,6 +2590,7 @@ namespace ts { sourceFiles: ReadonlyArray; /* @internal */ syntheticFileReferences?: ReadonlyArray; /* @internal */ syntheticTypeReferences?: ReadonlyArray; + /* @internal */ hasNoDefaultLib?: boolean; } export interface JsonSourceFile extends SourceFile { diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 10d6f31408b..b859f9f1876 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -3714,7 +3714,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]): SourceFile; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 26b942f6d81..d9381742cc3 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -3661,7 +3661,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]): SourceFile; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ diff --git a/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.js b/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.js new file mode 100644 index 00000000000..94e9f627e93 --- /dev/null +++ b/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.js @@ -0,0 +1,48 @@ +//// [tests/cases/compiler/declarationEmitBundlePreservesHasNoDefaultLibDirective.ts] //// + +//// [extensions.ts] +/// +class Foo { + public: string; +} +//// [core.ts] +interface Array {} +interface Boolean {} +interface Function {} +interface IArguments {} +interface Number {} +interface Object {} +interface RegExp {} +interface String {} + + +//// [mylib.js] +/// +var Foo = /** @class */ (function () { + function Foo() { + } + return Foo; +}()); + + +//// [mylib.d.ts] +/// +declare class Foo { + public: string; +} +interface Array { +} +interface Boolean { +} +interface Function { +} +interface IArguments { +} +interface Number { +} +interface Object { +} +interface RegExp { +} +interface String { +} diff --git a/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.symbols b/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.symbols new file mode 100644 index 00000000000..3819cefebcb --- /dev/null +++ b/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.symbols @@ -0,0 +1,34 @@ +=== tests/cases/compiler/extensions.ts === +/// +class Foo { +>Foo : Symbol(Foo, Decl(extensions.ts, 0, 0)) + + public: string; +>public : Symbol(Foo.public, Decl(extensions.ts, 1, 11)) +} +=== tests/cases/compiler/core.ts === +interface Array {} +>Array : Symbol(Array, Decl(core.ts, 0, 0)) +>T : Symbol(T, Decl(core.ts, 0, 16)) + +interface Boolean {} +>Boolean : Symbol(Boolean, Decl(core.ts, 0, 21)) + +interface Function {} +>Function : Symbol(Function, Decl(core.ts, 1, 20)) + +interface IArguments {} +>IArguments : Symbol(IArguments, Decl(core.ts, 2, 21)) + +interface Number {} +>Number : Symbol(Number, Decl(core.ts, 3, 23)) + +interface Object {} +>Object : Symbol(Object, Decl(core.ts, 4, 19)) + +interface RegExp {} +>RegExp : Symbol(RegExp, Decl(core.ts, 5, 19)) + +interface String {} +>String : Symbol(String, Decl(core.ts, 6, 19)) + diff --git a/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.types b/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.types new file mode 100644 index 00000000000..3b5f0685ce9 --- /dev/null +++ b/tests/baselines/reference/declarationEmitBundlePreservesHasNoDefaultLibDirective.types @@ -0,0 +1,34 @@ +=== tests/cases/compiler/extensions.ts === +/// +class Foo { +>Foo : Foo + + public: string; +>public : string +} +=== tests/cases/compiler/core.ts === +interface Array {} +>Array : T[] +>T : T + +interface Boolean {} +>Boolean : Boolean + +interface Function {} +>Function : Function + +interface IArguments {} +>IArguments : IArguments + +interface Number {} +>Number : Number + +interface Object {} +>Object : Object + +interface RegExp {} +>RegExp : RegExp + +interface String {} +>String : String + diff --git a/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.js b/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.js new file mode 100644 index 00000000000..b71b5ed3ded --- /dev/null +++ b/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.js @@ -0,0 +1,45 @@ +//// [declarationEmitPreservesHasNoDefaultLibDirective.ts] +/// +class Foo { + public: string; +} +interface Array {} +interface Boolean {} +interface Function {} +interface IArguments {} +interface Number {} +interface Object {} +interface RegExp {} +interface String {} + + +//// [declarationEmitPreservesHasNoDefaultLibDirective.js] +/// +var Foo = /** @class */ (function () { + function Foo() { + } + return Foo; +}()); + + +//// [declarationEmitPreservesHasNoDefaultLibDirective.d.ts] +/// +declare class Foo { + public: string; +} +interface Array { +} +interface Boolean { +} +interface Function { +} +interface IArguments { +} +interface Number { +} +interface Object { +} +interface RegExp { +} +interface String { +} diff --git a/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.symbols b/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.symbols new file mode 100644 index 00000000000..d271cb33a73 --- /dev/null +++ b/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.symbols @@ -0,0 +1,33 @@ +=== tests/cases/compiler/declarationEmitPreservesHasNoDefaultLibDirective.ts === +/// +class Foo { +>Foo : Symbol(Foo, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 0, 0)) + + public: string; +>public : Symbol(Foo.public, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 1, 11)) +} +interface Array {} +>Array : Symbol(Array, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 3, 1)) +>T : Symbol(T, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 4, 16)) + +interface Boolean {} +>Boolean : Symbol(Boolean, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 4, 21)) + +interface Function {} +>Function : Symbol(Function, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 5, 20)) + +interface IArguments {} +>IArguments : Symbol(IArguments, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 6, 21)) + +interface Number {} +>Number : Symbol(Number, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 7, 23)) + +interface Object {} +>Object : Symbol(Object, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 8, 19)) + +interface RegExp {} +>RegExp : Symbol(RegExp, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 9, 19)) + +interface String {} +>String : Symbol(String, Decl(declarationEmitPreservesHasNoDefaultLibDirective.ts, 10, 19)) + diff --git a/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.types b/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.types new file mode 100644 index 00000000000..723cc766795 --- /dev/null +++ b/tests/baselines/reference/declarationEmitPreservesHasNoDefaultLibDirective.types @@ -0,0 +1,33 @@ +=== tests/cases/compiler/declarationEmitPreservesHasNoDefaultLibDirective.ts === +/// +class Foo { +>Foo : Foo + + public: string; +>public : string +} +interface Array {} +>Array : T[] +>T : T + +interface Boolean {} +>Boolean : Boolean + +interface Function {} +>Function : Function + +interface IArguments {} +>IArguments : IArguments + +interface Number {} +>Number : Number + +interface Object {} +>Object : Object + +interface RegExp {} +>RegExp : RegExp + +interface String {} +>String : String + diff --git a/tests/cases/compiler/declarationEmitBundlePreservesHasNoDefaultLibDirective.ts b/tests/cases/compiler/declarationEmitBundlePreservesHasNoDefaultLibDirective.ts new file mode 100644 index 00000000000..79ebb3c9387 --- /dev/null +++ b/tests/cases/compiler/declarationEmitBundlePreservesHasNoDefaultLibDirective.ts @@ -0,0 +1,16 @@ +// @declaration: true +// @outFile: mylib.js +// @filename: extensions.ts +/// +class Foo { + public: string; +} +// @filename: core.ts +interface Array {} +interface Boolean {} +interface Function {} +interface IArguments {} +interface Number {} +interface Object {} +interface RegExp {} +interface String {} diff --git a/tests/cases/compiler/declarationEmitPreservesHasNoDefaultLibDirective.ts b/tests/cases/compiler/declarationEmitPreservesHasNoDefaultLibDirective.ts new file mode 100644 index 00000000000..8cb0e82b048 --- /dev/null +++ b/tests/cases/compiler/declarationEmitPreservesHasNoDefaultLibDirective.ts @@ -0,0 +1,13 @@ +// @declaration: true +/// +class Foo { + public: string; +} +interface Array {} +interface Boolean {} +interface Function {} +interface IArguments {} +interface Number {} +interface Object {} +interface RegExp {} +interface String {} From 4a39caffd4dc11a28f343566cf5933784c9d8f5d Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 15:40:25 -0700 Subject: [PATCH 72/75] Use isExternalModuleImportEquals in one more place (#22417) --- src/services/importTracker.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index b5ffaaf9cea..de8a49243fa 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -394,18 +394,16 @@ namespace ts.FindAllReferences { case SyntaxKind.ExportDeclaration: case SyntaxKind.ImportDeclaration: { const decl = statement as ImportDeclaration | ExportDeclaration; - if (decl.moduleSpecifier && decl.moduleSpecifier.kind === SyntaxKind.StringLiteral) { - action(decl, decl.moduleSpecifier as StringLiteral); + if (decl.moduleSpecifier && isStringLiteral(decl.moduleSpecifier)) { + action(decl, decl.moduleSpecifier); } break; } case SyntaxKind.ImportEqualsDeclaration: { const decl = statement as ImportEqualsDeclaration; - const { moduleReference } = decl; - if (moduleReference.kind === SyntaxKind.ExternalModuleReference && - moduleReference.expression.kind === SyntaxKind.StringLiteral) { - action(decl, moduleReference.expression as StringLiteral); + if (isExternalModuleImportEquals(decl)) { + action(decl, decl.moduleReference.expression); } break; } @@ -647,7 +645,7 @@ namespace ts.FindAllReferences { return node.kind === SyntaxKind.ModuleDeclaration && (node as ModuleDeclaration).name.kind === SyntaxKind.StringLiteral; } - function isExternalModuleImportEquals({ moduleReference }: ImportEqualsDeclaration): boolean { - return moduleReference.kind === SyntaxKind.ExternalModuleReference && moduleReference.expression.kind === SyntaxKind.StringLiteral; + function isExternalModuleImportEquals(eq: ImportEqualsDeclaration): eq is ImportEqualsDeclaration & { moduleReference: { expression: StringLiteral } } { + return eq.moduleReference.kind === SyntaxKind.ExternalModuleReference && eq.moduleReference.expression.kind === SyntaxKind.StringLiteral; } } From 5cef6274c32d525715b2201f920c587927d6bb04 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 15:43:31 -0700 Subject: [PATCH 73/75] Remove duplicate helper function (#23001) --- src/compiler/core.ts | 2 +- src/compiler/program.ts | 13 ++++--------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index b08d897b35c..017d3545206 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -2909,7 +2909,7 @@ namespace ts { return value; } - export function assertEachDefined>(value: A, message: string): A { + export function assertEachDefined>(value: A, message?: string): A { for (const v of value) { assertDefined(v, message); } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 4a7a5580dbe..342b697b977 100755 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -546,7 +546,7 @@ namespace ts { let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[]) => ResolvedModuleFull[]; const hasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames) => host.resolveModuleNames(checkAllDefined(moduleNames), containingFile, reusedNames).map(resolved => { + resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames) => host.resolveModuleNames(Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(resolved => { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) { return resolved as ResolvedModuleFull; @@ -559,16 +559,16 @@ namespace ts { else { moduleResolutionCache = createModuleResolutionCache(currentDirectory, x => host.getCanonicalFileName(x)); const loader = (moduleName: string, containingFile: string) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; - resolveModuleNamesWorker = (moduleNames, containingFile) => loadWithLocalCache(checkAllDefined(moduleNames), containingFile, loader); + resolveModuleNamesWorker = (moduleNames, containingFile) => loadWithLocalCache(Debug.assertEachDefined(moduleNames), containingFile, loader); } let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives(checkAllDefined(typeDirectiveNames), containingFile); + resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives(Debug.assertEachDefined(typeDirectiveNames), containingFile); } else { const loader = (typesRef: string, containingFile: string) => resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; - resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile) => loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader); + resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile) => loadWithLocalCache(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader); } // Map from a stringified PackageId to the source file with that id. @@ -2428,11 +2428,6 @@ namespace ts { } } - function checkAllDefined(names: string[]): string[] { - Debug.assert(names.every(name => name !== undefined), "A name is undefined.", () => JSON.stringify(names)); - return names; - } - function getModuleNames({ imports, moduleAugmentations }: SourceFile): string[] { const res = imports.map(i => i.text); for (const aug of moduleAugmentations) { From 09cfc0f9efe5d2fa73f2c3b02621be1e27ecfee4 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 29 Mar 2018 15:44:06 -0700 Subject: [PATCH 74/75] Remove unused method (#23000) --- src/compiler/types.ts | 9 +-------- src/compiler/utilities.ts | 7 ------- 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 83b3dde7aa7..8d497758cfa 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -5093,14 +5093,7 @@ namespace ts { // Otherwise, returns all the diagnostics (global and file associated) in this collection. getDiagnostics(fileName?: string): Diagnostic[]; - // Gets a count of how many times this collection has been modified. This value changes - // each time 'add' is called (regardless of whether or not an equivalent diagnostic was - // already in the collection). As such, it can be used as a simple way to tell if any - // operation caused diagnostics to be returned by storing and comparing the return value - // of this method before/after the operation is performed. - getModificationCount(): number; - - /* @internal */ reattachFileDiagnostics(newFile: SourceFile): void; + reattachFileDiagnostics(newFile: SourceFile): void; } // SyntaxKind.SyntaxList diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 4f9dcf69310..9a6fbcc8c21 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2557,20 +2557,14 @@ namespace ts { const filesWithDiagnostics = [] as SortedArray; const fileDiagnostics = createMap>(); let hasReadNonFileDiagnostics = false; - let modificationCount = 0; return { add, getGlobalDiagnostics, getDiagnostics, - getModificationCount, reattachFileDiagnostics }; - function getModificationCount() { - return modificationCount; - } - function reattachFileDiagnostics(newFile: SourceFile): void { forEach(fileDiagnostics.get(newFile.fileName), diagnostic => diagnostic.file = newFile); } @@ -2596,7 +2590,6 @@ namespace ts { } insertSorted(diagnostics, diagnostic, compareDiagnostics); - modificationCount++; } function getGlobalDiagnostics(): Diagnostic[] { From 3189d1732c54b1740db1801ea740f6552eabad6b Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 29 Mar 2018 15:45:17 -0700 Subject: [PATCH 75/75] Handful more usages of emitIfPresent on optional nodes (#22274) --- src/compiler/emitter.ts | 18 +++++++++--------- src/harness/unittests/printer.ts | 2 ++ ...eCorrectly.importStatementRemoveComments.js | 1 + 3 files changed, 12 insertions(+), 9 deletions(-) create mode 100644 tests/baselines/reference/printerApi/printsFileCorrectly.importStatementRemoveComments.js diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 23a74c8f1b7..34fef4e431f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -568,7 +568,7 @@ namespace ts { writeSpace(); writeKeyword("in"); writeSpace(); - emit(node.constraint); + emitIfPresent(node.constraint); } function pipelineEmitUnspecified(node: Node): void { @@ -1046,7 +1046,7 @@ namespace ts { } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === SyntaxKind.JSDocFunctionType && !node.name) { - emit(node.type); + emitIfPresent(node.type); } else { emitTypeAnnotation(node.type); @@ -1174,14 +1174,14 @@ namespace ts { writeSpace(); writePunctuation("=>"); writeSpace(); - emit(node.type); + emitIfPresent(node.type); } function emitJSDocFunctionType(node: JSDocFunctionType) { write("function"); emitParameters(node, node.parameters); write(":"); - emit(node.type); + emitIfPresent(node.type); } @@ -1208,7 +1208,7 @@ namespace ts { writeSpace(); writePunctuation("=>"); writeSpace(); - emit(node.type); + emitIfPresent(node.type); } function emitTypeQuery(node: TypeQueryNode) { @@ -1322,7 +1322,7 @@ namespace ts { } writePunctuation(":"); writeSpace(); - emit(node.type); + emitIfPresent(node.type); writeSemicolon(); if (emitFlags & EmitFlags.SingleLine) { writeSpace(); @@ -1593,7 +1593,7 @@ namespace ts { function emitYieldExpression(node: YieldExpression) { emitTokenWithComment(SyntaxKind.YieldKeyword, node.pos, writeKeyword, node); - emit(node.asteriskToken); + emitIfPresent(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } @@ -2156,12 +2156,12 @@ namespace ts { } function emitImportClause(node: ImportClause) { - emit(node.name); + emitIfPresent(node.name); if (node.name && node.namedBindings) { emitTokenWithComment(SyntaxKind.CommaToken, node.name.end, writePunctuation, node); writeSpace(); } - emit(node.namedBindings); + emitIfPresent(node.namedBindings); } function emitNamespaceImport(node: NamespaceImport) { diff --git a/src/harness/unittests/printer.ts b/src/harness/unittests/printer.ts index 69b8f011626..6392fd3e9f3 100644 --- a/src/harness/unittests/printer.ts +++ b/src/harness/unittests/printer.ts @@ -63,6 +63,8 @@ namespace ts { // github #18071 printsCorrectly("regularExpressionLiteral", {}, printer => printer.printFile(createSourceFile("source.ts", "let regex = /abc/;", ScriptTarget.ES2017))); + // github #22239 + printsCorrectly("importStatementRemoveComments", { removeComments: true }, printer => printer.printFile(createSourceFile("source.ts", "import {foo} from 'foo';", ScriptTarget.ESNext))); printsCorrectly("classHeritageClauses", {}, printer => printer.printFile(createSourceFile( "source.ts", `class A extends B implements C implements D {}`, diff --git a/tests/baselines/reference/printerApi/printsFileCorrectly.importStatementRemoveComments.js b/tests/baselines/reference/printerApi/printsFileCorrectly.importStatementRemoveComments.js new file mode 100644 index 00000000000..76edef681d3 --- /dev/null +++ b/tests/baselines/reference/printerApi/printsFileCorrectly.importStatementRemoveComments.js @@ -0,0 +1 @@ +import { foo } from "foo";