Compare commits

...

68 commits

Author SHA1 Message Date
TypeScript Bot 90600e1b17 Update package-lock.json 2021-11-24 06:07:09 +00:00
Daniel Rosenwasser a90389a22d
Switch deferredNodes from a Map to a Set. (#46751) 2021-11-23 17:46:33 -08:00
TypeScript Bot 0163a624b7 Update package-lock.json 2021-11-20 06:06:42 +00:00
TypeScript Bot 9766757ee6 Update package-lock.json 2021-11-19 06:06:13 +00:00
Nathan Shively-Sanders 868c275fdf
Plain JS binder errors (#46816)
* Plain JS binder errors

Issue select errors from the binder in JS files that do not have checkJS
explicitly turned on or off. These errors mirror runtime checks done by
Javascript.

* Rest of plain JS binder errors

* address PR comments

* Only issue binder errors in plain JS.

Checker errors require requesting diagnostics, which stll needs to be
peformance tested.

This commit removes one cross-file duplicate declaration error in the tests.

* fix const lint
2021-11-18 17:13:06 -08:00
Oleksandr T 6143237376
fix(46366): handle enum string access as enumMemberName (#46431) 2021-11-18 15:50:32 -08:00
Andrew Casey 1ade73df2b
Stop calling our own @deprecrated APIs (#46831)
* Clean up createMap

* Delete dead createMapFromTemplate

* Clean up assertDefined

* Delete dead assertEachDefined

* Delete dead createUnderscoreEscapedMap

* Delete dead hasEntries

* Delete dead ReadonlyNodeSet, NodeSet, ReadonlyNodeMap, NodeMap

* Use updated SyntaxKind names

* Update API baselines
2021-11-18 10:37:55 -08:00
Zzzen de4ba0f208
enable go-to-type-definition on type nodes (#46714)
* enable go-to-type-definition on type nodes

* only go when symbol has no value meaning

* Update formatting of src/services/goToDefinition.ts

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2021-11-18 08:55:54 -08:00
Oleksandr T a75f26e68b
fix(42238): emit this parameter in function declaration (#46511) 2021-11-17 15:43:27 -08:00
Andrew Branch f11f14baba
Fix broken module resolution after large/rapid edits in nodenext (#46818)
* Fix broken module resolution after edits in nodenext

* Move field copying to a better place I guess
2021-11-17 13:04:43 -08:00
Andrew Branch 009dd487a6
Update symlink cache from AutoImportProvider resolution even if host project already contains the file via its realpath (#46830) 2021-11-16 16:39:10 -08:00
Wesley Wigham 0bf97296d6
Allow nightly-only flags in -insiders builds (#46829) 2021-11-16 12:53:37 -08:00
Kevin Tan fcdbc932bf
implement code fix for override of js files (#45780)
* feat: code fix for override in js files

Co-Authored-By: Wenlu Wang <kingwenlu@gmail.com>

* fix comments

Co-Authored-By: Wenlu Wang <kingwenlu@gmail.com>

* remove tryMergeJsdocTags

* fix: bring the two methods back as functions

* revert emitter changes

* fix comments

* fix: test failures

Co-authored-by: Wenlu Wang <kingwenlu@gmail.com>
Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2021-11-16 08:01:43 -08:00
TypeScript Bot 7615547d42 Update package-lock.json 2021-11-15 06:06:28 +00:00
Oleksandr T 719ab0b477
fix(43359): emit default exports with named exports that have the same names with types (#44718) 2021-11-12 11:25:52 -08:00
Mohammad Aziz fe3e117cb2
fix(46712): Add "exceptZero" for "signDisplay" option of Intl.NumberFormat() (#46740) 2021-11-12 11:12:21 +00:00
Andrew Branch 1298f498f4
Revert changes to matchFiles/readDirectory made since 4.3 (#46787)
* Revert "Fix RWC missing file detection (#46673)"

This reverts commit 4a065f524c.

* Revert "Pass absolute path to directoryExists (#46086)"

This reverts commit 55b4928e82.

* Revert "Reduce exceptions (#44710)"

This reverts commit c0d5c29080.

* Add back system watcher limit
2021-11-11 15:24:20 -08:00
Armando Aguirre 7b86a65f22
Removed replacement from jsx completions (#46767)
* Removed replacement from jsx completions

* Fixed tests
2021-11-10 18:18:15 -08:00
Oleksandr T b12d5c5dc5
fix(46605): show completions in object literal parameters (#46743) 2021-11-09 14:50:26 -08:00
Daniel Rosenwasser 416571ca90
Remove unnecessary annotations/casts/aliases (#46727)
* Remove unnecessary annotation.

* Remove more unnecessary stuff.

* Remove unnecessary assertion.
2021-11-09 12:17:54 -08:00
Gabriela Araujo Britto e5a6ae397d
Fix extra newline in class member snippet completions (#46737)
* fix extra newline

* fix test
2021-11-09 12:03:07 -08:00
Wesley Wigham 4a065f524c
Fix RWC missing file detection (#46673) 2021-11-09 10:41:18 -08:00
TypeScript Bot e040e8516f Update package-lock.json 2021-11-09 06:06:42 +00:00
Oleksandr T a05d851dc3
fix(45907): don't use static member name to inherit JSDocs from instance members (#46274) 2021-11-08 15:05:08 -08:00
Nathan Shively-Sanders 9713cc1a75
Big[U]Int64Array.at returns bigint, not number (#46733)
bigint is needed to represent all 64-bit ints that these arrays could
contain.
2021-11-08 09:50:02 -08:00
Oleksandr T 3ef3cdddb3
fix(45692): merge non-primitive in spread-union (#45729) 2021-11-05 15:41:06 -07:00
Oleksandr T 0a628ff0c9
fix(44059): omit duplicate types (#45739) 2021-11-05 15:36:08 -07:00
Oleksandr T 2d4b243195
fix(33325): allow extract refactoring on selected statement without trailing semicolon (#45765) 2021-11-05 10:00:31 -07:00
Oleksandr T 4fca1e1fcd
fix(46666): add outlining spans for comments preceding call expressions (#46682) 2021-11-04 12:43:01 -07:00
Kagami Sascha Rosylight ae582a22ee
Add target: "es2022" (#46291)
* Add `target: "es2022"`

* Add Object.hasOwn

* formatToParts is es2018

* ref update

* optional parameter

* Revert "optional parameter"

This reverts commit e67d6e5f60.

* undefined

* error cause

* Lint fix

Co-authored-by: Orta <git@orta.io>
2021-11-04 10:55:11 -07:00
Oleksandr T ff75b8a180
fix(46615): remove useless assertion. change error suggestion for rest params (#46628) 2021-11-03 14:11:39 -07:00
Wesley Wigham d53630fac3
Make specifier generation from export map information conditional on module resolution mode (#46670) 2021-11-03 13:10:44 -07:00
Oleksandr T 7264cf7db5
fix(46589): omit ? in method signature completion for optional methods (#46594) 2021-11-03 12:56:17 -07:00
Andrew Casey e2f47a2db1
Duplicate GDPR fragment from VS Code repo (#46625)
* Duplicate GDPR fragment from VS Code repo

...because the tool doesn't handle cross-repro references.

* Explain functionality in more detail
2021-11-03 10:37:31 -07:00
Anders Hejlsberg 831b770b95
Control flow analysis for destructured discriminated unions (#46266)
* CFA for dependent variables destructured from discriminated union

* Accept new baselines

* Add tests

* Limit calls to isSymbolAssigned

* Fix wrong operator
2021-11-02 15:48:13 -07:00
Wesley Wigham de23842e45
Allow import assertions on esm imports under module: nodenext (#46630)
* Allow import assertions on esm imports under module: nodenext

* Changes to copy

Co-authored-by: Andrew Branch <andrew@wheream.io>
2021-11-02 15:34:37 -07:00
Oleksandr T b8f8fd7a3e
fix(46512): allow to use tag names containing keywords with - (#46546) 2021-11-02 15:12:10 -07:00
Anders Hejlsberg 33fe1b6ffc
Fix contextual typing for symbol-named properties (#46558)
* Properly handle symbol-named properties in contextual types

* Update index signature in PropertyDescriptorMap

* Add regression tests
2021-11-02 14:05:41 -07:00
Anders Hejlsberg 373accf28f
Improve recursion depth checks (#46599)
* Decrease recursion depth limit to 3 + smarter check for recursion

* Accept new baselines

* Always set last type id

* Keep indexed access recursion depth check

* Less expensive and corrected check for broadest equivalent keys
2021-11-02 14:05:17 -07:00
Anders Hejlsberg 56f81075f9
Properly check whether union type contains only primitive types (#46645)
* Properly check whether union type contains only primitive types

* Add regression test

* Remove 'export' modifier from test
2021-11-02 12:46:26 -07:00
Andrew Branch 7f8bf0b9c4
Fix git remote in cherry pick script (#46647) 2021-11-02 12:39:42 -07:00
Anders Hejlsberg 7cbcfeea99
Exclude identity relation from mapped type relation check (#46632)
* Exclude identity relation from mapped type relation check

* Add regression test
2021-11-02 06:54:35 -07:00
TypeScript Bot 2424d0e575 Update package-lock.json 2021-11-02 06:06:22 +00:00
Oleksandr T 5142e37f2d
fix(43292): forbid highlighting multiline template strings (#46531) 2021-11-01 14:21:38 -07:00
Eli Barzilay fa2ad1a35a Fix findUpDir.ts and uses
Missed a bunch of stuff in #46414 (556098e).
2021-11-01 16:45:49 -04:00
Daniel Rosenwasser d89076381e
Bump version to 4.6 and accept baselines. (#46612) 2021-11-01 11:45:22 -07:00
Daniel Rosenwasser 6d33d8797b
Check for type parameters on original type when getting type argument completions (#46614)
* Add failing test.

* Check for type parameters on the original type when asking for the type argument constraint.

* Update tests/cases/fourslash/stringLiteralTypeCompletionsInTypeArgForNonGeneric1.ts
2021-11-01 11:41:43 -07:00
csigs bf6d164bd5
LEGO: Merge pull request 46601
LEGO: Merge pull request 46601
2021-10-29 22:17:49 -07:00
Gabriela Araujo Britto 6b1e8f7baf
remove placeholders in class member snippets (#46598) 2021-10-29 16:55:59 -07:00
csigs e3fab9fc20
LEGO: Merge pull request 46597
LEGO: Merge pull request 46597
2021-10-29 16:13:23 -07:00
Andrew Branch 7742cf2180
Set hasAddedOrRemovedSymlinks when discovering an existing file by its link (#46569)
* Set hasAddedOrRemovedSymlinks when discovering an existing file by its link

* Make it optional
2021-10-29 15:47:48 -07:00
Andrew Branch eeaa595196
Enable auto imports in member snippet completions (#46592) 2021-10-29 14:43:32 -07:00
Anders Hejlsberg b0ab2a54bb
Fix mapped type instantiation circularity (#46586)
* Don't obtain constraint if doing so would cause circularity

* Add regression test

* Address CR feedback
2021-10-29 14:01:27 -07:00
Wesley Wigham 28e3cd3a80
Add error on new module/moduleResolution modes when used in non-nightly TS (#46557)
* Add error on new module/moduleResolution modes when used in non-nightly TS

* Update diagnostic
2021-10-29 11:46:19 -07:00
Jack Bates 9b1ba8f1e3
Fix react-jsx spread children invalid emit (#46565)
* Fix react-jsx spread children invalid emit

* Update Baselines and/or Applied Lint Fixes

* Change childrenLength parameter -> isStaticChildren

Co-authored-by: TypeScript Bot <typescriptbot@microsoft.com>
2021-10-29 10:54:46 -07:00
Andrew Casey 325435891a
Update GDPR comment formatting (#46585)
...so that they are picked up properly by the tooling.
2021-10-29 10:48:28 -07:00
Gabriela Araujo Britto 9cdbb7248b
Improve errors on module: node12 and extensionless relative imports (#46486)
* add new error + suggestions

* push down assert defined

* remove comment

* fix esm module import detection, update baselines

* add and update new tests

* fix review comments

* remove renamed baseline references

* update node modules test baselines

* fix error message, add new tests

* update old tests with new error message
2021-10-29 10:25:03 -07:00
csigs f1a69ec93e
LEGO: Merge pull request 46584
LEGO: Merge pull request 46584
2021-10-29 10:14:21 -07:00
Gabriela Araujo Britto fd620c93f6
Add method signature completions (#46370)
* prototype creation for method override completion snippet

* WIP: start using codefix `addNewNodeForMemberSymbol` to create method decl node

* update type of addNewNodeForMemberSymbol

* add more tests and support more cases

* add more tests and fix some details

* wip: more fixes and tests

* expose check override modifier in checker

* fix test

* WIP: add snippet support

* WIP: snippet support on emitter, adding snippets in completions

* make add snippets work with overloads (not synced)

* fix snippet adding

* rebase

* WIP: try to add snippet escaping in emitter

* support escaping in snippets

* small fixes; fixed tests

* more tests and fixes

* fix new tests

* fix modifier inheritance for overloads

* merge conflict fixes; remove comments

* throw error if setOptions is called but not implemented

* fix newline handling

* fix weird stuff

* fix tests

* fix more tests

* Fix unbound host.getNewLine

* fix isParameterDeclaration changes

* rename diagnostic to status and remove snippets from public api

* rename emitter functions + fix indentation

* check completion kind before calling isclasslikemembercompletion

* fix missing type parameters

* Revert "fix missing type parameters"

This reverts commit 7bdeaa86da.

* add isAmbient flag to addNewNodeForMemberSymbol

* add test for abstract overloads

* refactor snippet escaping support

* add user preference flag for enabling class member snippets

* update API baseline

* update tabstop order

Co-authored-by: Andrew Branch <andrewbranch@users.noreply.github.com>
2021-10-28 16:05:36 -07:00
csigs 566758d6cb
LEGO: Merge pull request 46566
LEGO: Merge pull request 46566
2021-10-28 10:13:44 -07:00
TypeScript Bot 4e237ed66f
🤖 Update TypeScript DOM Libs (#46222)
Co-authored-by: orta <orta@users.noreply.github.com>
2021-10-28 09:14:26 -07:00
TypeScript Bot 8173afbb8a Update package-lock.json 2021-10-28 06:06:31 +00:00
Daniel Rosenwasser f494742ce9
Check for array types when instantiating mapped type constraints with any (#46218)
* Added/updated tests.

* Accepted baselines.

* Update test.

* Update instantiateMappedType to work specially when 'any' replaced an array.

* Accepted baselines.

* Ensure check works when constraint is a union of arrayish types, just like in `Promise.all`.

* Accepted baselines.

* Update test for indirect instantiation of a mapped type.

* Accepted baselines.

* Update test comment.

* Accepted baselines.

* Added tuple test case.

* Accepted baselines.

* Don't add special behavior for tuples.

* Accepted baselines.

* Revert "Don't add special behavior for tuples."

This reverts commit f01ae16e65.

* Accepted baselines.
2021-10-27 15:03:01 -07:00
Wesley Wigham abfd537503
Support resolveJsonModule in new module modes (#46434)
* Support resolveJsonModule in new module modes

* Formatting feedback
2021-10-27 12:30:06 -07:00
Zzzen 8a68c8616d
allow typeof this after for-loops (#46181) 2021-10-27 10:26:05 -07:00
Anders Hejlsberg f424dfc18a
Slightly less conservative check in isConstraintPosition (#46526)
* Slight adjustment to check in isConstraintPosition

* Add regression test
2021-10-26 11:54:46 -07:00
Anders Hejlsberg 44c63a757e
Always cache relations involving intersection types (#46523)
* Always cache relations involving intersection types

* Accept new baselines

* Add regression test
2021-10-26 09:36:19 -07:00
Anders Hejlsberg 658764e499
Bypass caching in removeStringLiteralsMatchedByTemplateLiterals (#46525)
* Bypass caching in removeStringLiteralsMatchedByTemplateLiterals

* Add regression test
2021-10-26 09:34:15 -07:00
386 changed files with 11119 additions and 1649 deletions

26
package-lock.json generated
View file

@ -1,6 +1,6 @@
{ {
"name": "typescript", "name": "typescript",
"version": "4.5.0", "version": "4.6.0",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
@ -676,9 +676,9 @@
"dev": true "dev": true
}, },
"@types/node": { "@types/node": {
"version": "16.11.6", "version": "16.11.10",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.6.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.10.tgz",
"integrity": "sha512-ua7PgUoeQFjmWPcoo9khiPum3Pd60k4/2ZGXt18sm2Slk0W0xZTqt5Y0Ny1NyBiN1EVQ/+FaF9NcY4Qe6rwk5w==", "integrity": "sha512-3aRnHa1KlOEEhJ6+CvyHKK5vE9BcLGjtUpwvqYLRvYNQKMfabu3BwfJaA/SLW8dxe28LsNDjtHwePTuzn3gmOA==",
"dev": true "dev": true
}, },
"@types/node-fetch": { "@types/node-fetch": {
@ -1316,9 +1316,9 @@
"dev": true "dev": true
}, },
"async": { "async": {
"version": "3.2.1", "version": "3.2.2",
"resolved": "https://registry.npmjs.org/async/-/async-3.2.1.tgz", "resolved": "https://registry.npmjs.org/async/-/async-3.2.2.tgz",
"integrity": "sha512-XdD5lRO/87udXCMC9meWdYiR+Nq6ZjUfXidViUZGu2F1MO4T3XwZ1et0hb2++BgLfhyJwy44BGB/yx80ABx8hg==", "integrity": "sha512-H0E+qZaDEfx/FY4t7iLRv1W2fFI6+pyCeTw1uN20AQPiwqwM6ojPxHxdLv4z8hi2DtnW9BOckSspLucW7pIE5g==",
"dev": true "dev": true
}, },
"async-done": { "async-done": {
@ -6997,9 +6997,9 @@
} }
}, },
"source-map-support": { "source-map-support": {
"version": "0.5.20", "version": "0.5.21",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.20.tgz", "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
"integrity": "sha512-n1lZZ8Ve4ksRqizaBQgxXDgKwttHDhyfQjA6YZZn8+AroHbsIz+JjwxQDxbp+7y5OYCI8t1Yk7etjD9CRd2hIw==", "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
"dev": true, "dev": true,
"requires": { "requires": {
"buffer-from": "^1.0.0", "buffer-from": "^1.0.0",
@ -8423,9 +8423,9 @@
}, },
"dependencies": { "dependencies": {
"camelcase": { "camelcase": {
"version": "6.2.0", "version": "6.2.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.1.tgz",
"integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==", "integrity": "sha512-tVI4q5jjFV5CavAU8DXfza/TJcZutVKo/5Foskmsqcm0MsL91moHvwiGNnqaa2o6PF/7yT5ikDRcVcl8Rj6LCA==",
"dev": true "dev": true
}, },
"decamelize": { "decamelize": {

View file

@ -2,7 +2,7 @@
"name": "typescript", "name": "typescript",
"author": "Microsoft Corp.", "author": "Microsoft Corp.",
"homepage": "https://www.typescriptlang.org/", "homepage": "https://www.typescriptlang.org/",
"version": "4.5.0", "version": "4.6.0",
"license": "Apache-2.0", "license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development", "description": "TypeScript is a language for application scale JavaScript development",
"keywords": [ "keywords": [

View file

@ -39,7 +39,7 @@ const execTsc = (lkg, ...args) =>
exec(process.execPath, exec(process.execPath,
[resolve(findUpRoot(), lkg ? "./lib/tsc" : "./built/local/tsc"), [resolve(findUpRoot(), lkg ? "./lib/tsc" : "./built/local/tsc"),
"-b", ...args], "-b", ...args],
{ hidePrompt: true }) { hidePrompt: true });
const projectBuilder = new ProjectQueue((projects, lkg, force) => execTsc(lkg, ...(force ? ["--force"] : []), ...projects)); const projectBuilder = new ProjectQueue((projects, lkg, force) => execTsc(lkg, ...(force ? ["--force"] : []), ...projects));

View file

@ -33,9 +33,9 @@ async function main() {
const inputPR = (await gh.pulls.get({ pull_number: +process.env.SOURCE_ISSUE, owner: "microsoft", repo: "TypeScript" })).data; const inputPR = (await gh.pulls.get({ pull_number: +process.env.SOURCE_ISSUE, owner: "microsoft", repo: "TypeScript" })).data;
let remoteName = "origin"; let remoteName = "origin";
if (inputPR.base.repo.git_url !== `git:github.com/microsoft/TypeScript`) { if (inputPR.base.repo.git_url !== `git:github.com/microsoft/TypeScript` && inputPR.base.repo.git_url !== `git://github.com/microsoft/TypeScript`) {
runSequence([ runSequence([
["git", ["remote", "add", "nonlocal", inputPR.base.repo.git_url]] ["git", ["remote", "add", "nonlocal", inputPR.base.repo.git_url.replace(/^git:(?:\/\/)?/, "https://")]]
]); ]);
remoteName = "nonlocal"; remoteName = "nonlocal";
} }

File diff suppressed because it is too large Load diff

View file

@ -29,6 +29,7 @@ namespace ts {
["es2019", "lib.es2019.d.ts"], ["es2019", "lib.es2019.d.ts"],
["es2020", "lib.es2020.d.ts"], ["es2020", "lib.es2020.d.ts"],
["es2021", "lib.es2021.d.ts"], ["es2021", "lib.es2021.d.ts"],
["es2022", "lib.es2022.d.ts"],
["esnext", "lib.esnext.d.ts"], ["esnext", "lib.esnext.d.ts"],
// Host only // Host only
["dom", "lib.dom.d.ts"], ["dom", "lib.dom.d.ts"],
@ -72,12 +73,16 @@ namespace ts {
["es2021.string", "lib.es2021.string.d.ts"], ["es2021.string", "lib.es2021.string.d.ts"],
["es2021.weakref", "lib.es2021.weakref.d.ts"], ["es2021.weakref", "lib.es2021.weakref.d.ts"],
["es2021.intl", "lib.es2021.intl.d.ts"], ["es2021.intl", "lib.es2021.intl.d.ts"],
["esnext.array", "lib.es2019.array.d.ts"], ["es2022.array", "lib.es2022.array.d.ts"],
["es2022.error", "lib.es2022.error.d.ts"],
["es2022.object", "lib.es2022.object.d.ts"],
["es2022.string", "lib.es2022.string.d.ts"],
["esnext.array", "lib.es2022.array.d.ts"],
["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"],
["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"],
["esnext.bigint", "lib.es2020.bigint.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"],
["esnext.string", "lib.es2021.string.d.ts"], ["esnext.string", "lib.es2022.string.d.ts"],
["esnext.promise", "lib.es2021.promise.d.ts"], ["esnext.promise", "lib.es2021.promise.d.ts"],
["esnext.weakref", "lib.es2021.weakref.d.ts"] ["esnext.weakref", "lib.es2021.weakref.d.ts"]
]; ];
@ -314,6 +319,7 @@ namespace ts {
es2019: ScriptTarget.ES2019, es2019: ScriptTarget.ES2019,
es2020: ScriptTarget.ES2020, es2020: ScriptTarget.ES2020,
es2021: ScriptTarget.ES2021, es2021: ScriptTarget.ES2021,
es2022: ScriptTarget.ES2022,
esnext: ScriptTarget.ESNext, esnext: ScriptTarget.ESNext,
})), })),
affectsSourceFile: true, affectsSourceFile: true,

View file

@ -23,34 +23,6 @@ namespace ts {
export const emptyMap: ReadonlyESMap<never, never> = new Map<never, never>(); export const emptyMap: ReadonlyESMap<never, never> = new Map<never, never>();
export const emptySet: ReadonlySet<never> = new Set<never>(); export const emptySet: ReadonlySet<never> = new Set<never>();
/**
* Create a new map.
* @deprecated Use `new Map()` instead.
*/
export function createMap<K, V>(): ESMap<K, V>;
export function createMap<T>(): ESMap<string, T>;
export function createMap<K, V>(): ESMap<K, V> {
return new Map<K, V>();
}
/**
* Create a new map from a template object is provided, the map will copy entries from it.
* @deprecated Use `new Map(getEntries(template))` instead.
*/
export function createMapFromTemplate<T>(template: MapLike<T>): ESMap<string, T> {
const map: ESMap<string, T> = new Map<string, T>();
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
for (const key in template) {
if (hasOwnProperty.call(template, key)) {
map.set(key, template[key]);
}
}
return map;
}
export function length(array: readonly any[] | undefined): number { export function length(array: readonly any[] | undefined): number {
return array ? array.length : 0; return array ? array.length : 0;
} }

View file

@ -1,7 +1,7 @@
namespace ts { namespace ts {
// WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
// If changing the text in this section, be sure to test `configurePrerelease` too. // If changing the text in this section, be sure to test `configurePrerelease` too.
export const versionMajorMinor = "4.5"; export const versionMajorMinor = "4.6";
// The following is baselined as a literal template type without intervention // The following is baselined as a literal template type without intervention
/** The version of the TypeScript compiler release */ /** The version of the TypeScript compiler release */
// eslint-disable-next-line @typescript-eslint/no-inferrable-types // eslint-disable-next-line @typescript-eslint/no-inferrable-types

View file

@ -171,12 +171,6 @@ namespace ts {
return value; return value;
} }
/**
* @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
* a value is defined at the statement level.
*/
export const assertDefined = checkDefined;
export function assertEachIsDefined<T extends Node>(value: NodeArray<T>, message?: string, stackCrawlMark?: AnyFunction): asserts value is NodeArray<T>; export function assertEachIsDefined<T extends Node>(value: NodeArray<T>, message?: string, stackCrawlMark?: AnyFunction): asserts value is NodeArray<T>;
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction): asserts value is readonly NonNullable<T>[]; export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction): asserts value is readonly NonNullable<T>[];
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction) { export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction) {
@ -190,12 +184,6 @@ namespace ts {
return value; return value;
} }
/**
* @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
* the elements of an array are defined at the statement level.
*/
export const assertEachDefined = checkEachDefined;
export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never { export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never {
const detail = typeof member === "object" && hasProperty(member, "kind") && hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind((member as Node).kind) : JSON.stringify(member); const detail = typeof member === "object" && hasProperty(member, "kind") && hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind((member as Node).kind) : JSON.stringify(member);
return fail(`${message} ${detail}`, stackCrawlMark || assertNever); return fail(`${message} ${detail}`, stackCrawlMark || assertNever);
@ -351,6 +339,10 @@ namespace ts {
return formatEnum(kind, (ts as any).SyntaxKind, /*isFlags*/ false); return formatEnum(kind, (ts as any).SyntaxKind, /*isFlags*/ false);
} }
export function formatSnippetKind(kind: SnippetKind | undefined): string {
return formatEnum(kind, (ts as any).SnippetKind, /*isFlags*/ false);
}
export function formatNodeFlags(flags: NodeFlags | undefined): string { export function formatNodeFlags(flags: NodeFlags | undefined): string {
return formatEnum(flags, (ts as any).NodeFlags, /*isFlags*/ true); return formatEnum(flags, (ts as any).NodeFlags, /*isFlags*/ true);
} }

View file

@ -924,7 +924,7 @@
"category": "Error", "category": "Error",
"code": 1323 "code": 1323
}, },
"Dynamic imports only support a second argument when the '--module' option is set to 'esnext'.": { "Dynamic imports only support a second argument when the '--module' option is set to 'esnext' or 'nodenext'.": {
"category": "Error", "category": "Error",
"code": 1324 "code": 1324
}, },
@ -3333,7 +3333,7 @@
"category": "Error", "category": "Error",
"code": 2820 "code": 2820
}, },
"Import assertions are only supported when the '--module' option is set to 'esnext'.": { "Import assertions are only supported when the '--module' option is set to 'esnext' or 'nodenext'.": {
"category": "Error", "category": "Error",
"code": 2821 "code": 2821
}, },
@ -3345,6 +3345,18 @@
"category": "Error", "category": "Error",
"code": 2833 "code": 2833
}, },
"Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path.": {
"category": "Error",
"code": 2834
},
"Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?": {
"category": "Error",
"code": 2835
},
"Import assertions are not allowed on statements that transpile to commonjs 'require' calls.": {
"category": "Error",
"code": 2836
},
"Import declaration '{0}' is using private name '{1}'.": { "Import declaration '{0}' is using private name '{1}'.": {
"category": "Error", "category": "Error",
@ -3770,6 +3782,11 @@
"category": "Error", "category": "Error",
"code": 4123 "code": 4123
}, },
"Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'.": {
"category": "Error",
"code": 4124
},
"The current host does not support the '{0}' option.": { "The current host does not support the '{0}' option.": {
"category": "Error", "category": "Error",
"code": 5001 "code": 5001
@ -6001,6 +6018,10 @@
"category": "Error", "category": "Error",
"code": 7061 "code": 7061
}, },
"JSON imports are experimental in ES module mode imports.": {
"category": "Error",
"code": 7062
},
"You cannot rename this element.": { "You cannot rename this element.": {
"category": "Error", "category": "Error",
@ -6416,6 +6437,11 @@
"category": "Message", "category": "Message",
"code": 90053 "code": 90053
}, },
"Includes imports of types referenced by '{0}'": {
"category": "Message",
"code": 90054
},
"Convert function to an ES2015 class": { "Convert function to an ES2015 class": {
"category": "Message", "category": "Message",
"code": 95001 "code": 95001

View file

@ -1283,7 +1283,13 @@ namespace ts {
currentParenthesizerRule = undefined; currentParenthesizerRule = undefined;
} }
function pipelineEmitWithHintWorker(hint: EmitHint, node: Node): void { function pipelineEmitWithHintWorker(hint: EmitHint, node: Node, allowSnippets = true): void {
if (allowSnippets) {
const snippet = getSnippetElement(node);
if (snippet) {
return emitSnippetNode(hint, node, snippet);
}
}
if (hint === EmitHint.SourceFile) return emitSourceFile(cast(node, isSourceFile)); if (hint === EmitHint.SourceFile) return emitSourceFile(cast(node, isSourceFile));
if (hint === EmitHint.IdentifierName) return emitIdentifier(cast(node, isIdentifier)); if (hint === EmitHint.IdentifierName) return emitIdentifier(cast(node, isIdentifier));
if (hint === EmitHint.JsxAttributeValue) return emitLiteral(cast(node, isStringLiteral), /*jsxAttributeEscape*/ true); if (hint === EmitHint.JsxAttributeValue) return emitLiteral(cast(node, isStringLiteral), /*jsxAttributeEscape*/ true);
@ -1598,6 +1604,7 @@ namespace ts {
return emitJSDocSignature(node as JSDocSignature); return emitJSDocSignature(node as JSDocSignature);
case SyntaxKind.JSDocTag: case SyntaxKind.JSDocTag:
case SyntaxKind.JSDocClassTag: case SyntaxKind.JSDocClassTag:
case SyntaxKind.JSDocOverrideTag:
return emitJSDocSimpleTag(node as JSDocTag); return emitJSDocSimpleTag(node as JSDocTag);
case SyntaxKind.JSDocAugmentsTag: case SyntaxKind.JSDocAugmentsTag:
case SyntaxKind.JSDocImplementsTag: case SyntaxKind.JSDocImplementsTag:
@ -1610,7 +1617,6 @@ namespace ts {
case SyntaxKind.JSDocPrivateTag: case SyntaxKind.JSDocPrivateTag:
case SyntaxKind.JSDocProtectedTag: case SyntaxKind.JSDocProtectedTag:
case SyntaxKind.JSDocReadonlyTag: case SyntaxKind.JSDocReadonlyTag:
case SyntaxKind.JSDocOverrideTag:
return; return;
case SyntaxKind.JSDocCallbackTag: case SyntaxKind.JSDocCallbackTag:
return emitJSDocCallbackTag(node as JSDocCallbackTag); return emitJSDocCallbackTag(node as JSDocCallbackTag);
@ -1924,6 +1930,32 @@ namespace ts {
} }
} }
//
// Snippet Elements
//
function emitSnippetNode(hint: EmitHint, node: Node, snippet: SnippetElement) {
switch (snippet.kind) {
case SnippetKind.Placeholder:
emitPlaceholder(hint, node, snippet);
break;
case SnippetKind.TabStop:
emitTabStop(snippet);
break;
}
}
function emitPlaceholder(hint: EmitHint, node: Node, snippet: Placeholder) {
nonEscapingWrite(`\$\{${snippet.order}:`); // `${2:`
pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...`
nonEscapingWrite(`\}`); // `}`
// `${2:...}`
}
function emitTabStop(snippet: TabStop) {
nonEscapingWrite(`\$${snippet.order}`);
}
// //
// Identifiers // Identifiers
// //
@ -4457,6 +4489,16 @@ namespace ts {
writer.writeProperty(s); writer.writeProperty(s);
} }
function nonEscapingWrite(s: string) {
// This should be defined in a snippet-escaping text writer.
if (writer.nonEscapingWrite) {
writer.nonEscapingWrite(s);
}
else {
writer.write(s);
}
}
function writeLine(count = 1) { function writeLine(count = 1) {
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
writer.writeLine(i > 0); writer.writeLine(i > 0);

View file

@ -256,6 +256,24 @@ namespace ts {
} }
} }
/**
* Gets the SnippetElement of a node.
*/
/* @internal */
export function getSnippetElement(node: Node): SnippetElement | undefined {
return node.emitNode?.snippetElement;
}
/**
* Sets the SnippetElement of a node.
*/
/* @internal */
export function setSnippetElement<T extends Node>(node: T, snippet: SnippetElement): T {
const emitNode = getOrCreateEmitNode(node);
emitNode.snippetElement = snippet;
return node;
}
/* @internal */ /* @internal */
export function ignoreSourceNewlines<T extends Node>(node: T): T { export function ignoreSourceNewlines<T extends Node>(node: T): T {
getOrCreateEmitNode(node).flags |= EmitFlags.IgnoreSourceNewlines; getOrCreateEmitNode(node).flags |= EmitFlags.IgnoreSourceNewlines;

View file

@ -6387,7 +6387,7 @@ namespace ts {
sourceMapText = mapTextOrStripInternal as string; sourceMapText = mapTextOrStripInternal as string;
} }
const node = oldFileOfCurrentEmit ? const node = oldFileOfCurrentEmit ?
parseOldFileOfCurrentEmit(Debug.assertDefined(bundleFileInfo)) : parseOldFileOfCurrentEmit(Debug.checkDefined(bundleFileInfo)) :
parseUnparsedSourceFile(bundleFileInfo, stripInternal, length); parseUnparsedSourceFile(bundleFileInfo, stripInternal, length);
node.fileName = fileName; node.fileName = fileName;
node.sourceMapPath = sourceMapPath; node.sourceMapPath = sourceMapPath;
@ -6587,13 +6587,13 @@ namespace ts {
}; };
node.javascriptPath = declarationTextOrJavascriptPath; node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath; node.javascriptMapPath = javascriptMapPath;
node.declarationPath = Debug.assertDefined(javascriptMapTextOrDeclarationPath); node.declarationPath = Debug.checkDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath; node.declarationMapPath = declarationMapPath;
node.buildInfoPath = declarationMapTextOrBuildInfoPath; node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, { Object.defineProperties(node, {
javascriptText: { get() { return definedTextGetter(declarationTextOrJavascriptPath); } }, javascriptText: { get() { return definedTextGetter(declarationTextOrJavascriptPath); } },
javascriptMapText: { get() { return textGetter(javascriptMapPath); } }, // TODO:: if there is inline sourceMap in jsFile, use that javascriptMapText: { get() { return textGetter(javascriptMapPath); } }, // TODO:: if there is inline sourceMap in jsFile, use that
declarationText: { get() { return definedTextGetter(Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } }, declarationText: { get() { return definedTextGetter(Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
declarationMapText: { get() { return textGetter(declarationMapPath); } }, // TODO:: if there is inline sourceMap in dtsFile, use that declarationMapText: { get() { return textGetter(declarationMapPath); } }, // TODO:: if there is inline sourceMap in dtsFile, use that
buildInfo: { get() { return getAndCacheBuildInfo(() => textGetter(declarationMapTextOrBuildInfoPath)); } } buildInfo: { get() { return getAndCacheBuildInfo(() => textGetter(declarationMapTextOrBuildInfoPath)); } }
}); });

View file

@ -707,13 +707,15 @@ namespace ts.moduleSpecifiers {
if (host.fileExists(packageJsonPath)) { if (host.fileExists(packageJsonPath)) {
const packageJsonContent = JSON.parse(host.readFile!(packageJsonPath)!); const packageJsonContent = JSON.parse(host.readFile!(packageJsonPath)!);
// TODO: Inject `require` or `import` condition based on the intended import mode // TODO: Inject `require` or `import` condition based on the intended import mode
const fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; if (getEmitModuleResolutionKind(options) === ModuleResolutionKind.Node12 || getEmitModuleResolutionKind(options) === ModuleResolutionKind.NodeNext) {
if (fromExports) { const fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined;
const withJsExtension = !hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; if (fromExports) {
return { ...withJsExtension, verbatimFromExports: true }; const withJsExtension = !hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) };
} return { ...withJsExtension, verbatimFromExports: true };
if (packageJsonContent.exports) { }
return { moduleFileToTry: path, blockedByExports: true }; if (packageJsonContent.exports) {
return { moduleFileToTry: path, blockedByExports: true };
}
} }
const versionPaths = packageJsonContent.typesVersions const versionPaths = packageJsonContent.typesVersions
? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)

View file

@ -818,6 +818,25 @@ namespace ts {
} }
} }
/** @internal */
export const plainJSErrors: Set<number> = new Set([
Diagnostics.Cannot_redeclare_block_scoped_variable_0.code,
Diagnostics.A_module_cannot_have_multiple_default_exports.code,
Diagnostics.Another_export_default_is_here.code,
Diagnostics.The_first_export_default_is_here.code,
Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module.code,
Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode.code,
Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here.code,
Diagnostics.constructor_is_a_reserved_word.code,
Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode.code,
Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode.code,
Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode.code,
Diagnostics.Invalid_use_of_0_in_strict_mode.code,
Diagnostics.A_label_is_not_allowed_here.code,
Diagnostics.Octal_literals_are_not_allowed_in_strict_mode.code,
Diagnostics.with_statements_are_not_allowed_in_strict_mode.code,
]);
/** /**
* Determine if source file needs to be re-created even if its text hasn't changed * Determine if source file needs to be re-created even if its text hasn't changed
*/ */
@ -1577,6 +1596,7 @@ namespace ts {
newSourceFile.originalFileName = oldSourceFile.originalFileName; newSourceFile.originalFileName = oldSourceFile.originalFileName;
newSourceFile.resolvedPath = oldSourceFile.resolvedPath; newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
newSourceFile.fileName = oldSourceFile.fileName; newSourceFile.fileName = oldSourceFile.fileName;
newSourceFile.impliedNodeFormat = oldSourceFile.impliedNodeFormat;
const packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); const packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
if (packageName !== undefined) { if (packageName !== undefined) {
@ -1674,8 +1694,8 @@ namespace ts {
const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => toFileNameLowerCase(ref.fileName)); const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => toFileNameLowerCase(ref.fileName));
const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile); const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile);
// ensure that types resolutions are still correct // ensure that types resolutions are still correct
const typeReferenceEesolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, typeDirectiveIsEqualTo); const typeReferenceResolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, typeDirectiveIsEqualTo);
if (typeReferenceEesolutionsChanged) { if (typeReferenceResolutionsChanged) {
structureIsReused = StructureIsReused.SafeModules; structureIsReused = StructureIsReused.SafeModules;
newSourceFile.resolvedTypeReferenceDirectiveNames = zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions); newSourceFile.resolvedTypeReferenceDirectiveNames = zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions);
} }
@ -2004,15 +2024,24 @@ namespace ts {
Debug.assert(!!sourceFile.bindDiagnostics); Debug.assert(!!sourceFile.bindDiagnostics);
const isCheckJs = isCheckJsEnabledForFile(sourceFile, options); const isJs = sourceFile.scriptKind === ScriptKind.JS || sourceFile.scriptKind === ScriptKind.JSX;
const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options);
const isPlainJs = isJs && !sourceFile.checkJsDirective && options.checkJs === undefined;
const isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false; const isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
// By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === ScriptKind.TS || sourceFile.scriptKind === ScriptKind.TSX
|| sourceFile.scriptKind === ScriptKind.External || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred);
const bindDiagnostics: readonly Diagnostic[] = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray;
const checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : emptyArray;
return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined); // By default, only type-check .ts, .tsx, Deferred, plain JS, checked JS and External
// - plain JS: .js files with no // ts-check and checkJs: undefined
// - check JS: .js files with either // ts-check or checkJs: true
// - external: files that are added by plugins
const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === ScriptKind.TS || sourceFile.scriptKind === ScriptKind.TSX
|| sourceFile.scriptKind === ScriptKind.External || isPlainJs || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred);
let bindDiagnostics: readonly Diagnostic[] = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray;
const checkDiagnostics = includeBindAndCheckDiagnostics && !isPlainJs ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : emptyArray;
if (isPlainJs) {
bindDiagnostics = filter(bindDiagnostics, d => plainJSErrors.has(d.code));
}
// skip ts-expect-error errors in plain JS files, and skip JSDoc errors except in checked JS
return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics && !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
}); });
} }
@ -3160,6 +3189,21 @@ namespace ts {
} }
function verifyCompilerOptions() { function verifyCompilerOptions() {
const isNightly = stringContains(version, "-dev") || stringContains(version, "-insiders");
if (!isNightly) {
if (getEmitModuleKind(options) === ModuleKind.Node12) {
createOptionValueDiagnostic("module", Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12");
}
else if (getEmitModuleKind(options) === ModuleKind.NodeNext) {
createOptionValueDiagnostic("module", Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "nodenext");
}
else if (getEmitModuleResolutionKind(options) === ModuleResolutionKind.Node12) {
createOptionValueDiagnostic("moduleResolution", Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "node12");
}
else if (getEmitModuleResolutionKind(options) === ModuleResolutionKind.NodeNext) {
createOptionValueDiagnostic("moduleResolution", Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "nodenext");
}
}
if (options.strictPropertyInitialization && !getStrictOptionValue(options, "strictNullChecks")) { if (options.strictPropertyInitialization && !getStrictOptionValue(options, "strictNullChecks")) {
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
} }
@ -3333,7 +3377,9 @@ namespace ts {
} }
if (options.resolveJsonModule) { if (options.resolveJsonModule) {
if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs) { if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs &&
getEmitModuleResolutionKind(options) !== ModuleResolutionKind.Node12 &&
getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeNext) {
createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
} }
// Any emit other than common js, amd, es2015 or esnext is error // Any emit other than common js, amd, es2015 or esnext is error
@ -3694,8 +3740,8 @@ namespace ts {
createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
} }
function createOptionValueDiagnostic(option1: string, message: DiagnosticMessage, arg0?: string) { function createOptionValueDiagnostic(option1: string, message: DiagnosticMessage, arg0?: string, arg1?: string) {
createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0, arg1);
} }
function createDiagnosticForReference(sourceFile: JsonSourceFile | undefined, index: number, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number) { function createDiagnosticForReference(sourceFile: JsonSourceFile | undefined, index: number, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number) {

View file

@ -66,6 +66,7 @@ namespace ts {
getCurrentProgram(): Program | undefined; getCurrentProgram(): Program | undefined;
fileIsOpen(filePath: Path): boolean; fileIsOpen(filePath: Path): boolean;
getCompilerHost?(): CompilerHost | undefined; getCompilerHost?(): CompilerHost | undefined;
onDiscoveredSymlink?(): void;
} }
interface DirectoryWatchesOfFailedLookup { interface DirectoryWatchesOfFailedLookup {
@ -431,6 +432,9 @@ namespace ts {
else { else {
resolution = loader(name, containingFile, compilerOptions, resolutionHost.getCompilerHost?.() || resolutionHost, redirectedReference, containingSourceFile); resolution = loader(name, containingFile, compilerOptions, resolutionHost.getCompilerHost?.() || resolutionHost, redirectedReference, containingSourceFile);
perDirectoryResolution.set(name, mode, resolution); perDirectoryResolution.set(name, mode, resolution);
if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) {
resolutionHost.onDiscoveredSymlink();
}
} }
resolutionsInFile.set(name, mode, resolution); resolutionsInFile.set(name, mode, resolution);
watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
@ -615,7 +619,7 @@ namespace ts {
) { ) {
if (resolution.refCount) { if (resolution.refCount) {
resolution.refCount++; resolution.refCount++;
Debug.assertDefined(resolution.files); Debug.assertIsDefined(resolution.files);
} }
else { else {
resolution.refCount = 1; resolution.refCount = 1;
@ -692,7 +696,7 @@ namespace ts {
filePath: Path, filePath: Path,
getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName<T, R>, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName<T, R>,
) { ) {
unorderedRemoveItem(Debug.assertDefined(resolution.files), filePath); unorderedRemoveItem(Debug.checkDefined(resolution.files), filePath);
resolution.refCount!--; resolution.refCount!--;
if (resolution.refCount) { if (resolution.refCount) {
return; return;
@ -794,7 +798,7 @@ namespace ts {
for (const resolution of resolutions) { for (const resolution of resolutions) {
if (resolution.isInvalidated || !canInvalidate(resolution)) continue; if (resolution.isInvalidated || !canInvalidate(resolution)) continue;
resolution.isInvalidated = invalidated = true; resolution.isInvalidated = invalidated = true;
for (const containingFilePath of Debug.assertDefined(resolution.files)) { for (const containingFilePath of Debug.checkDefined(resolution.files)) {
(filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new Set())).add(containingFilePath); (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new Set())).add(containingFilePath);
// When its a file with inferred types resolution, invalidate type reference directive resolution // When its a file with inferred types resolution, invalidate type reference directive resolution
hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || endsWith(containingFilePath, inferredTypesContainingFile); hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || endsWith(containingFilePath, inferredTypesContainingFile);
@ -965,4 +969,11 @@ namespace ts {
return dirPath === rootPath || canWatchDirectory(dirPath); return dirPath === rootPath || canWatchDirectory(dirPath);
} }
} }
function resolutionIsSymlink(resolution: ResolutionWithFailedLookupLocations) {
return !!(
(resolution as ResolvedModuleWithFailedLookupLocations).resolvedModule?.originalPath ||
(resolution as ResolvedTypeReferenceDirectiveWithFailedLookupLocations).resolvedTypeReferenceDirective?.originalPath
);
}
} }

View file

@ -2374,6 +2374,7 @@ namespace ts {
tokenValue = tokenValue.slice(0, -1); tokenValue = tokenValue.slice(0, -1);
pos--; pos--;
} }
return getIdentifierToken();
} }
return token; return token;
} }

View file

@ -1625,7 +1625,6 @@ namespace ts {
sysLog(`sysLog:: ${fileOrDirectory}:: Defaulting to fsWatchFile`); sysLog(`sysLog:: ${fileOrDirectory}:: Defaulting to fsWatchFile`);
return watchPresentFileSystemEntryWithFsWatchFile(); return watchPresentFileSystemEntryWithFsWatchFile();
} }
try { try {
const presentWatcher = _fs.watch( const presentWatcher = _fs.watch(
fileOrDirectory, fileOrDirectory,
@ -1804,7 +1803,7 @@ namespace ts {
} }
function readDirectory(path: string, extensions?: readonly string[], excludes?: readonly string[], includes?: readonly string[], depth?: number): string[] { function readDirectory(path: string, extensions?: readonly string[], excludes?: readonly string[], includes?: readonly string[], depth?: number): string[] {
return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath, directoryExists); return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
} }
function fileSystemEntryExists(path: string, entryKind: FileSystemEntryKind): boolean { function fileSystemEntryExists(path: string, entryKind: FileSystemEntryKind): boolean {

View file

@ -282,7 +282,7 @@ namespace ts {
function visitYieldExpression(node: YieldExpression) { function visitYieldExpression(node: YieldExpression) {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
if (node.asteriskToken) { if (node.asteriskToken) {
const expression = visitNode(Debug.assertDefined(node.expression), visitor, isExpression); const expression = visitNode(Debug.checkDefined(node.expression), visitor, isExpression);
return setOriginalNode( return setOriginalNode(
setTextRange( setTextRange(

View file

@ -26,12 +26,12 @@ namespace ts {
return currentFileState.filenameDeclaration.name; return currentFileState.filenameDeclaration.name;
} }
function getJsxFactoryCalleePrimitive(childrenLength: number): "jsx" | "jsxs" | "jsxDEV" { function getJsxFactoryCalleePrimitive(isStaticChildren: boolean): "jsx" | "jsxs" | "jsxDEV" {
return compilerOptions.jsx === JsxEmit.ReactJSXDev ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx"; return compilerOptions.jsx === JsxEmit.ReactJSXDev ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx";
} }
function getJsxFactoryCallee(childrenLength: number) { function getJsxFactoryCallee(isStaticChildren: boolean) {
const type = getJsxFactoryCalleePrimitive(childrenLength); const type = getJsxFactoryCalleePrimitive(isStaticChildren);
return getImplicitImportForName(type); return getImplicitImportForName(type);
} }
@ -48,11 +48,11 @@ namespace ts {
return existing.name; return existing.name;
} }
if (!currentFileState.utilizedImplicitRuntimeImports) { if (!currentFileState.utilizedImplicitRuntimeImports) {
currentFileState.utilizedImplicitRuntimeImports = createMap(); currentFileState.utilizedImplicitRuntimeImports = new Map();
} }
let specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource); let specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource);
if (!specifierSourceImports) { if (!specifierSourceImports) {
specifierSourceImports = createMap(); specifierSourceImports = new Map();
currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports); currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports);
} }
const generatedName = factory.createUniqueName(`_${name}`, GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.AllowNameSubstitution); const generatedName = factory.createUniqueName(`_${name}`, GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.AllowNameSubstitution);
@ -206,7 +206,7 @@ namespace ts {
function convertJsxChildrenToChildrenPropAssignment(children: readonly JsxChild[]) { function convertJsxChildrenToChildrenPropAssignment(children: readonly JsxChild[]) {
const nonWhitespaceChildren = getSemanticJsxChildren(children); const nonWhitespaceChildren = getSemanticJsxChildren(children);
if (length(nonWhitespaceChildren) === 1) { if (length(nonWhitespaceChildren) === 1 && !(nonWhitespaceChildren[0] as JsxExpression).dotDotDotToken) {
const result = transformJsxChildToExpression(nonWhitespaceChildren[0]); const result = transformJsxChildToExpression(nonWhitespaceChildren[0]);
return result && factory.createPropertyAssignment("children", result); return result && factory.createPropertyAssignment("children", result);
} }
@ -221,16 +221,33 @@ namespace ts {
const attrs = keyAttr ? filter(node.attributes.properties, p => p !== keyAttr) : node.attributes.properties; const attrs = keyAttr ? filter(node.attributes.properties, p => p !== keyAttr) : node.attributes.properties;
const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) :
factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : emptyArray); // When there are no attributes, React wants {} factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : emptyArray); // When there are no attributes, React wants {}
return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, length(getSemanticJsxChildren(children || emptyArray)), isChild, location); return visitJsxOpeningLikeElementOrFragmentJSX(
tagName,
objectProperties,
keyAttr,
children || emptyArray,
isChild,
location
);
} }
function visitJsxOpeningLikeElementOrFragmentJSX(tagName: Expression, objectProperties: Expression, keyAttr: JsxAttribute | undefined, childrenLength: number, isChild: boolean, location: TextRange) { function visitJsxOpeningLikeElementOrFragmentJSX(
tagName: Expression,
objectProperties: Expression,
keyAttr: JsxAttribute | undefined,
children: readonly JsxChild[],
isChild: boolean,
location: TextRange
) {
const nonWhitespaceChildren = getSemanticJsxChildren(children);
const isStaticChildren =
length(nonWhitespaceChildren) > 1 || !!(nonWhitespaceChildren[0] as JsxExpression)?.dotDotDotToken;
const args: Expression[] = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; const args: Expression[] = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)];
if (compilerOptions.jsx === JsxEmit.ReactJSXDev) { if (compilerOptions.jsx === JsxEmit.ReactJSXDev) {
const originalFile = getOriginalNode(currentSourceFile); const originalFile = getOriginalNode(currentSourceFile);
if (originalFile && isSourceFile(originalFile)) { if (originalFile && isSourceFile(originalFile)) {
// isStaticChildren development flag // isStaticChildren development flag
args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse()); args.push(isStaticChildren ? factory.createTrue() : factory.createFalse());
// __source development flag // __source development flag
const lineCol = getLineAndCharacterOfPosition(originalFile, location.pos); const lineCol = getLineAndCharacterOfPosition(originalFile, location.pos);
args.push(factory.createObjectLiteralExpression([ args.push(factory.createObjectLiteralExpression([
@ -242,7 +259,10 @@ namespace ts {
args.push(factory.createThis()); args.push(factory.createThis());
} }
} }
const element = setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location); const element = setTextRange(
factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ undefined, args),
location
);
if (isChild) { if (isChild) {
startOnNewLine(element); startOnNewLine(element);
@ -294,7 +314,7 @@ namespace ts {
getImplicitJsxFragmentReference(), getImplicitJsxFragmentReference(),
childrenProps || factory.createObjectLiteralExpression([]), childrenProps || factory.createObjectLiteralExpression([]),
/*keyAttr*/ undefined, /*keyAttr*/ undefined,
length(getSemanticJsxChildren(children)), children,
isChild, isChild,
location location
); );

View file

@ -1609,7 +1609,7 @@ namespace ts {
export interface TypePredicateNode extends TypeNode { export interface TypePredicateNode extends TypeNode {
readonly kind: SyntaxKind.TypePredicate; readonly kind: SyntaxKind.TypePredicate;
readonly parent: SignatureDeclaration | JSDocTypeExpression; readonly parent: SignatureDeclaration | JSDocTypeExpression;
readonly assertsModifier?: AssertsToken; readonly assertsModifier?: AssertsKeyword;
readonly parameterName: Identifier | ThisTypeNode; readonly parameterName: Identifier | ThisTypeNode;
readonly type?: TypeNode; readonly type?: TypeNode;
} }
@ -1702,7 +1702,7 @@ namespace ts {
export interface MappedTypeNode extends TypeNode, Declaration { export interface MappedTypeNode extends TypeNode, Declaration {
readonly kind: SyntaxKind.MappedType; readonly kind: SyntaxKind.MappedType;
readonly readonlyToken?: ReadonlyToken | PlusToken | MinusToken; readonly readonlyToken?: ReadonlyKeyword | PlusToken | MinusToken;
readonly typeParameter: TypeParameterDeclaration; readonly typeParameter: TypeParameterDeclaration;
readonly nameType?: TypeNode; readonly nameType?: TypeNode;
readonly questionToken?: QuestionToken | PlusToken | MinusToken; readonly questionToken?: QuestionToken | PlusToken | MinusToken;
@ -2756,7 +2756,7 @@ namespace ts {
export interface ForOfStatement extends IterationStatement { export interface ForOfStatement extends IterationStatement {
readonly kind: SyntaxKind.ForOfStatement; readonly kind: SyntaxKind.ForOfStatement;
readonly awaitModifier?: AwaitKeywordToken; readonly awaitModifier?: AwaitKeyword;
readonly initializer: ForInitializer; readonly initializer: ForInitializer;
readonly expression: Expression; readonly expression: Expression;
} }
@ -4414,6 +4414,14 @@ namespace ts {
/* @internal */ isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean; /* @internal */ isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean;
/* @internal */ isPropertyAccessible(node: Node, isSuper: boolean, isWrite: boolean, containingType: Type, property: Symbol): boolean; /* @internal */ isPropertyAccessible(node: Node, isSuper: boolean, isWrite: boolean, containingType: Type, property: Symbol): boolean;
/* @internal */ getTypeOnlyAliasDeclaration(symbol: Symbol): TypeOnlyAliasDeclaration | undefined; /* @internal */ getTypeOnlyAliasDeclaration(symbol: Symbol): TypeOnlyAliasDeclaration | undefined;
/* @internal */ getMemberOverrideModifierStatus(node: ClassLikeDeclaration, member: ClassElement): MemberOverrideStatus;
}
/* @internal */
export const enum MemberOverrideStatus {
Ok,
NeedsOverride,
HasInvalidOverride
} }
/* @internal */ /* @internal */
@ -5075,6 +5083,7 @@ namespace ts {
ConstructorReferenceInClass = 0x02000000, // Binding to a class constructor inside of the class's body. ConstructorReferenceInClass = 0x02000000, // Binding to a class constructor inside of the class's body.
ContainsClassWithPrivateIdentifiers = 0x04000000, // Marked on all block-scoped containers containing a class with private identifiers. ContainsClassWithPrivateIdentifiers = 0x04000000, // Marked on all block-scoped containers containing a class with private identifiers.
ContainsSuperPropertyInStaticInitializer = 0x08000000, // Marked on all block-scoped containers containing a static initializer with 'super.x' or 'super[x]'. ContainsSuperPropertyInStaticInitializer = 0x08000000, // Marked on all block-scoped containers containing a static initializer with 'super.x' or 'super[x]'.
InCheckIdentifier = 0x10000000,
} }
/* @internal */ /* @internal */
@ -5098,7 +5107,7 @@ namespace ts {
jsxNamespace?: Symbol | false; // Resolved jsx namespace symbol for this node jsxNamespace?: Symbol | false; // Resolved jsx namespace symbol for this node
jsxImplicitImportContainer?: Symbol | false; // Resolved module symbol the implicit jsx import of this file should refer to jsxImplicitImportContainer?: Symbol | false; // Resolved module symbol the implicit jsx import of this file should refer to
contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive
deferredNodes?: ESMap<NodeId, Node>; // Set of nodes whose checking has been deferred deferredNodes?: Set<Node>; // Set of nodes whose checking has been deferred
capturedBlockScopeBindings?: Symbol[]; // Block-scoped bindings captured beneath this part of an IterationStatement capturedBlockScopeBindings?: Symbol[]; // Block-scoped bindings captured beneath this part of an IterationStatement
outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type
isExhaustive?: boolean; // Is node an exhaustive switch statement isExhaustive?: boolean; // Is node an exhaustive switch statement
@ -5179,8 +5188,6 @@ namespace ts {
// 'Narrowable' types are types where narrowing actually narrows. // 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never // This *should* be every type other than null, undefined, void, and never
Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive, Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive,
/* @internal */
NotPrimitiveUnion = Any | Unknown | Enum | Void | Never | Object | Intersection | Instantiable,
// The following flags are aggregated during union and intersection type construction // The following flags are aggregated during union and intersection type construction
/* @internal */ /* @internal */
IncludesMask = Any | Unknown | Primitive | Never | Object | Union | Intersection | NonPrimitive | TemplateLiteral, IncludesMask = Any | Unknown | Primitive | Never | Object | Union | Intersection | NonPrimitive | TemplateLiteral,
@ -5193,6 +5200,10 @@ namespace ts {
IncludesWildcard = IndexedAccess, IncludesWildcard = IndexedAccess,
/* @internal */ /* @internal */
IncludesEmptyObject = Conditional, IncludesEmptyObject = Conditional,
/* @internal */
IncludesInstantiable = Substitution,
/* @internal */
NotPrimitiveUnion = Any | Unknown | Enum | Void | Never | Object | Intersection | IncludesInstantiable,
} }
export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
@ -5579,6 +5590,7 @@ namespace ts {
/* @internal */ /* @internal */
export interface SyntheticDefaultModuleType extends Type { export interface SyntheticDefaultModuleType extends Type {
syntheticType?: Type; syntheticType?: Type;
defaultOnlyType?: Type;
} }
export interface InstantiableType extends Type { export interface InstantiableType extends Type {
@ -5983,7 +5995,7 @@ namespace ts {
export enum ModuleResolutionKind { export enum ModuleResolutionKind {
Classic = 1, Classic = 1,
NodeJs = 2, NodeJs = 2,
// Starting with node12, node's module resolver has significant departures from tranditional cjs resolution // Starting with node12, node's module resolver has significant departures from traditional cjs resolution
// to better support ecmascript modules and their use within node - more features are still being added, so // to better support ecmascript modules and their use within node - more features are still being added, so
// we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12` // we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12`
// version-anchored resolution target // version-anchored resolution target
@ -6256,6 +6268,7 @@ namespace ts {
ES2019 = 6, ES2019 = 6,
ES2020 = 7, ES2020 = 7,
ES2021 = 8, ES2021 = 8,
ES2022 = 9,
ESNext = 99, ESNext = 99,
JSON = 100, JSON = 100,
Latest = ESNext, Latest = ESNext,
@ -6713,15 +6726,16 @@ namespace ts {
ContainsTypeScript = 1 << 0, ContainsTypeScript = 1 << 0,
ContainsJsx = 1 << 1, ContainsJsx = 1 << 1,
ContainsESNext = 1 << 2, ContainsESNext = 1 << 2,
ContainsES2021 = 1 << 3, ContainsES2022 = 1 << 3,
ContainsES2020 = 1 << 4, ContainsES2021 = 1 << 4,
ContainsES2019 = 1 << 5, ContainsES2020 = 1 << 5,
ContainsES2018 = 1 << 6, ContainsES2019 = 1 << 6,
ContainsES2017 = 1 << 7, ContainsES2018 = 1 << 7,
ContainsES2016 = 1 << 8, ContainsES2017 = 1 << 8,
ContainsES2015 = 1 << 9, ContainsES2016 = 1 << 9,
ContainsGenerator = 1 << 10, ContainsES2015 = 1 << 10,
ContainsDestructuringAssignment = 1 << 11, ContainsGenerator = 1 << 11,
ContainsDestructuringAssignment = 1 << 12,
// Markers // Markers
// - Flags used to indicate that a subtree contains a specific transformation. // - Flags used to indicate that a subtree contains a specific transformation.
@ -6750,6 +6764,7 @@ namespace ts {
AssertTypeScript = ContainsTypeScript, AssertTypeScript = ContainsTypeScript,
AssertJsx = ContainsJsx, AssertJsx = ContainsJsx,
AssertESNext = ContainsESNext, AssertESNext = ContainsESNext,
AssertES2022 = ContainsES2022,
AssertES2021 = ContainsES2021, AssertES2021 = ContainsES2021,
AssertES2020 = ContainsES2020, AssertES2020 = ContainsES2020,
AssertES2019 = ContainsES2019, AssertES2019 = ContainsES2019,
@ -6815,6 +6830,31 @@ namespace ts {
externalHelpers?: boolean; externalHelpers?: boolean;
helpers?: EmitHelper[]; // Emit helpers for the node helpers?: EmitHelper[]; // Emit helpers for the node
startsOnNewLine?: boolean; // If the node should begin on a new line startsOnNewLine?: boolean; // If the node should begin on a new line
snippetElement?: SnippetElement; // Snippet element of the node
}
/* @internal */
export type SnippetElement = TabStop | Placeholder;
/* @internal */
export interface TabStop {
kind: SnippetKind.TabStop;
order: number;
}
/* @internal */
export interface Placeholder {
kind: SnippetKind.Placeholder;
order: number;
}
// Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax
/* @internal */
export const enum SnippetKind {
TabStop, // `$1`, `$2`
Placeholder, // `${1:foo}`
Choice, // `${1|one,two,three|}`
Variable, // `$name`, `${name:default}`
} }
export const enum EmitFlags { export const enum EmitFlags {
@ -8277,6 +8317,7 @@ namespace ts {
hasTrailingComment(): boolean; hasTrailingComment(): boolean;
hasTrailingWhitespace(): boolean; hasTrailingWhitespace(): boolean;
getTextPosWithWriteLine?(): number; getTextPosWithWriteLine?(): number;
nonEscapingWrite?(text: string): void;
} }
export interface GetEffectiveTypeRootsHost { export interface GetEffectiveTypeRootsHost {
@ -8622,6 +8663,7 @@ namespace ts {
readonly includeCompletionsWithSnippetText?: boolean; readonly includeCompletionsWithSnippetText?: boolean;
readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly includeCompletionsWithInsertText?: boolean; readonly includeCompletionsWithInsertText?: boolean;
readonly includeCompletionsWithClassMemberSnippets?: boolean;
readonly allowIncompleteCompletions?: boolean; readonly allowIncompleteCompletions?: boolean;
readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */

View file

@ -20,21 +20,6 @@ namespace ts {
return undefined; return undefined;
} }
/**
* Create a new escaped identifier map.
* @deprecated Use `new Map<__String, T>()` instead.
*/
export function createUnderscoreEscapedMap<T>(): UnderscoreEscapedMap<T> {
return new Map<__String, T>();
}
/**
* @deprecated Use `!!map?.size` instead
*/
export function hasEntries(map: ReadonlyCollection<any> | undefined): map is ReadonlyCollection<any> {
return !!map && !!map.size;
}
export function createSymbolTable(symbols?: readonly Symbol[]): SymbolTable { export function createSymbolTable(symbols?: readonly Symbol[]): SymbolTable {
const result = new Map<__String, Symbol>(); const result = new Map<__String, Symbol>();
if (symbols) { if (symbols) {
@ -606,6 +591,7 @@ namespace ts {
AsyncIterableIterator: emptyArray, AsyncIterableIterator: emptyArray,
AsyncGenerator: emptyArray, AsyncGenerator: emptyArray,
AsyncGeneratorFunction: emptyArray, AsyncGeneratorFunction: emptyArray,
NumberFormat: ["formatToParts"]
}, },
es2019: { es2019: {
Array: ["flat", "flatMap"], Array: ["flat", "flatMap"],
@ -627,8 +613,21 @@ namespace ts {
PromiseConstructor: ["any"], PromiseConstructor: ["any"],
String: ["replaceAll"] String: ["replaceAll"]
}, },
esnext: { es2022: {
NumberFormat: ["formatToParts"] Array: ["at"],
String: ["at"],
Int8Array: ["at"],
Uint8Array: ["at"],
Uint8ClampedArray: ["at"],
Int16Array: ["at"],
Uint16Array: ["at"],
Int32Array: ["at"],
Uint32Array: ["at"],
Float32Array: ["at"],
Float64Array: ["at"],
BigInt64Array: ["at"],
BigUint64Array: ["at"],
ObjectConstructor: ["hasOwn"]
} }
}; };
} }
@ -3161,7 +3160,7 @@ namespace ts {
return undefined; return undefined;
} }
export function isKeyword(token: SyntaxKind): boolean { export function isKeyword(token: SyntaxKind): token is KeywordSyntaxKind {
return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword; return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword;
} }
@ -3346,7 +3345,7 @@ namespace ts {
return node.escapedText === "push" || node.escapedText === "unshift"; return node.escapedText === "push" || node.escapedText === "unshift";
} }
export function isParameterDeclaration(node: VariableLikeDeclaration) { export function isParameterDeclaration(node: VariableLikeDeclaration): boolean {
const root = getRootDeclaration(node); const root = getRootDeclaration(node);
return root.kind === SyntaxKind.Parameter; return root.kind === SyntaxKind.Parameter;
} }
@ -6168,6 +6167,8 @@ namespace ts {
case ModuleKind.ES2020: case ModuleKind.ES2020:
case ModuleKind.ES2022: case ModuleKind.ES2022:
case ModuleKind.ESNext: case ModuleKind.ESNext:
case ModuleKind.Node12:
case ModuleKind.NodeNext:
return true; return true;
default: default:
return false; return false;
@ -6613,7 +6614,7 @@ namespace ts {
includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
basePaths: getBasePaths(absolutePath, includes, useCaseSensitiveFileNames) basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
}; };
} }
@ -6622,7 +6623,7 @@ namespace ts {
} }
/** @param path directory of the tsconfig.json */ /** @param path directory of the tsconfig.json */
export function matchFiles(path: string, extensions: readonly string[] | undefined, excludes: readonly string[] | undefined, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string, directoryExists: (path: string) => boolean): string[] { export function matchFiles(path: string, extensions: readonly string[] | undefined, excludes: readonly string[] | undefined, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string): string[] {
path = normalizePath(path); path = normalizePath(path);
currentDirectory = normalizePath(currentDirectory); currentDirectory = normalizePath(currentDirectory);
@ -6637,22 +6638,20 @@ namespace ts {
const results: string[][] = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]]; const results: string[][] = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]];
const visited = new Map<string, true>(); const visited = new Map<string, true>();
const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames); const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames);
for (const absoluteBasePath of patterns.basePaths) { for (const basePath of patterns.basePaths) {
if (directoryExists(absoluteBasePath)) { visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
visitDirectory(absoluteBasePath, depth);
}
} }
return flatten(results); return flatten(results);
function visitDirectory(absolutePath: string, depth: number | undefined) { function visitDirectory(path: string, absolutePath: string, depth: number | undefined) {
const canonicalPath = toCanonical(realpath(absolutePath)); const canonicalPath = toCanonical(realpath(absolutePath));
if (visited.has(canonicalPath)) return; if (visited.has(canonicalPath)) return;
visited.set(canonicalPath, true); visited.set(canonicalPath, true);
const { files, directories } = getFileSystemEntries(absolutePath); const { files, directories } = getFileSystemEntries(path);
for (const current of sort<string>(files, compareStringsCaseSensitive)) { for (const current of sort<string>(files, compareStringsCaseSensitive)) {
const name = combinePaths(absolutePath, current); const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current); const absoluteName = combinePaths(absolutePath, current);
if (extensions && !fileExtensionIsOneOf(name, extensions)) continue; if (extensions && !fileExtensionIsOneOf(name, extensions)) continue;
if (excludeRegex && excludeRegex.test(absoluteName)) continue; if (excludeRegex && excludeRegex.test(absoluteName)) continue;
@ -6675,10 +6674,11 @@ namespace ts {
} }
for (const current of sort<string>(directories, compareStringsCaseSensitive)) { for (const current of sort<string>(directories, compareStringsCaseSensitive)) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current); const absoluteName = combinePaths(absolutePath, current);
if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
(!excludeRegex || !excludeRegex.test(absoluteName))) { (!excludeRegex || !excludeRegex.test(absoluteName))) {
visitDirectory(absoluteName, depth); visitDirectory(name, absoluteName, depth);
} }
} }
} }
@ -6686,11 +6686,10 @@ namespace ts {
/** /**
* Computes the unique non-wildcard base paths amongst the provided include patterns. * Computes the unique non-wildcard base paths amongst the provided include patterns.
* @returns Absolute directory paths
*/ */
function getBasePaths(absoluteTsconfigPath: string, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean): string[] { function getBasePaths(path: string, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean): string[] {
// Storage for our results in the form of literal paths (e.g. the paths as written by the user). // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
const basePaths: string[] = [absoluteTsconfigPath]; const basePaths: string[] = [path];
if (includes) { if (includes) {
// Storage for literal base paths amongst the include patterns. // Storage for literal base paths amongst the include patterns.
@ -6698,9 +6697,9 @@ namespace ts {
for (const include of includes) { for (const include of includes) {
// We also need to check the relative paths by converting them to absolute and normalizing // We also need to check the relative paths by converting them to absolute and normalizing
// in case they escape the base path (e.g "..\somedirectory") // in case they escape the base path (e.g "..\somedirectory")
const absoluteIncludePath: string = isRootedDiskPath(include) ? include : normalizePath(combinePaths(absoluteTsconfigPath, include)); const absolute: string = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include));
// Append the literal and canonical candidate base paths. // Append the literal and canonical candidate base paths.
includeBasePaths.push(getIncludeBasePath(absoluteIncludePath)); includeBasePaths.push(getIncludeBasePath(absolute));
} }
// Sort the offsets array using either the literal or canonical path representations. // Sort the offsets array using either the literal or canonical path representations.
@ -6709,7 +6708,7 @@ namespace ts {
// Iterate over each include base path and include unique base paths that are not a // Iterate over each include base path and include unique base paths that are not a
// subpath of an existing base path // subpath of an existing base path
for (const includeBasePath of includeBasePaths) { for (const includeBasePath of includeBasePaths) {
if (every(basePaths, basePath => !containsPath(basePath, includeBasePath, absoluteTsconfigPath, !useCaseSensitiveFileNames))) { if (every(basePaths, basePath => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) {
basePaths.push(includeBasePath); basePaths.push(includeBasePath);
} }
} }
@ -6980,18 +6979,6 @@ namespace ts {
return { min, max }; return { min, max };
} }
/** @deprecated Use `ReadonlySet<TNode>` instead. */
export type ReadonlyNodeSet<TNode extends Node> = ReadonlySet<TNode>;
/** @deprecated Use `Set<TNode>` instead. */
export type NodeSet<TNode extends Node> = Set<TNode>;
/** @deprecated Use `ReadonlyMap<TNode, TValue>` instead. */
export type ReadonlyNodeMap<TNode extends Node, TValue> = ReadonlyESMap<TNode, TValue>;
/** @deprecated Use `Map<TNode, TValue>` instead. */
export type NodeMap<TNode extends Node, TValue> = ESMap<TNode, TValue>;
export function rangeOfNode(node: Node): TextRange { export function rangeOfNode(node: Node): TextRange {
return { pos: getTokenPosOfNode(node), end: node.end }; return { pos: getTokenPosOfNode(node), end: node.end };
} }
@ -7423,4 +7410,8 @@ namespace ts {
export function isFunctionExpressionOrArrowFunction(node: Node): node is FunctionExpression | ArrowFunction { export function isFunctionExpressionOrArrowFunction(node: Node): node is FunctionExpression | ArrowFunction {
return node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.ArrowFunction; return node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.ArrowFunction;
} }
export function escapeSnippetText(text: string): string {
return text.replace(/\$/gm, "\\$");
}
} }

View file

@ -14,6 +14,8 @@ namespace ts {
switch (getEmitScriptTarget(options)) { switch (getEmitScriptTarget(options)) {
case ScriptTarget.ESNext: case ScriptTarget.ESNext:
return "lib.esnext.full.d.ts"; return "lib.esnext.full.d.ts";
case ScriptTarget.ES2022:
return "lib.es2022.full.d.ts";
case ScriptTarget.ES2021: case ScriptTarget.ES2021:
return "lib.es2021.full.d.ts"; return "lib.es2021.full.d.ts";
case ScriptTarget.ES2020: case ScriptTarget.ES2020:

View file

@ -184,7 +184,7 @@ namespace ts {
const rootResult = tryReadDirectory(rootDir, rootDirPath); const rootResult = tryReadDirectory(rootDir, rootDirPath);
let rootSymLinkResult: FileSystemEntries | undefined; let rootSymLinkResult: FileSystemEntries | undefined;
if (rootResult !== undefined) { if (rootResult !== undefined) {
return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists); return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
} }
return host.readDirectory!(rootDir, extensions, excludes, includes, depth); return host.readDirectory!(rootDir, extensions, excludes, includes, depth);

View file

@ -95,7 +95,7 @@ namespace fakes {
} }
public readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] { public readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] {
return ts.matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, path => this.getAccessibleFileSystemEntries(path), path => this.realpath(path), path => this.directoryExists(path)); return ts.matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, path => this.getAccessibleFileSystemEntries(path), path => this.realpath(path));
} }
public getAccessibleFileSystemEntries(path: string): ts.FileSystemEntries { public getAccessibleFileSystemEntries(path: string): ts.FileSystemEntries {

View file

@ -1,11 +1,11 @@
namespace findUpDir { namespace Utils {
import { join, resolve, dirname } from "path"; const { join, resolve, dirname } = require("path") as typeof import("path");
import { existsSync } from "fs"; const { existsSync } = require("fs") as typeof import("fs");
// search directories upward to avoid hard-wired paths based on the // search directories upward to avoid hard-wired paths based on the
// build tree (same as scripts/build/findUpDir.js) // build tree (same as scripts/build/findUpDir.js)
export function findUpFile(name: string) { export function findUpFile(name: string): string {
let dir = __dirname; let dir = __dirname;
while (true) { while (true) {
const fullPath = join(dir, name); const fullPath = join(dir, name);

View file

@ -637,7 +637,8 @@ namespace FourSlash {
ts.forEachKey(this.inputFiles, fileName => { ts.forEachKey(this.inputFiles, fileName => {
if (!ts.isAnySupportedFileExtension(fileName) if (!ts.isAnySupportedFileExtension(fileName)
|| Harness.getConfigNameFromFileName(fileName) || Harness.getConfigNameFromFileName(fileName)
|| !ts.getAllowJSCompilerOption(this.getProgram().getCompilerOptions()) && !ts.resolutionExtensionIsTSOrJson(ts.extensionFromPath(fileName)) // Can't get a Program in Server tests
|| this.testType !== FourSlashTestType.Server && !ts.getAllowJSCompilerOption(this.getProgram().getCompilerOptions()) && !ts.resolutionExtensionIsTSOrJson(ts.extensionFromPath(fileName))
|| ts.getBaseFileName(fileName) === "package.json") return; || ts.getBaseFileName(fileName) === "package.json") return;
const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion); const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion);
if (errors.length) { if (errors.length) {
@ -942,7 +943,7 @@ namespace FourSlash {
expected = typeof expected === "string" ? { name: expected } : expected; expected = typeof expected === "string" ? { name: expected } : expected;
if (actual.insertText !== expected.insertText) { if (actual.insertText !== expected.insertText) {
this.raiseError(`Expected completion insert text to be ${expected.insertText}, got ${actual.insertText}`); this.raiseError(`Completion insert text did not match: ${showTextDiff(expected.insertText || "", actual.insertText || "")}`);
} }
const convertedReplacementSpan = expected.replacementSpan && ts.createTextSpanFromRange(expected.replacementSpan); const convertedReplacementSpan = expected.replacementSpan && ts.createTextSpanFromRange(expected.replacementSpan);
if (convertedReplacementSpan?.length) { if (convertedReplacementSpan?.length) {

View file

@ -41,6 +41,7 @@ namespace Harness {
export const virtualFileSystemRoot = "/"; export const virtualFileSystemRoot = "/";
function createNodeIO(): IO { function createNodeIO(): IO {
const workspaceRoot = Utils.findUpRoot();
let fs: any, pathModule: any; let fs: any, pathModule: any;
if (require) { if (require) {
fs = require("fs"); fs = require("fs");
@ -154,7 +155,7 @@ namespace Harness {
log: s => console.log(s), log: s => console.log(s),
args: () => ts.sys.args, args: () => ts.sys.args,
getExecutingFilePath: () => ts.sys.getExecutingFilePath(), getExecutingFilePath: () => ts.sys.getExecutingFilePath(),
getWorkspaceRoot: () => vpath.resolve(__dirname, "../.."), getWorkspaceRoot: () => workspaceRoot,
exit: exitCode => ts.sys.exit(exitCode), exit: exitCode => ts.sys.exit(exitCode),
readDirectory: (path, extension, exclude, include, depth) => ts.sys.readDirectory(path, extension, exclude, include, depth), readDirectory: (path, extension, exclude, include, depth) => ts.sys.readDirectory(path, extension, exclude, include, depth),
getAccessibleFileSystemEntries, getAccessibleFileSystemEntries,

View file

@ -28,6 +28,7 @@
"evaluatorImpl.ts", "evaluatorImpl.ts",
"fakesHosts.ts", "fakesHosts.ts",
"client.ts", "client.ts",
"findUpDir.ts",
"runnerbase.ts", "runnerbase.ts",
"sourceMapRecorder.ts", "sourceMapRecorder.ts",

View file

@ -922,7 +922,7 @@ interface Array<T> { length: number; [n: number]: T; }`
}); });
} }
return { directories, files }; return { directories, files };
}, path => this.realpath(path), path => this.directoryExists(path)); }, path => this.realpath(path));
} }
createHash(s: string): string { createHash(s: string): string {

View file

@ -53,8 +53,8 @@ interface AnimationEventInit extends EventInit {
} }
interface AnimationPlaybackEventInit extends EventInit { interface AnimationPlaybackEventInit extends EventInit {
currentTime?: number | null; currentTime?: CSSNumberish | null;
timelineTime?: number | null; timelineTime?: CSSNumberish | null;
} }
interface AssignedNodesOptions { interface AssignedNodesOptions {
@ -808,6 +808,7 @@ interface MediaTrackCapabilities {
interface MediaTrackConstraintSet { interface MediaTrackConstraintSet {
aspectRatio?: ConstrainDouble; aspectRatio?: ConstrainDouble;
autoGainControl?: ConstrainBoolean;
channelCount?: ConstrainULong; channelCount?: ConstrainULong;
deviceId?: ConstrainDOMString; deviceId?: ConstrainDOMString;
echoCancellation?: ConstrainBoolean; echoCancellation?: ConstrainBoolean;
@ -816,6 +817,7 @@ interface MediaTrackConstraintSet {
groupId?: ConstrainDOMString; groupId?: ConstrainDOMString;
height?: ConstrainULong; height?: ConstrainULong;
latency?: ConstrainDouble; latency?: ConstrainDouble;
noiseSuppression?: ConstrainBoolean;
sampleRate?: ConstrainULong; sampleRate?: ConstrainULong;
sampleSize?: ConstrainULong; sampleSize?: ConstrainULong;
suppressLocalAudioPlayback?: ConstrainBoolean; suppressLocalAudioPlayback?: ConstrainBoolean;
@ -828,12 +830,14 @@ interface MediaTrackConstraints extends MediaTrackConstraintSet {
interface MediaTrackSettings { interface MediaTrackSettings {
aspectRatio?: number; aspectRatio?: number;
autoGainControl?: boolean;
deviceId?: string; deviceId?: string;
echoCancellation?: boolean; echoCancellation?: boolean;
facingMode?: string; facingMode?: string;
frameRate?: number; frameRate?: number;
groupId?: string; groupId?: string;
height?: number; height?: number;
noiseSuppression?: boolean;
restrictOwnAudio?: boolean; restrictOwnAudio?: boolean;
sampleRate?: number; sampleRate?: number;
sampleSize?: number; sampleSize?: number;
@ -842,12 +846,14 @@ interface MediaTrackSettings {
interface MediaTrackSupportedConstraints { interface MediaTrackSupportedConstraints {
aspectRatio?: boolean; aspectRatio?: boolean;
autoGainControl?: boolean;
deviceId?: boolean; deviceId?: boolean;
echoCancellation?: boolean; echoCancellation?: boolean;
facingMode?: boolean; facingMode?: boolean;
frameRate?: boolean; frameRate?: boolean;
groupId?: boolean; groupId?: boolean;
height?: boolean; height?: boolean;
noiseSuppression?: boolean;
sampleRate?: boolean; sampleRate?: boolean;
sampleSize?: boolean; sampleSize?: boolean;
suppressLocalAudioPlayback?: boolean; suppressLocalAudioPlayback?: boolean;
@ -1463,7 +1469,7 @@ interface RequestInit {
/** An AbortSignal to set request's signal. */ /** An AbortSignal to set request's signal. */
signal?: AbortSignal | null; signal?: AbortSignal | null;
/** Can only be null. Used to disassociate request from any Window. */ /** Can only be null. Used to disassociate request from any Window. */
window?: any; window?: null;
} }
interface ResizeObserverOptions { interface ResizeObserverOptions {
@ -1867,7 +1873,7 @@ interface AbortSignal extends EventTarget {
declare var AbortSignal: { declare var AbortSignal: {
prototype: AbortSignal; prototype: AbortSignal;
new(): AbortSignal; new(): AbortSignal;
// abort(): AbortSignal; // abort(): AbortSignal; - To be re-added in the future
}; };
interface AbstractRange { interface AbstractRange {
@ -1930,7 +1936,7 @@ interface AnimationEventMap {
} }
interface Animation extends EventTarget { interface Animation extends EventTarget {
currentTime: number | null; currentTime: CSSNumberish | null;
effect: AnimationEffect | null; effect: AnimationEffect | null;
readonly finished: Promise<Animation>; readonly finished: Promise<Animation>;
id: string; id: string;
@ -1942,7 +1948,7 @@ interface Animation extends EventTarget {
playbackRate: number; playbackRate: number;
readonly ready: Promise<Animation>; readonly ready: Promise<Animation>;
readonly replaceState: AnimationReplaceState; readonly replaceState: AnimationReplaceState;
startTime: number | null; startTime: CSSNumberish | null;
timeline: AnimationTimeline | null; timeline: AnimationTimeline | null;
cancel(): void; cancel(): void;
commitStyles(): void; commitStyles(): void;
@ -1992,8 +1998,8 @@ interface AnimationFrameProvider {
} }
interface AnimationPlaybackEvent extends Event { interface AnimationPlaybackEvent extends Event {
readonly currentTime: number | null; readonly currentTime: CSSNumberish | null;
readonly timelineTime: number | null; readonly timelineTime: CSSNumberish | null;
} }
declare var AnimationPlaybackEvent: { declare var AnimationPlaybackEvent: {
@ -2208,6 +2214,7 @@ declare var AudioScheduledSourceNode: {
new(): AudioScheduledSourceNode; new(): AudioScheduledSourceNode;
}; };
/** Available only in secure contexts. */
interface AudioWorklet extends Worklet { interface AudioWorklet extends Worklet {
} }
@ -2220,6 +2227,7 @@ interface AudioWorkletNodeEventMap {
"processorerror": Event; "processorerror": Event;
} }
/** Available only in secure contexts. */
interface AudioWorkletNode extends AudioNode { interface AudioWorkletNode extends AudioNode {
onprocessorerror: ((this: AudioWorkletNode, ev: Event) => any) | null; onprocessorerror: ((this: AudioWorkletNode, ev: Event) => any) | null;
readonly parameters: AudioParamMap; readonly parameters: AudioParamMap;
@ -2235,6 +2243,7 @@ declare var AudioWorkletNode: {
new(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode; new(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode;
}; };
/** Available only in secure contexts. */
interface AuthenticatorAssertionResponse extends AuthenticatorResponse { interface AuthenticatorAssertionResponse extends AuthenticatorResponse {
readonly authenticatorData: ArrayBuffer; readonly authenticatorData: ArrayBuffer;
readonly signature: ArrayBuffer; readonly signature: ArrayBuffer;
@ -2246,6 +2255,7 @@ declare var AuthenticatorAssertionResponse: {
new(): AuthenticatorAssertionResponse; new(): AuthenticatorAssertionResponse;
}; };
/** Available only in secure contexts. */
interface AuthenticatorAttestationResponse extends AuthenticatorResponse { interface AuthenticatorAttestationResponse extends AuthenticatorResponse {
readonly attestationObject: ArrayBuffer; readonly attestationObject: ArrayBuffer;
} }
@ -2255,6 +2265,7 @@ declare var AuthenticatorAttestationResponse: {
new(): AuthenticatorAttestationResponse; new(): AuthenticatorAttestationResponse;
}; };
/** Available only in secure contexts. */
interface AuthenticatorResponse { interface AuthenticatorResponse {
readonly clientDataJSON: ArrayBuffer; readonly clientDataJSON: ArrayBuffer;
} }
@ -2278,6 +2289,7 @@ interface BaseAudioContextEventMap {
} }
interface BaseAudioContext extends EventTarget { interface BaseAudioContext extends EventTarget {
/** Available only in secure contexts. */
readonly audioWorklet: AudioWorklet; readonly audioWorklet: AudioWorklet;
readonly currentTime: number; readonly currentTime: number;
readonly destination: AudioDestinationNode; readonly destination: AudioDestinationNode;
@ -2600,6 +2612,7 @@ declare var CSSRuleList: {
/** An object that is a CSS declaration block, and exposes style information and various style-related methods and properties. */ /** An object that is a CSS declaration block, and exposes style information and various style-related methods and properties. */
interface CSSStyleDeclaration { interface CSSStyleDeclaration {
accentColor: string;
alignContent: string; alignContent: string;
alignItems: string; alignItems: string;
alignSelf: string; alignSelf: string;
@ -2773,11 +2786,14 @@ interface CSSStyleDeclaration {
gridAutoRows: string; gridAutoRows: string;
gridColumn: string; gridColumn: string;
gridColumnEnd: string; gridColumnEnd: string;
/** @deprecated This is a legacy alias of `columnGap`. */
gridColumnGap: string; gridColumnGap: string;
gridColumnStart: string; gridColumnStart: string;
/** @deprecated This is a legacy alias of `gap`. */
gridGap: string; gridGap: string;
gridRow: string; gridRow: string;
gridRowEnd: string; gridRowEnd: string;
/** @deprecated This is a legacy alias of `rowGap`. */
gridRowGap: string; gridRowGap: string;
gridRowStart: string; gridRowStart: string;
gridTemplate: string; gridTemplate: string;
@ -3016,15 +3032,15 @@ interface CSSStyleDeclaration {
webkitBorderTopLeftRadius: string; webkitBorderTopLeftRadius: string;
/** @deprecated This is a legacy alias of `borderTopRightRadius`. */ /** @deprecated This is a legacy alias of `borderTopRightRadius`. */
webkitBorderTopRightRadius: string; webkitBorderTopRightRadius: string;
/** @deprecated */ /** @deprecated This is a legacy alias of `boxAlign`. */
webkitBoxAlign: string; webkitBoxAlign: string;
/** @deprecated */ /** @deprecated This is a legacy alias of `boxFlex`. */
webkitBoxFlex: string; webkitBoxFlex: string;
/** @deprecated */ /** @deprecated This is a legacy alias of `boxOrdinalGroup`. */
webkitBoxOrdinalGroup: string; webkitBoxOrdinalGroup: string;
/** @deprecated */ /** @deprecated This is a legacy alias of `boxOrient`. */
webkitBoxOrient: string; webkitBoxOrient: string;
/** @deprecated */ /** @deprecated This is a legacy alias of `boxPack`. */
webkitBoxPack: string; webkitBoxPack: string;
/** @deprecated This is a legacy alias of `boxShadow`. */ /** @deprecated This is a legacy alias of `boxShadow`. */
webkitBoxShadow: string; webkitBoxShadow: string;
@ -3179,7 +3195,10 @@ declare var CSSTransition: {
new(): CSSTransition; new(): CSSTransition;
}; };
/** Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. */ /**
* Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec.
* Available only in secure contexts.
*/
interface Cache { interface Cache {
add(request: RequestInfo): Promise<void>; add(request: RequestInfo): Promise<void>;
addAll(requests: RequestInfo[]): Promise<void>; addAll(requests: RequestInfo[]): Promise<void>;
@ -3195,7 +3214,10 @@ declare var Cache: {
new(): Cache; new(): Cache;
}; };
/** The storage for Cache objects. */ /**
* The storage for Cache objects.
* Available only in secure contexts.
*/
interface CacheStorage { interface CacheStorage {
delete(cacheName: string): Promise<boolean>; delete(cacheName: string): Promise<boolean>;
has(cacheName: string): Promise<boolean>; has(cacheName: string): Promise<boolean>;
@ -3427,6 +3449,7 @@ interface ChildNode extends Node {
interface ClientRect extends DOMRect { interface ClientRect extends DOMRect {
} }
/** Available only in secure contexts. */
interface Clipboard extends EventTarget { interface Clipboard extends EventTarget {
read(): Promise<ClipboardItems>; read(): Promise<ClipboardItems>;
readText(): Promise<string>; readText(): Promise<string>;
@ -3530,6 +3553,7 @@ declare var CountQueuingStrategy: {
new(init: QueuingStrategyInit): CountQueuingStrategy; new(init: QueuingStrategyInit): CountQueuingStrategy;
}; };
/** Available only in secure contexts. */
interface Credential { interface Credential {
readonly id: string; readonly id: string;
readonly type: string; readonly type: string;
@ -3540,6 +3564,7 @@ declare var Credential: {
new(): Credential; new(): Credential;
}; };
/** Available only in secure contexts. */
interface CredentialsContainer { interface CredentialsContainer {
create(options?: CredentialCreationOptions): Promise<Credential | null>; create(options?: CredentialCreationOptions): Promise<Credential | null>;
get(options?: CredentialRequestOptions): Promise<Credential | null>; get(options?: CredentialRequestOptions): Promise<Credential | null>;
@ -3554,6 +3579,7 @@ declare var CredentialsContainer: {
/** Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */ /** Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */
interface Crypto { interface Crypto {
/** Available only in secure contexts. */
readonly subtle: SubtleCrypto; readonly subtle: SubtleCrypto;
getRandomValues<T extends ArrayBufferView | null>(array: T): T; getRandomValues<T extends ArrayBufferView | null>(array: T): T;
} }
@ -3563,7 +3589,10 @@ declare var Crypto: {
new(): Crypto; new(): Crypto;
}; };
/** The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. */ /**
* The CryptoKey dictionary of the Web Crypto API represents a cryptographic key.
* Available only in secure contexts.
*/
interface CryptoKey { interface CryptoKey {
readonly algorithm: KeyAlgorithm; readonly algorithm: KeyAlgorithm;
readonly extractable: boolean; readonly extractable: boolean;
@ -4071,7 +4100,10 @@ declare var DelayNode: {
new(context: BaseAudioContext, options?: DelayOptions): DelayNode; new(context: BaseAudioContext, options?: DelayOptions): DelayNode;
}; };
/** The DeviceMotionEvent provides web developers with information about the speed of changes for the device's position and orientation. */ /**
* The DeviceMotionEvent provides web developers with information about the speed of changes for the device's position and orientation.
* Available only in secure contexts.
*/
interface DeviceMotionEvent extends Event { interface DeviceMotionEvent extends Event {
readonly acceleration: DeviceMotionEventAcceleration | null; readonly acceleration: DeviceMotionEventAcceleration | null;
readonly accelerationIncludingGravity: DeviceMotionEventAcceleration | null; readonly accelerationIncludingGravity: DeviceMotionEventAcceleration | null;
@ -4084,19 +4116,24 @@ declare var DeviceMotionEvent: {
new(type: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; new(type: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent;
}; };
/** Available only in secure contexts. */
interface DeviceMotionEventAcceleration { interface DeviceMotionEventAcceleration {
readonly x: number | null; readonly x: number | null;
readonly y: number | null; readonly y: number | null;
readonly z: number | null; readonly z: number | null;
} }
/** Available only in secure contexts. */
interface DeviceMotionEventRotationRate { interface DeviceMotionEventRotationRate {
readonly alpha: number | null; readonly alpha: number | null;
readonly beta: number | null; readonly beta: number | null;
readonly gamma: number | null; readonly gamma: number | null;
} }
/** The DeviceOrientationEvent provides web developers with information from the physical orientation of the device running the web page. */ /**
* The DeviceOrientationEvent provides web developers with information from the physical orientation of the device running the web page.
* Available only in secure contexts.
*/
interface DeviceOrientationEvent extends Event { interface DeviceOrientationEvent extends Event {
readonly absolute: boolean; readonly absolute: boolean;
readonly alpha: number | null; readonly alpha: number | null;
@ -4394,13 +4431,6 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad
* @param filter A custom NodeFilter function to use. * @param filter A custom NodeFilter function to use.
*/ */
createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null): TreeWalker; createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null): TreeWalker;
/**
* Returns the element for the specified x coordinate and the specified y coordinate.
* @param x The x-offset
* @param y The y-offset
*/
elementFromPoint(x: number, y: number): Element | null;
elementsFromPoint(x: number, y: number): Element[];
/** /**
* Executes a command on the current document, current selection, or the given range. * Executes a command on the current document, current selection, or the given range.
* @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script.
@ -4558,6 +4588,13 @@ interface DocumentOrShadowRoot {
readonly pointerLockElement: Element | null; readonly pointerLockElement: 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. */ /** Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. */
readonly styleSheets: StyleSheetList; readonly styleSheets: StyleSheetList;
/**
* Returns the element for the specified x coordinate and the specified y coordinate.
* @param x The x-offset
* @param y The y-offset
*/
elementFromPoint(x: number, y: number): Element | null;
elementsFromPoint(x: number, y: number): Element[];
getAnimations(): Animation[]; getAnimations(): Animation[];
} }
@ -4785,6 +4822,16 @@ interface ElementContentEditable {
readonly isContentEditable: boolean; readonly isContentEditable: boolean;
} }
interface ElementInternals extends ARIAMixin {
/** Returns the ShadowRoot for internals's target element, if the target element is a shadow host, or null otherwise. */
readonly shadowRoot: ShadowRoot | null;
}
declare var ElementInternals: {
prototype: ElementInternals;
new(): ElementInternals;
};
/** Events providing information related to errors in scripts or in files. */ /** Events providing information related to errors in scripts or in files. */
interface ErrorEvent extends Event { interface ErrorEvent extends Event {
readonly colno: number; readonly colno: number;
@ -5024,13 +5071,10 @@ declare var FileSystemDirectoryEntry: {
new(): FileSystemDirectoryEntry; new(): FileSystemDirectoryEntry;
}; };
/** @deprecated */
interface FileSystemDirectoryReader { interface FileSystemDirectoryReader {
/** @deprecated */
readEntries(successCallback: FileSystemEntriesCallback, errorCallback?: ErrorCallback): void; readEntries(successCallback: FileSystemEntriesCallback, errorCallback?: ErrorCallback): void;
} }
/** @deprecated */
declare var FileSystemDirectoryReader: { declare var FileSystemDirectoryReader: {
prototype: FileSystemDirectoryReader; prototype: FileSystemDirectoryReader;
new(): FileSystemDirectoryReader; new(): FileSystemDirectoryReader;
@ -5167,7 +5211,10 @@ declare var GainNode: {
new(context: BaseAudioContext, options?: GainOptions): GainNode; new(context: BaseAudioContext, options?: GainOptions): GainNode;
}; };
/** This Gamepad API interface defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id. */ /**
* This Gamepad API interface defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id.
* Available only in secure contexts.
*/
interface Gamepad { interface Gamepad {
readonly axes: ReadonlyArray<number>; readonly axes: ReadonlyArray<number>;
readonly buttons: ReadonlyArray<GamepadButton>; readonly buttons: ReadonlyArray<GamepadButton>;
@ -5184,7 +5231,10 @@ declare var Gamepad: {
new(): Gamepad; new(): Gamepad;
}; };
/** An individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device. */ /**
* An individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device.
* Available only in secure contexts.
*/
interface GamepadButton { interface GamepadButton {
readonly pressed: boolean; readonly pressed: boolean;
readonly touched: boolean; readonly touched: boolean;
@ -5196,7 +5246,10 @@ declare var GamepadButton: {
new(): GamepadButton; new(): GamepadButton;
}; };
/** This Gamepad API interface contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to. */ /**
* This Gamepad API interface contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to.
* Available only in secure contexts.
*/
interface GamepadEvent extends Event { interface GamepadEvent extends Event {
readonly gamepad: Gamepad; readonly gamepad: Gamepad;
} }
@ -5233,6 +5286,7 @@ declare var Geolocation: {
new(): Geolocation; new(): Geolocation;
}; };
/** Available only in secure contexts. */
interface GeolocationCoordinates { interface GeolocationCoordinates {
readonly accuracy: number; readonly accuracy: number;
readonly altitude: number | null; readonly altitude: number | null;
@ -5248,6 +5302,7 @@ declare var GeolocationCoordinates: {
new(): GeolocationCoordinates; new(): GeolocationCoordinates;
}; };
/** Available only in secure contexts. */
interface GeolocationPosition { interface GeolocationPosition {
readonly coords: GeolocationCoordinates; readonly coords: GeolocationCoordinates;
readonly timestamp: DOMTimeStamp; readonly timestamp: DOMTimeStamp;
@ -6072,6 +6127,7 @@ interface HTMLElement extends Element, DocumentAndElementEventHandlers, ElementC
spellcheck: boolean; spellcheck: boolean;
title: string; title: string;
translate: boolean; translate: boolean;
attachInternals(): ElementInternals;
click(): void; click(): void;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@ -6933,6 +6989,7 @@ interface HTMLMediaElement extends HTMLElement {
readonly error: MediaError | null; readonly error: MediaError | null;
/** Gets or sets a flag to specify whether playback should restart after it completes. */ /** Gets or sets a flag to specify whether playback should restart after it completes. */
loop: boolean; loop: boolean;
/** Available only in secure contexts. */
readonly mediaKeys: MediaKeys | null; readonly mediaKeys: MediaKeys | null;
/** Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. */ /** Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. */
muted: boolean; muted: boolean;
@ -6970,6 +7027,7 @@ interface HTMLMediaElement extends HTMLElement {
pause(): void; pause(): void;
/** Loads and starts playback of a media resource. */ /** Loads and starts playback of a media resource. */
play(): Promise<void>; play(): Promise<void>;
/** Available only in secure contexts. */
setMediaKeys(mediaKeys: MediaKeys | null): Promise<void>; setMediaKeys(mediaKeys: MediaKeys | null): Promise<void>;
readonly HAVE_CURRENT_DATA: number; readonly HAVE_CURRENT_DATA: number;
readonly HAVE_ENOUGH_DATA: number; readonly HAVE_ENOUGH_DATA: number;
@ -7523,6 +7581,7 @@ declare var HTMLSelectElement: {
interface HTMLSlotElement extends HTMLElement { interface HTMLSlotElement extends HTMLElement {
name: string; name: string;
assign(...nodes: (Element | Text)[]): void;
assignedElements(options?: AssignedNodesOptions): Element[]; assignedElements(options?: AssignedNodesOptions): Element[];
assignedNodes(options?: AssignedNodesOptions): Node[]; assignedNodes(options?: AssignedNodesOptions): Node[];
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@ -8797,7 +8856,10 @@ declare var MediaCapabilities: {
new(): MediaCapabilities; new(): MediaCapabilities;
}; };
/** The MediaDevicesInfo interface contains information that describes a single media input or output device. */ /**
* The MediaDevicesInfo interface contains information that describes a single media input or output device.
* Available only in secure contexts.
*/
interface MediaDeviceInfo { interface MediaDeviceInfo {
readonly deviceId: string; readonly deviceId: string;
readonly groupId: string; readonly groupId: string;
@ -8815,7 +8877,10 @@ interface MediaDevicesEventMap {
"devicechange": Event; "devicechange": Event;
} }
/** Provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data. */ /**
* Provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data.
* Available only in secure contexts.
*/
interface MediaDevices extends EventTarget { interface MediaDevices extends EventTarget {
ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; ondevicechange: ((this: MediaDevices, ev: Event) => any) | null;
enumerateDevices(): Promise<MediaDeviceInfo[]>; enumerateDevices(): Promise<MediaDeviceInfo[]>;
@ -8872,7 +8937,10 @@ declare var MediaError: {
readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;
}; };
/** This EncryptedMediaExtensions API interface contains the content and related data when the content decryption module generates a message for the session. */ /**
* This EncryptedMediaExtensions API interface contains the content and related data when the content decryption module generates a message for the session.
* Available only in secure contexts.
*/
interface MediaKeyMessageEvent extends Event { interface MediaKeyMessageEvent extends Event {
readonly message: ArrayBuffer; readonly message: ArrayBuffer;
readonly messageType: MediaKeyMessageType; readonly messageType: MediaKeyMessageType;
@ -8888,7 +8956,10 @@ interface MediaKeySessionEventMap {
"message": MediaKeyMessageEvent; "message": MediaKeyMessageEvent;
} }
/** This EncryptedMediaExtensions API interface represents a context for message exchange with a content decryption module (CDM). */ /**
* This EncryptedMediaExtensions API interface represents a context for message exchange with a content decryption module (CDM).
* Available only in secure contexts.
*/
interface MediaKeySession extends EventTarget { interface MediaKeySession extends EventTarget {
readonly closed: Promise<MediaKeySessionClosedReason>; readonly closed: Promise<MediaKeySessionClosedReason>;
readonly expiration: number; readonly expiration: number;
@ -8912,7 +8983,10 @@ declare var MediaKeySession: {
new(): MediaKeySession; new(): MediaKeySession;
}; };
/** This EncryptedMediaExtensions API interface is a read-only map of media key statuses by key IDs. */ /**
* This EncryptedMediaExtensions API interface is a read-only map of media key statuses by key IDs.
* Available only in secure contexts.
*/
interface MediaKeyStatusMap { interface MediaKeyStatusMap {
readonly size: number; readonly size: number;
get(keyId: BufferSource): MediaKeyStatus | undefined; get(keyId: BufferSource): MediaKeyStatus | undefined;
@ -8925,7 +8999,10 @@ declare var MediaKeyStatusMap: {
new(): MediaKeyStatusMap; new(): MediaKeyStatusMap;
}; };
/** This EncryptedMediaExtensions API interface provides access to a Key System for decryption and/or a content protection provider. You can request an instance of this object using the Navigator.requestMediaKeySystemAccess method. */ /**
* This EncryptedMediaExtensions API interface provides access to a Key System for decryption and/or a content protection provider. You can request an instance of this object using the Navigator.requestMediaKeySystemAccess method.
* Available only in secure contexts.
*/
interface MediaKeySystemAccess { interface MediaKeySystemAccess {
readonly keySystem: string; readonly keySystem: string;
createMediaKeys(): Promise<MediaKeys>; createMediaKeys(): Promise<MediaKeys>;
@ -8937,7 +9014,10 @@ declare var MediaKeySystemAccess: {
new(): MediaKeySystemAccess; new(): MediaKeySystemAccess;
}; };
/** This EncryptedMediaExtensions API interface the represents a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback. */ /**
* This EncryptedMediaExtensions API interface the represents a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback.
* Available only in secure contexts.
*/
interface MediaKeys { interface MediaKeys {
createSession(sessionType?: MediaKeySessionType): MediaKeySession; createSession(sessionType?: MediaKeySessionType): MediaKeySession;
setServerCertificate(serverCertificate: BufferSource): Promise<boolean>; setServerCertificate(serverCertificate: BufferSource): Promise<boolean>;
@ -9011,7 +9091,7 @@ declare var MediaQueryListEvent: {
interface MediaRecorderEventMap { interface MediaRecorderEventMap {
"dataavailable": BlobEvent; "dataavailable": BlobEvent;
"error": Event; "error": MediaRecorderErrorEvent;
"pause": Event; "pause": Event;
"resume": Event; "resume": Event;
"start": Event; "start": Event;
@ -9022,7 +9102,7 @@ interface MediaRecorder extends EventTarget {
readonly audioBitsPerSecond: number; readonly audioBitsPerSecond: number;
readonly mimeType: string; readonly mimeType: string;
ondataavailable: ((this: MediaRecorder, ev: BlobEvent) => any) | null; ondataavailable: ((this: MediaRecorder, ev: BlobEvent) => any) | null;
onerror: ((this: MediaRecorder, ev: Event) => any) | null; onerror: ((this: MediaRecorder, ev: MediaRecorderErrorEvent) => any) | null;
onpause: ((this: MediaRecorder, ev: Event) => any) | null; onpause: ((this: MediaRecorder, ev: Event) => any) | null;
onresume: ((this: MediaRecorder, ev: Event) => any) | null; onresume: ((this: MediaRecorder, ev: Event) => any) | null;
onstart: ((this: MediaRecorder, ev: Event) => any) | null; onstart: ((this: MediaRecorder, ev: Event) => any) | null;
@ -9441,20 +9521,27 @@ declare var NamedNodeMap: {
/** The state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities. */ /** The state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities. */
interface Navigator extends NavigatorAutomationInformation, NavigatorConcurrentHardware, NavigatorContentUtils, NavigatorCookies, NavigatorID, NavigatorLanguage, NavigatorNetworkInformation, NavigatorOnLine, NavigatorPlugins, NavigatorStorage { interface Navigator extends NavigatorAutomationInformation, NavigatorConcurrentHardware, NavigatorContentUtils, NavigatorCookies, NavigatorID, NavigatorLanguage, NavigatorNetworkInformation, NavigatorOnLine, NavigatorPlugins, NavigatorStorage {
/** Available only in secure contexts. */
readonly clipboard: Clipboard; readonly clipboard: Clipboard;
/** Available only in secure contexts. */
readonly credentials: CredentialsContainer; readonly credentials: CredentialsContainer;
readonly doNotTrack: string | null; readonly doNotTrack: string | null;
readonly geolocation: Geolocation; readonly geolocation: Geolocation;
readonly maxTouchPoints: number; readonly maxTouchPoints: number;
readonly mediaCapabilities: MediaCapabilities; readonly mediaCapabilities: MediaCapabilities;
/** Available only in secure contexts. */
readonly mediaDevices: MediaDevices; readonly mediaDevices: MediaDevices;
readonly mediaSession: MediaSession; readonly mediaSession: MediaSession;
readonly permissions: Permissions; readonly permissions: Permissions;
readonly pointerEnabled: boolean; /** Available only in secure contexts. */
readonly serviceWorker: ServiceWorkerContainer; readonly serviceWorker: ServiceWorkerContainer;
/** Available only in secure contexts. */
canShare(data?: ShareData): boolean;
getGamepads(): (Gamepad | null)[]; getGamepads(): (Gamepad | null)[];
/** Available only in secure contexts. */
requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise<MediaKeySystemAccess>; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise<MediaKeySystemAccess>;
sendBeacon(url: string | URL, data?: BodyInit | null): boolean; sendBeacon(url: string | URL, data?: BodyInit | null): boolean;
/** Available only in secure contexts. */
share(data?: ShareData): Promise<void>; share(data?: ShareData): Promise<void>;
vibrate(pattern: VibratePattern): boolean; vibrate(pattern: VibratePattern): boolean;
} }
@ -9473,6 +9560,7 @@ interface NavigatorConcurrentHardware {
} }
interface NavigatorContentUtils { interface NavigatorContentUtils {
/** Available only in secure contexts. */
registerProtocolHandler(scheme: string, url: string | URL): void; registerProtocolHandler(scheme: string, url: string | URL): void;
} }
@ -9521,6 +9609,7 @@ interface NavigatorPlugins {
javaEnabled(): boolean; javaEnabled(): boolean;
} }
/** Available only in secure contexts. */
interface NavigatorStorage { interface NavigatorStorage {
readonly storage: StorageManager; readonly storage: StorageManager;
} }
@ -9948,41 +10037,7 @@ declare var Path2D: {
new(path?: Path2D | string): Path2D; new(path?: Path2D | string): Path2D;
}; };
/** /** Available only in secure contexts. */
* This Payment Request API interface is used to store shipping or payment address information.
* @deprecated
*/
interface PaymentAddress {
/** @deprecated */
readonly addressLine: ReadonlyArray<string>;
/** @deprecated */
readonly city: string;
/** @deprecated */
readonly country: string;
/** @deprecated */
readonly dependentLocality: string;
/** @deprecated */
readonly organization: string;
/** @deprecated */
readonly phone: string;
/** @deprecated */
readonly postalCode: string;
/** @deprecated */
readonly recipient: string;
/** @deprecated */
readonly region: string;
/** @deprecated */
readonly sortingCode: string;
/** @deprecated */
toJSON(): any;
}
/** @deprecated */
declare var PaymentAddress: {
prototype: PaymentAddress;
new(): PaymentAddress;
};
interface PaymentMethodChangeEvent extends PaymentRequestUpdateEvent { interface PaymentMethodChangeEvent extends PaymentRequestUpdateEvent {
readonly methodDetails: any; readonly methodDetails: any;
readonly methodName: string; readonly methodName: string;
@ -9997,7 +10052,10 @@ interface PaymentRequestEventMap {
"paymentmethodchange": Event; "paymentmethodchange": Event;
} }
/** This Payment Request API interface is the primary access point into the API, and lets web content and apps accept payments from the end user. */ /**
* This Payment Request API interface is the primary access point into the API, and lets web content and apps accept payments from the end user.
* Available only in secure contexts.
*/
interface PaymentRequest extends EventTarget { interface PaymentRequest extends EventTarget {
readonly id: string; readonly id: string;
onpaymentmethodchange: ((this: PaymentRequest, ev: Event) => any) | null; onpaymentmethodchange: ((this: PaymentRequest, ev: Event) => any) | null;
@ -10015,7 +10073,10 @@ declare var PaymentRequest: {
new(methodData: PaymentMethodData[], details: PaymentDetailsInit): PaymentRequest; new(methodData: PaymentMethodData[], details: PaymentDetailsInit): PaymentRequest;
}; };
/** This Payment Request API interface enables a web page to update the details of a PaymentRequest in response to a user action. */ /**
* This Payment Request API interface enables a web page to update the details of a PaymentRequest in response to a user action.
* Available only in secure contexts.
*/
interface PaymentRequestUpdateEvent extends Event { interface PaymentRequestUpdateEvent extends Event {
updateWith(detailsPromise: PaymentDetailsUpdate | PromiseLike<PaymentDetailsUpdate>): void; updateWith(detailsPromise: PaymentDetailsUpdate | PromiseLike<PaymentDetailsUpdate>): void;
} }
@ -10025,7 +10086,10 @@ declare var PaymentRequestUpdateEvent: {
new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent;
}; };
/** This Payment Request API interface is returned after a user selects a payment method and approves a payment request. */ /**
* This Payment Request API interface is returned after a user selects a payment method and approves a payment request.
* Available only in secure contexts.
*/
interface PaymentResponse extends EventTarget { interface PaymentResponse extends EventTarget {
readonly details: any; readonly details: any;
readonly methodName: string; readonly methodName: string;
@ -10425,6 +10489,7 @@ interface PointerEvent extends MouseEvent {
readonly tiltY: number; readonly tiltY: number;
readonly twist: number; readonly twist: number;
readonly width: number; readonly width: number;
/** Available only in secure contexts. */
getCoalescedEvents(): PointerEvent[]; getCoalescedEvents(): PointerEvent[];
getPredictedEvents(): PointerEvent[]; getPredictedEvents(): PointerEvent[];
} }
@ -10479,6 +10544,7 @@ declare var PromiseRejectionEvent: {
new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent; new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent;
}; };
/** Available only in secure contexts. */
interface PublicKeyCredential extends Credential { interface PublicKeyCredential extends Credential {
readonly rawId: ArrayBuffer; readonly rawId: ArrayBuffer;
readonly response: AuthenticatorResponse; readonly response: AuthenticatorResponse;
@ -10491,7 +10557,10 @@ declare var PublicKeyCredential: {
isUserVerifyingPlatformAuthenticatorAvailable(): Promise<boolean>; isUserVerifyingPlatformAuthenticatorAvailable(): Promise<boolean>;
}; };
/** This Push API interface provides a way to receive notifications from third-party servers as well as request URLs for push notifications. */ /**
* This Push API interface provides a way to receive notifications from third-party servers as well as request URLs for push notifications.
* Available only in secure contexts.
*/
interface PushManager { interface PushManager {
getSubscription(): Promise<PushSubscription | null>; getSubscription(): Promise<PushSubscription | null>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>; permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>;
@ -10504,7 +10573,10 @@ declare var PushManager: {
readonly supportedContentEncodings: ReadonlyArray<string>; readonly supportedContentEncodings: ReadonlyArray<string>;
}; };
/** This Push API interface provides a subcription's URL endpoint and allows unsubscription from a push service. */ /**
* This Push API interface provides a subcription's URL endpoint and allows unsubscription from a push service.
* Available only in secure contexts.
*/
interface PushSubscription { interface PushSubscription {
readonly endpoint: string; readonly endpoint: string;
readonly options: PushSubscriptionOptions; readonly options: PushSubscriptionOptions;
@ -10518,6 +10590,7 @@ declare var PushSubscription: {
new(): PushSubscription; new(): PushSubscription;
}; };
/** Available only in secure contexts. */
interface PushSubscriptionOptions { interface PushSubscriptionOptions {
readonly applicationServerKey: ArrayBuffer | null; readonly applicationServerKey: ArrayBuffer | null;
} }
@ -10910,7 +10983,6 @@ interface ReadableStream<R = any> {
pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>; pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>; pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
tee(): [ReadableStream<R>, ReadableStream<R>]; tee(): [ReadableStream<R>, ReadableStream<R>];
forEach(callbackfn: (value: any, key: number, parent: ReadableStream<R>) => void, thisArg?: any): void;
} }
declare var ReadableStream: { declare var ReadableStream: {
@ -12898,7 +12970,10 @@ interface ServiceWorkerEventMap extends AbstractWorkerEventMap {
"statechange": Event; "statechange": Event;
} }
/** This ServiceWorker API interface provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. */ /**
* This ServiceWorker API interface provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object.
* Available only in secure contexts.
*/
interface ServiceWorker extends EventTarget, AbstractWorker { interface ServiceWorker extends EventTarget, AbstractWorker {
onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;
readonly scriptURL: string; readonly scriptURL: string;
@ -12922,7 +12997,10 @@ interface ServiceWorkerContainerEventMap {
"messageerror": MessageEvent; "messageerror": MessageEvent;
} }
/** The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. */ /**
* The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
* Available only in secure contexts.
*/
interface ServiceWorkerContainer extends EventTarget { interface ServiceWorkerContainer extends EventTarget {
readonly controller: ServiceWorker | null; readonly controller: ServiceWorker | null;
oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;
@ -12948,7 +13026,10 @@ interface ServiceWorkerRegistrationEventMap {
"updatefound": Event; "updatefound": Event;
} }
/** This ServiceWorker API interface represents the service worker registration. You register a service worker to control one or more pages that share the same origin. */ /**
* This ServiceWorker API interface represents the service worker registration. You register a service worker to control one or more pages that share the same origin.
* Available only in secure contexts.
*/
interface ServiceWorkerRegistration extends EventTarget { interface ServiceWorkerRegistration extends EventTarget {
readonly active: ServiceWorker | null; readonly active: ServiceWorker | null;
readonly installing: ServiceWorker | null; readonly installing: ServiceWorker | null;
@ -13266,6 +13347,7 @@ declare var StorageEvent: {
new(type: string, eventInitDict?: StorageEventInit): StorageEvent; new(type: string, eventInitDict?: StorageEventInit): StorageEvent;
}; };
/** Available only in secure contexts. */
interface StorageManager { interface StorageManager {
estimate(): Promise<StorageEstimate>; estimate(): Promise<StorageEstimate>;
persist(): Promise<boolean>; persist(): Promise<boolean>;
@ -13321,7 +13403,10 @@ declare var SubmitEvent: {
new(type: string, eventInitDict?: SubmitEventInit): SubmitEvent; new(type: string, eventInitDict?: SubmitEventInit): SubmitEvent;
}; };
/** This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). */ /**
* This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto).
* Available only in secure contexts.
*/
interface SubtleCrypto { interface SubtleCrypto {
decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<any>; decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<any>;
deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>; deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>;
@ -13348,7 +13433,6 @@ declare var SubtleCrypto: {
/** The textual content of Element or Attr. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. */ /** The textual content of Element or Attr. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. */
interface Text extends CharacterData, Slottable { interface Text extends CharacterData, Slottable {
readonly assignedSlot: HTMLSlotElement | null;
/** Returns the combined data of all direct Text node siblings. */ /** Returns the combined data of all direct Text node siblings. */
readonly wholeText: string; readonly wholeText: string;
/** Splits data at the given offset and returns the remainder as Text node. */ /** Splits data at the given offset and returns the remainder as Text node. */
@ -16032,7 +16116,9 @@ interface Window extends EventTarget, AnimationFrameProvider, GlobalEventHandler
readonly menubar: BarProp; readonly menubar: BarProp;
name: string; name: string;
readonly navigator: Navigator; readonly navigator: Navigator;
/** Available only in secure contexts. */
ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;
/** Available only in secure contexts. */
ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;
/** @deprecated */ /** @deprecated */
onorientationchange: ((this: Window, ev: Event) => any) | null; onorientationchange: ((this: Window, ev: Event) => any) | null;
@ -16180,6 +16266,7 @@ interface WindowLocalStorage {
} }
interface WindowOrWorkerGlobalScope { interface WindowOrWorkerGlobalScope {
/** Available only in secure contexts. */
readonly caches: CacheStorage; readonly caches: CacheStorage;
readonly crossOriginIsolated: boolean; readonly crossOriginIsolated: boolean;
readonly crypto: Crypto; readonly crypto: Crypto;
@ -16228,6 +16315,7 @@ declare var Worker: {
new(scriptURL: string | URL, options?: WorkerOptions): Worker; new(scriptURL: string | URL, options?: WorkerOptions): Worker;
}; };
/** Available only in secure contexts. */
interface Worklet { interface Worklet {
/** /**
* Loads and executes the module script given by moduleURL into all of worklet's global scopes. It can also create additional global scopes as part of this process, depending on the worklet type. The returned promise will fulfill once the script has been successfully loaded and run in all global scopes. * Loads and executes the module script given by moduleURL into all of worklet's global scopes. It can also create additional global scopes as part of this process, depending on the worklet type. The returned promise will fulfill once the script has been successfully loaded and run in all global scopes.
@ -16573,7 +16661,8 @@ declare namespace WebAssembly {
var CompileError: { var CompileError: {
prototype: CompileError; prototype: CompileError;
new(): CompileError; new(message?: string): CompileError;
(message?: string): CompileError;
}; };
interface Global { interface Global {
@ -16600,7 +16689,8 @@ declare namespace WebAssembly {
var LinkError: { var LinkError: {
prototype: LinkError; prototype: LinkError;
new(): LinkError; new(message?: string): LinkError;
(message?: string): LinkError;
}; };
interface Memory { interface Memory {
@ -16629,7 +16719,8 @@ declare namespace WebAssembly {
var RuntimeError: { var RuntimeError: {
prototype: RuntimeError; prototype: RuntimeError;
new(): RuntimeError; new(message?: string): RuntimeError;
(message?: string): RuntimeError;
}; };
interface Table { interface Table {
@ -16774,7 +16865,7 @@ interface PositionErrorCallback {
} }
interface QueuingStrategySize<T = any> { interface QueuingStrategySize<T = any> {
(chunk?: T): number; (chunk: T): number;
} }
interface RTCPeerConnectionErrorCallback { interface RTCPeerConnectionErrorCallback {
@ -17066,7 +17157,9 @@ declare var menubar: BarProp;
/** @deprecated */ /** @deprecated */
declare const name: void; declare const name: void;
declare var navigator: Navigator; declare var navigator: Navigator;
/** Available only in secure contexts. */
declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;
/** Available only in secure contexts. */
declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;
/** @deprecated */ /** @deprecated */
declare var onorientationchange: ((this: Window, ev: Event) => any) | null; declare var onorientationchange: ((this: Window, ev: Event) => any) | null;
@ -17447,6 +17540,7 @@ declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null;
declare var onunhandledrejection: ((this: Window, ev: PromiseRejectionEvent) => any) | null; declare var onunhandledrejection: ((this: Window, ev: PromiseRejectionEvent) => any) | null;
declare var onunload: ((this: Window, ev: Event) => any) | null; declare var onunload: ((this: Window, ev: Event) => any) | null;
declare var localStorage: Storage; declare var localStorage: Storage;
/** Available only in secure contexts. */
declare var caches: CacheStorage; declare var caches: CacheStorage;
declare var crossOriginIsolated: boolean; declare var crossOriginIsolated: boolean;
declare var crypto: Crypto; declare var crypto: Crypto;
@ -17609,7 +17703,7 @@ type OscillatorType = "custom" | "sawtooth" | "sine" | "square" | "triangle";
type OverSampleType = "2x" | "4x" | "none"; type OverSampleType = "2x" | "4x" | "none";
type PanningModelType = "HRTF" | "equalpower"; type PanningModelType = "HRTF" | "equalpower";
type PaymentComplete = "fail" | "success" | "unknown"; type PaymentComplete = "fail" | "success" | "unknown";
type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock"; type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking";
type PermissionState = "denied" | "granted" | "prompt"; type PermissionState = "denied" | "granted" | "prompt";
type PlaybackDirection = "alternate" | "alternate-reverse" | "normal" | "reverse"; type PlaybackDirection = "alternate" | "alternate-reverse" | "normal" | "reverse";
type PositionAlignSetting = "auto" | "center" | "line-left" | "line-right"; type PositionAlignSetting = "auto" | "center" | "line-left" | "line-right";

View file

@ -135,6 +135,7 @@ interface NamedNodeMap {
} }
interface Navigator { interface Navigator {
/** Available only in secure contexts. */
requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: Iterable<MediaKeySystemConfiguration>): Promise<MediaKeySystemAccess>; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: Iterable<MediaKeySystemConfiguration>): Promise<MediaKeySystemAccess>;
vibrate(pattern: Iterable<number>): boolean; vibrate(pattern: Iterable<number>): boolean;
} }
@ -170,13 +171,6 @@ interface PluginArray {
interface RTCStatsReport extends ReadonlyMap<string, any> { interface RTCStatsReport extends ReadonlyMap<string, any> {
} }
interface ReadableStream<R = any> {
[Symbol.iterator](): IterableIterator<any>;
entries(): IterableIterator<[number, any]>;
keys(): IterableIterator<number>;
values(): IterableIterator<any>;
}
interface SVGLengthList { interface SVGLengthList {
[Symbol.iterator](): IterableIterator<SVGLength>; [Symbol.iterator](): IterableIterator<SVGLength>;
} }

View file

@ -200,7 +200,7 @@ declare namespace Intl {
interface NumberFormatOptions { interface NumberFormatOptions {
compactDisplay?: "short" | "long" | undefined; compactDisplay?: "short" | "long" | undefined;
notation?: "standard" | "scientific" | "engineering" | "compact" | undefined; notation?: "standard" | "scientific" | "engineering" | "compact" | undefined;
signDisplay?: "auto" | "never" | "always" | undefined; signDisplay?: "auto" | "never" | "always" | "exceptZero" | undefined;
unit?: string | undefined; unit?: string | undefined;
unitDisplay?: "short" | "long" | "narrow" | undefined; unitDisplay?: "short" | "long" | "narrow" | undefined;
} }
@ -208,7 +208,7 @@ declare namespace Intl {
interface ResolvedNumberFormatOptions { interface ResolvedNumberFormatOptions {
compactDisplay?: "short" | "long"; compactDisplay?: "short" | "long";
notation?: "standard" | "scientific" | "engineering" | "compact"; notation?: "standard" | "scientific" | "engineering" | "compact";
signDisplay?: "auto" | "never" | "always"; signDisplay?: "auto" | "never" | "always" | "exceptZero";
unit?: string; unit?: string;
unitDisplay?: "short" | "long" | "narrow"; unitDisplay?: "short" | "long" | "narrow";
} }

103
src/lib/es2022.array.d.ts vendored Normal file
View file

@ -0,0 +1,103 @@
interface Array<T> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): T | undefined;
}
interface ReadonlyArray<T> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): T | undefined;
}
interface Int8Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint8Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint8ClampedArray {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Int16Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint16Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Int32Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint32Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Float32Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Float64Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface BigInt64Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): bigint | undefined;
}
interface BigUint64Array {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): bigint | undefined;
}

5
src/lib/es2022.d.ts vendored Normal file
View file

@ -0,0 +1,5 @@
/// <reference lib="es2021" />
/// <reference lib="es2022.array" />
/// <reference lib="es2022.error" />
/// <reference lib="es2022.object" />
/// <reference lib="es2022.string" />

8
src/lib/es2022.error.d.ts vendored Normal file
View file

@ -0,0 +1,8 @@
interface ErrorOptions {
cause?: Error;
}
interface ErrorConstructor {
new(message?: string, options?: ErrorOptions): Error;
(message?: string, options?: ErrorOptions): Error;
}

5
src/lib/es2022.full.d.ts vendored Normal file
View file

@ -0,0 +1,5 @@
/// <reference lib="es2022" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />

8
src/lib/es2022.object.d.ts vendored Normal file
View file

@ -0,0 +1,8 @@
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param o An object.
* @param v A property name.
*/
hasOwn(o: object, v: PropertyKey): boolean;
}

7
src/lib/es2022.string.d.ts vendored Normal file
View file

@ -0,0 +1,7 @@
interface String {
/**
* Returns a new String consisting of the single UTF-16 code unit located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): string | undefined;
}

2
src/lib/es5.d.ts vendored
View file

@ -96,7 +96,7 @@ interface PropertyDescriptor {
} }
interface PropertyDescriptorMap { interface PropertyDescriptorMap {
[s: string]: PropertyDescriptor; [key: PropertyKey]: PropertyDescriptor;
} }
interface Object { interface Object {

2
src/lib/esnext.d.ts vendored
View file

@ -1,2 +1,2 @@
/// <reference lib="es2021" /> /// <reference lib="es2022" />
/// <reference lib="esnext.intl" /> /// <reference lib="esnext.intl" />

View file

@ -9,6 +9,7 @@
"es2019", "es2019",
"es2020", "es2020",
"es2021", "es2021",
"es2022",
"esnext", "esnext",
// Host only // Host only
"dom.generated", "dom.generated",
@ -52,6 +53,10 @@
"es2021.promise", "es2021.promise",
"es2021.weakref", "es2021.weakref",
"es2021.intl", "es2021.intl",
"es2022.array",
"es2022.error",
"es2022.object",
"es2022.string",
"esnext.intl", "esnext.intl",
// Default libraries // Default libraries
"es5.full", "es5.full",
@ -62,6 +67,7 @@
"es2019.full", "es2019.full",
"es2020.full", "es2020.full",
"es2021.full", "es2021.full",
"es2022.full",
"esnext.full" "esnext.full"
], ],
"paths": { "paths": {

View file

@ -477,7 +477,7 @@ interface RequestInit {
/** An AbortSignal to set request's signal. */ /** An AbortSignal to set request's signal. */
signal?: AbortSignal | null; signal?: AbortSignal | null;
/** Can only be null. Used to disassociate request from any Window. */ /** Can only be null. Used to disassociate request from any Window. */
window?: any; window?: null;
} }
interface ResponseInit { interface ResponseInit {
@ -671,7 +671,7 @@ interface AbortSignal extends EventTarget {
declare var AbortSignal: { declare var AbortSignal: {
prototype: AbortSignal; prototype: AbortSignal;
new(): AbortSignal; new(): AbortSignal;
// abort(): AbortSignal; // abort(): AbortSignal; - To be re-added in the future
}; };
interface AbstractWorkerEventMap { interface AbstractWorkerEventMap {
@ -752,7 +752,10 @@ declare var ByteLengthQueuingStrategy: {
new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; new(init: QueuingStrategyInit): ByteLengthQueuingStrategy;
}; };
/** Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. */ /**
* Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec.
* Available only in secure contexts.
*/
interface Cache { interface Cache {
add(request: RequestInfo): Promise<void>; add(request: RequestInfo): Promise<void>;
addAll(requests: RequestInfo[]): Promise<void>; addAll(requests: RequestInfo[]): Promise<void>;
@ -768,7 +771,10 @@ declare var Cache: {
new(): Cache; new(): Cache;
}; };
/** The storage for Cache objects. */ /**
* The storage for Cache objects.
* Available only in secure contexts.
*/
interface CacheStorage { interface CacheStorage {
delete(cacheName: string): Promise<boolean>; delete(cacheName: string): Promise<boolean>;
has(cacheName: string): Promise<boolean>; has(cacheName: string): Promise<boolean>;
@ -876,6 +882,7 @@ declare var CountQueuingStrategy: {
/** Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */ /** Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */
interface Crypto { interface Crypto {
/** Available only in secure contexts. */
readonly subtle: SubtleCrypto; readonly subtle: SubtleCrypto;
getRandomValues<T extends ArrayBufferView | null>(array: T): T; getRandomValues<T extends ArrayBufferView | null>(array: T): T;
} }
@ -885,7 +892,10 @@ declare var Crypto: {
new(): Crypto; new(): Crypto;
}; };
/** The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. */ /**
* The CryptoKey dictionary of the Web Crypto API represents a cryptographic key.
* Available only in secure contexts.
*/
interface CryptoKey { interface CryptoKey {
readonly algorithm: KeyAlgorithm; readonly algorithm: KeyAlgorithm;
readonly extractable: boolean; readonly extractable: boolean;
@ -2137,6 +2147,7 @@ interface NavigatorOnLine {
readonly onLine: boolean; readonly onLine: boolean;
} }
/** Available only in secure contexts. */
interface NavigatorStorage { interface NavigatorStorage {
readonly storage: StorageManager; readonly storage: StorageManager;
} }
@ -2431,7 +2442,10 @@ declare var PromiseRejectionEvent: {
new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent; new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent;
}; };
/** This Push API interface represents a push message that has been received. This event is sent to the global scope of a ServiceWorker. It contains the information sent from an application server to a PushSubscription. */ /**
* This Push API interface represents a push message that has been received. This event is sent to the global scope of a ServiceWorker. It contains the information sent from an application server to a PushSubscription.
* Available only in secure contexts.
*/
interface PushEvent extends ExtendableEvent { interface PushEvent extends ExtendableEvent {
readonly data: PushMessageData | null; readonly data: PushMessageData | null;
} }
@ -2441,7 +2455,10 @@ declare var PushEvent: {
new(type: string, eventInitDict?: PushEventInit): PushEvent; new(type: string, eventInitDict?: PushEventInit): PushEvent;
}; };
/** This Push API interface provides a way to receive notifications from third-party servers as well as request URLs for push notifications. */ /**
* This Push API interface provides a way to receive notifications from third-party servers as well as request URLs for push notifications.
* Available only in secure contexts.
*/
interface PushManager { interface PushManager {
getSubscription(): Promise<PushSubscription | null>; getSubscription(): Promise<PushSubscription | null>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>; permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>;
@ -2454,7 +2471,10 @@ declare var PushManager: {
readonly supportedContentEncodings: ReadonlyArray<string>; readonly supportedContentEncodings: ReadonlyArray<string>;
}; };
/** This Push API interface provides methods which let you retrieve the push data sent by a server in various formats. */ /**
* This Push API interface provides methods which let you retrieve the push data sent by a server in various formats.
* Available only in secure contexts.
*/
interface PushMessageData { interface PushMessageData {
arrayBuffer(): ArrayBuffer; arrayBuffer(): ArrayBuffer;
blob(): Blob; blob(): Blob;
@ -2467,7 +2487,10 @@ declare var PushMessageData: {
new(): PushMessageData; new(): PushMessageData;
}; };
/** This Push API interface provides a subcription's URL endpoint and allows unsubscription from a push service. */ /**
* This Push API interface provides a subcription's URL endpoint and allows unsubscription from a push service.
* Available only in secure contexts.
*/
interface PushSubscription { interface PushSubscription {
readonly endpoint: string; readonly endpoint: string;
readonly options: PushSubscriptionOptions; readonly options: PushSubscriptionOptions;
@ -2481,6 +2504,7 @@ declare var PushSubscription: {
new(): PushSubscription; new(): PushSubscription;
}; };
/** Available only in secure contexts. */
interface PushSubscriptionOptions { interface PushSubscriptionOptions {
readonly applicationServerKey: ArrayBuffer | null; readonly applicationServerKey: ArrayBuffer | null;
} }
@ -2498,7 +2522,6 @@ interface ReadableStream<R = any> {
pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>; pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>; pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
tee(): [ReadableStream<R>, ReadableStream<R>]; tee(): [ReadableStream<R>, ReadableStream<R>];
forEach(callbackfn: (value: any, key: number, parent: ReadableStream<R>) => void, thisArg?: any): void;
} }
declare var ReadableStream: { declare var ReadableStream: {
@ -2613,7 +2636,10 @@ interface ServiceWorkerEventMap extends AbstractWorkerEventMap {
"statechange": Event; "statechange": Event;
} }
/** This ServiceWorker API interface provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. */ /**
* This ServiceWorker API interface provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object.
* Available only in secure contexts.
*/
interface ServiceWorker extends EventTarget, AbstractWorker { interface ServiceWorker extends EventTarget, AbstractWorker {
onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;
readonly scriptURL: string; readonly scriptURL: string;
@ -2637,7 +2663,10 @@ interface ServiceWorkerContainerEventMap {
"messageerror": MessageEvent; "messageerror": MessageEvent;
} }
/** The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. */ /**
* The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
* Available only in secure contexts.
*/
interface ServiceWorkerContainer extends EventTarget { interface ServiceWorkerContainer extends EventTarget {
readonly controller: ServiceWorker | null; readonly controller: ServiceWorker | null;
oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;
@ -2698,7 +2727,10 @@ interface ServiceWorkerRegistrationEventMap {
"updatefound": Event; "updatefound": Event;
} }
/** This ServiceWorker API interface represents the service worker registration. You register a service worker to control one or more pages that share the same origin. */ /**
* This ServiceWorker API interface represents the service worker registration. You register a service worker to control one or more pages that share the same origin.
* Available only in secure contexts.
*/
interface ServiceWorkerRegistration extends EventTarget { interface ServiceWorkerRegistration extends EventTarget {
readonly active: ServiceWorker | null; readonly active: ServiceWorker | null;
readonly installing: ServiceWorker | null; readonly installing: ServiceWorker | null;
@ -2743,6 +2775,7 @@ declare var SharedWorkerGlobalScope: {
new(): SharedWorkerGlobalScope; new(): SharedWorkerGlobalScope;
}; };
/** Available only in secure contexts. */
interface StorageManager { interface StorageManager {
estimate(): Promise<StorageEstimate>; estimate(): Promise<StorageEstimate>;
persisted(): Promise<boolean>; persisted(): Promise<boolean>;
@ -2753,7 +2786,10 @@ declare var StorageManager: {
new(): StorageManager; new(): StorageManager;
}; };
/** This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). */ /**
* This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto).
* Available only in secure contexts.
*/
interface SubtleCrypto { interface SubtleCrypto {
decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<any>; decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<any>;
deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>; deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>;
@ -5030,6 +5066,7 @@ declare var WindowClient: {
}; };
interface WindowOrWorkerGlobalScope { interface WindowOrWorkerGlobalScope {
/** Available only in secure contexts. */
readonly caches: CacheStorage; readonly caches: CacheStorage;
readonly crossOriginIsolated: boolean; readonly crossOriginIsolated: boolean;
readonly crypto: Crypto; readonly crypto: Crypto;
@ -5352,7 +5389,8 @@ declare namespace WebAssembly {
var CompileError: { var CompileError: {
prototype: CompileError; prototype: CompileError;
new(): CompileError; new(message?: string): CompileError;
(message?: string): CompileError;
}; };
interface Global { interface Global {
@ -5379,7 +5417,8 @@ declare namespace WebAssembly {
var LinkError: { var LinkError: {
prototype: LinkError; prototype: LinkError;
new(): LinkError; new(message?: string): LinkError;
(message?: string): LinkError;
}; };
interface Memory { interface Memory {
@ -5408,7 +5447,8 @@ declare namespace WebAssembly {
var RuntimeError: { var RuntimeError: {
prototype: RuntimeError; prototype: RuntimeError;
new(): RuntimeError; new(message?: string): RuntimeError;
(message?: string): RuntimeError;
}; };
interface Table { interface Table {
@ -5485,7 +5525,7 @@ interface PerformanceObserverCallback {
} }
interface QueuingStrategySize<T = any> { interface QueuingStrategySize<T = any> {
(chunk?: T): number; (chunk: T): number;
} }
interface TransformerFlushCallback<O> { interface TransformerFlushCallback<O> {
@ -5560,6 +5600,7 @@ declare function importScripts(...urls: (string | URL)[]): void;
/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */
declare function dispatchEvent(event: Event): boolean; declare function dispatchEvent(event: Event): boolean;
declare var fonts: FontFaceSet; declare var fonts: FontFaceSet;
/** Available only in secure contexts. */
declare var caches: CacheStorage; declare var caches: CacheStorage;
declare var crossOriginIsolated: boolean; declare var crossOriginIsolated: boolean;
declare var crypto: Crypto; declare var crypto: Crypto;
@ -5648,7 +5689,7 @@ type MediaDecodingType = "file" | "media-source" | "webrtc";
type MediaEncodingType = "record" | "webrtc"; type MediaEncodingType = "record" | "webrtc";
type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationDirection = "auto" | "ltr" | "rtl";
type NotificationPermission = "default" | "denied" | "granted"; type NotificationPermission = "default" | "denied" | "granted";
type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock"; type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking";
type PermissionState = "denied" | "granted" | "prompt"; type PermissionState = "denied" | "granted" | "prompt";
type PredefinedColorSpace = "display-p3" | "srgb"; type PredefinedColorSpace = "display-p3" | "srgb";
type PremultiplyAlpha = "default" | "none" | "premultiply"; type PremultiplyAlpha = "default" | "none" | "premultiply";

View file

@ -56,13 +56,6 @@ interface MessageEvent<T = any> {
initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable<MessagePort>): void; initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable<MessagePort>): void;
} }
interface ReadableStream<R = any> {
[Symbol.iterator](): IterableIterator<any>;
entries(): IterableIterator<[number, any]>;
keys(): IterableIterator<number>;
values(): IterableIterator<any>;
}
interface SubtleCrypto { interface SubtleCrypto {
deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>; deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair>; generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair>;

View file

@ -7764,6 +7764,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[JSON 导入在 ES 模块模式导入中是实验性的。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7764,6 +7764,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[JSON 匯入在 ES 模組模式匯入中為實驗性。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7773,6 +7773,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Importy JSON jsou v importech režimu modulu ES experimentální.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7761,6 +7761,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[JSON-Importe sind experimentell in Importen im ES-Modulmodus.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7776,6 +7776,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Las importaciones de JSON son experimentales en las importaciones del modo de módulo ES.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7776,6 +7776,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Les importations JSON sont expérimentales dans les importations en mode module ES.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7764,6 +7764,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Le importazioni JSON sono sperimentali nelle importazioni in modalità modulo ES.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7764,6 +7764,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[JSON インポートは、ES モジュール モードのインポートでは試験的な機能です。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7764,6 +7764,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[JSON 가져오기는 ES 모듈 모드 가져오기에서 실험적입니다.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7754,6 +7754,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Importy JSON są eksperymentalne w importach w trybie modułu ES.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7757,6 +7757,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[As importações JSON são experimentais em importações de modo de módulo ES.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7763,6 +7763,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Импорт данных JSON — экспериментальная функция импорта в режиме модуля ES.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -7757,6 +7757,15 @@
</Str> </Str>
<Disp Icon="Str" /> <Disp Icon="Str" />
</Item> </Item>
<Item ItemId=";JSON_imports_are_experimental_in_ES_module_mode_imports_7062" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[JSON imports are experimental in ES module mode imports.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[JSON içeri aktarmaları, ES modül modu içeri aktarmaları için deneyseldir.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true"> <Item ItemId=";JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text"> <Str Cat="Text">
<Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val> <Val><![CDATA[JSX attributes must only be assigned a non-empty 'expression'.]]></Val>

View file

@ -49,24 +49,23 @@ namespace ts.server {
readonly data: ProjectInfoTelemetryEventData; readonly data: ProjectInfoTelemetryEventData;
} }
/* /* __GDPR__
* __GDPR__ "projectInfo" : {
* "projectInfo" : { "${include}": ["${TypeScriptCommonProperties}"],
* "${include}": ["${TypeScriptCommonProperties}"], "projectId": { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight", "endpoint": "ProjectId" },
* "projectId": { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight", "endpoint": "ProjectId" }, "fileStats": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "fileStats": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "compilerOptions": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "compilerOptions": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extends": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "extends": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "files": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "files": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "include": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "include": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "exclude": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "exclude": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "compileOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "compileOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "typeAcquisition": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "typeAcquisition": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "configFileName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "configFileName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "projectType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "projectType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "languageServiceEnabled": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
* "languageServiceEnabled": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
* "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } }
* }
*/ */
export interface ProjectInfoTelemetryEventData { export interface ProjectInfoTelemetryEventData {
/** Cryptographically secure hash of project file location. */ /** Cryptographically secure hash of project file location. */

View file

@ -1031,6 +1031,11 @@ namespace ts.server {
} }
} }
/* @internal */
onDiscoveredSymlink() {
this.hasAddedOrRemovedSymlinks = true;
}
/** /**
* Updates set of files that contribute to this project * Updates set of files that contribute to this project
* @returns: true if set of files in the project stays the same and false - otherwise. * @returns: true if set of files in the project stays the same and false - otherwise.
@ -1939,15 +1944,15 @@ namespace ts.server {
for (const resolution of resolutions) { for (const resolution of resolutions) {
if (!resolution.resolvedFileName) continue; if (!resolution.resolvedFileName) continue;
const { resolvedFileName, originalPath } = resolution; const { resolvedFileName, originalPath } = resolution;
if (originalPath) {
symlinkCache.setSymlinkedDirectoryFromSymlinkedFile(originalPath, resolvedFileName);
}
if (!program.getSourceFile(resolvedFileName) && (!originalPath || !program.getSourceFile(originalPath))) { if (!program.getSourceFile(resolvedFileName) && (!originalPath || !program.getSourceFile(originalPath))) {
rootNames = append(rootNames, resolvedFileName); rootNames = append(rootNames, resolvedFileName);
// Avoid creating a large project that would significantly slow down time to editor interactivity // Avoid creating a large project that would significantly slow down time to editor interactivity
if (dependencySelection === PackageJsonAutoImportPreference.Auto && rootNames.length > this.maxDependencies) { if (dependencySelection === PackageJsonAutoImportPreference.Auto && rootNames.length > this.maxDependencies) {
return ts.emptyArray; return ts.emptyArray;
} }
if (originalPath) {
symlinkCache.setSymlinkedDirectoryFromSymlinkedFile(originalPath, resolvedFileName);
}
} }
} }
} }

View file

@ -2289,7 +2289,7 @@ namespace ts.server.protocol {
/** /**
* Human-readable description of the `source`. * Human-readable description of the `source`.
*/ */
sourceDisplay?: SymbolDisplayPart[]; sourceDisplay?: SymbolDisplayPart[];
/** /**
* If true, this completion should be highlighted as recommended. There will only be one of these. * If true, this completion should be highlighted as recommended. There will only be one of these.
* This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class.
@ -3199,14 +3199,32 @@ namespace ts.server.protocol {
payload: TypingsInstalledTelemetryEventPayload; payload: TypingsInstalledTelemetryEventPayload;
} }
/* // A __GDPR__FRAGMENT__ has no meaning until it is ${include}d by a __GDPR__ comment, at which point
* __GDPR__ // the included properties are effectively inlined into the __GDPR__ declaration. In this case, for
* "typingsinstalled" : { // example, any __GDPR__ comment including the TypeScriptCommonProperties will be updated with an
* "${include}": ["${TypeScriptCommonProperties}"], // additional version property with the classification below. Obviously, the purpose of such a construct
* "installedPackages": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, // is to reduce duplication and keep multiple use sites consistent (e.g. by making sure that all reflect
* "installSuccess": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, // any newly added TypeScriptCommonProperties). Unfortunately, the system has limits - in particular,
* "typingsInstallerVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } // these reusable __GDPR__FRAGMENT__s are not accessible across repo boundaries. Therefore, even though
* } // the code for adding the common properties (i.e. version), along with the corresponding __GDPR__FRAGMENT__,
// lives in the VS Code repo (see https://github.com/microsoft/vscode/blob/main/extensions/typescript-language-features/src/utils/telemetry.ts)
// we have to duplicate it here. It would be nice to keep them in sync, but the only likely failure mode
// is adding a property to the VS Code repro but not here and the only consequence would be having that
// property suppressed on the events (i.e. __GDPT__ comments) in this repo that reference the out-of-date
// local __GDPR__FRAGMENT__.
/* __GDPR__FRAGMENT__
"TypeScriptCommonProperties" : {
"version" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
/* __GDPR__
"typingsinstalled" : {
"${include}": ["${TypeScriptCommonProperties}"],
"installedPackages": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"installSuccess": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"typingsInstallerVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/ */
export interface TypingsInstalledTelemetryEventPayload { export interface TypingsInstalledTelemetryEventPayload {
/** /**
@ -3381,6 +3399,13 @@ namespace ts.server.protocol {
* values, with insertion text to replace preceding `.` tokens with `?.`. * values, with insertion text to replace preceding `.` tokens with `?.`.
*/ */
readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean;
/**
* If enabled, completions for class members (e.g. methods and properties) will include
* a whole declaration for the member.
* E.g., `class A { f| }` could be completed to `class A { foo(): number {} }`, instead of
* `class A { foo }`.
*/
readonly includeCompletionsWithClassMemberSnippets?: boolean;
readonly allowIncompleteCompletions?: boolean; readonly allowIncompleteCompletions?: boolean;
readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
@ -3509,6 +3534,7 @@ namespace ts.server.protocol {
ES2019 = "ES2019", ES2019 = "ES2019",
ES2020 = "ES2020", ES2020 = "ES2020",
ES2021 = "ES2021", ES2021 = "ES2021",
ES2022 = "ES2022",
ESNext = "ESNext" ESNext = "ESNext"
} }

View file

@ -2112,7 +2112,7 @@ namespace ts.server {
private getFullNavigateToItems(args: protocol.NavtoRequestArgs): CombineOutputResult<NavigateToItem> { private getFullNavigateToItems(args: protocol.NavtoRequestArgs): CombineOutputResult<NavigateToItem> {
const { currentFileOnly, searchValue, maxResultCount, projectFileName } = args; const { currentFileOnly, searchValue, maxResultCount, projectFileName } = args;
if (currentFileOnly) { if (currentFileOnly) {
Debug.assertDefined(args.file); Debug.assertIsDefined(args.file);
const { file, project } = this.getFileAndProject(args as protocol.FileRequestArgs); const { file, project } = this.getFileAndProject(args as protocol.FileRequestArgs);
return [{ project, result: project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file) }]; return [{ project, result: project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file) }];
} }

View file

@ -3,13 +3,6 @@ namespace ts.codefix {
const errorCodeToFixes = createMultiMap<CodeFixRegistration>(); const errorCodeToFixes = createMultiMap<CodeFixRegistration>();
const fixIdToRegistration = new Map<string, CodeFixRegistration>(); const fixIdToRegistration = new Map<string, CodeFixRegistration>();
export type DiagnosticAndArguments = DiagnosticMessage | [DiagnosticMessage, string] | [DiagnosticMessage, string, string];
function diagnosticToString(diag: DiagnosticAndArguments): string {
return isArray(diag)
? formatStringFromArgs(getLocaleSpecificMessage(diag[0]), diag.slice(1) as readonly string[])
: getLocaleSpecificMessage(diag);
}
export function createCodeFixActionWithoutFixAll(fixName: string, changes: FileTextChanges[], description: DiagnosticAndArguments) { export function createCodeFixActionWithoutFixAll(fixName: string, changes: FileTextChanges[], description: DiagnosticAndArguments) {
return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined);
} }

View file

@ -14,24 +14,24 @@ namespace ts.codefix {
function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) { function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) {
const token = getTokenAtPosition(sourceFile, pos); const token = getTokenAtPosition(sourceFile, pos);
if (!isIdentifier(token)) {
return Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + Debug.formatSyntaxKind(token.kind));
}
const param = token.parent; const param = token.parent;
if (!isParameter(param)) { if (!isParameter(param)) {
return Debug.fail("Tried to add a parameter name to a non-parameter: " + Debug.formatSyntaxKind(token.kind)); return Debug.fail("Tried to add a parameter name to a non-parameter: " + Debug.formatSyntaxKind(token.kind));
} }
const i = param.parent.parameters.indexOf(param); const i = param.parent.parameters.indexOf(param);
Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
Debug.assert(i > -1, "Parameter not found in parent parameter list."); Debug.assert(i > -1, "Parameter not found in parent parameter list.");
const typeNode = factory.createTypeReferenceNode(param.name as Identifier, /*typeArguments*/ undefined);
const replacement = factory.createParameterDeclaration( const replacement = factory.createParameterDeclaration(
/*decorators*/ undefined, /*decorators*/ undefined,
param.modifiers, param.modifiers,
param.dotDotDotToken, param.dotDotDotToken,
"arg" + i, "arg" + i,
param.questionToken, param.questionToken,
factory.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.dotDotDotToken ? factory.createArrayTypeNode(typeNode) : typeNode,
param.initializer); param.initializer);
changeTracker.replaceNode(sourceFile, token, replacement); changeTracker.replaceNode(sourceFile, param, replacement);
} }
} }

View file

@ -408,9 +408,7 @@ namespace ts.codefix {
const importSpecifiers = mapAllOrFail(name.elements, e => const importSpecifiers = mapAllOrFail(name.elements, e =>
e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name)
? undefined ? undefined
// (TODO: GH#18217) : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text));
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
: makeImportSpecifier(e.propertyName && (e.propertyName as Identifier).text, e.name.text));
if (importSpecifiers) { if (importSpecifiers) {
return convertedImports([makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]); return convertedImports([makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]);
} }

View file

@ -42,7 +42,7 @@ namespace ts.codefix {
const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);
const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host); const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host);
createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, sourceFile, context, preferences, importAdder, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member)); createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, sourceFile, context, preferences, importAdder, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member as ClassElement));
importAdder.writeFixes(changeTracker); importAdder.writeFixes(changeTracker);
} }

View file

@ -64,7 +64,7 @@ namespace ts.codefix {
} }
const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host); const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host);
createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, sourceFile, context, preferences, importAdder, member => insertInterfaceMemberNode(sourceFile, classDeclaration, member)); createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, sourceFile, context, preferences, importAdder, member => insertInterfaceMemberNode(sourceFile, classDeclaration, member as ClassElement));
importAdder.writeFixes(changeTracker); importAdder.writeFixes(changeTracker);
function createMissingIndexSignatureDeclaration(type: InterfaceType, kind: IndexKind): void { function createMissingIndexSignatureDeclaration(type: InterfaceType, kind: IndexKind): void {

View file

@ -26,9 +26,9 @@ namespace ts.codefix {
if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) return undefined; if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) return undefined;
if (!isSourceFile(getThisContainer(fn, /*includeArrowFunctions*/ false))) { // 'this' is defined outside, convert to arrow function if (!isSourceFile(getThisContainer(fn, /*includeArrowFunctions*/ false))) { // 'this' is defined outside, convert to arrow function
const fnKeyword = Debug.assertDefined(findChildOfKind(fn, SyntaxKind.FunctionKeyword, sourceFile)); const fnKeyword = Debug.checkDefined(findChildOfKind(fn, SyntaxKind.FunctionKeyword, sourceFile));
const { name } = fn; const { name } = fn;
const body = Debug.assertDefined(fn.body); // Should be defined because the function contained a 'this' expression const body = Debug.checkDefined(fn.body); // Should be defined because the function contained a 'this' expression
if (isFunctionExpression(fn)) { if (isFunctionExpression(fn)) {
if (name && FindAllReferences.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) { if (name && FindAllReferences.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) {
// Function expression references itself. To fix we would have to extract it to a const. // Function expression references itself. To fix we would have to extract it to a const.

View file

@ -17,37 +17,81 @@ namespace ts.codefix {
Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code,
Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code,
Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code,
Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code,
Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code,
Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code,
Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code,
Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code,
]; ];
const errorCodeFixIdMap: Record<number, [DiagnosticMessage, string | undefined, DiagnosticMessage | undefined]> = { interface ErrorCodeFixInfo {
[Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code]: [ descriptions: DiagnosticMessage;
Diagnostics.Add_override_modifier, fixAddOverrideId, Diagnostics.Add_all_missing_override_modifiers, fixId?: string | undefined;
], fixAllDescriptions?: DiagnosticMessage | undefined;
[Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code]: [ }
Diagnostics.Remove_override_modifier, fixRemoveOverrideId, Diagnostics.Remove_all_unnecessary_override_modifiers
], const errorCodeFixIdMap: Record<number, ErrorCodeFixInfo> = {
[Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code]: [ // case #1:
Diagnostics.Add_override_modifier, fixAddOverrideId, Diagnostics.Add_all_missing_override_modifiers, [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code]: {
], descriptions: Diagnostics.Add_override_modifier,
[Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code]: [ fixId: fixAddOverrideId,
Diagnostics.Add_override_modifier, fixAddOverrideId, Diagnostics.Remove_all_unnecessary_override_modifiers fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers,
], },
[Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code]: [ [Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: {
Diagnostics.Remove_override_modifier, fixRemoveOverrideId, Diagnostics.Remove_all_unnecessary_override_modifiers descriptions: Diagnostics.Add_override_modifier,
] fixId: fixAddOverrideId,
fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
},
// case #2:
[Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code]: {
descriptions: Diagnostics.Remove_override_modifier,
fixId: fixRemoveOverrideId,
fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers,
},
[Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code]: {
descriptions: Diagnostics.Remove_override_modifier,
fixId: fixRemoveOverrideId,
fixAllDescriptions: Diagnostics.Remove_override_modifier
},
// case #3:
[Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code]: {
descriptions: Diagnostics.Add_override_modifier,
fixId: fixAddOverrideId,
fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers,
},
[Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: {
descriptions: Diagnostics.Add_override_modifier,
fixId: fixAddOverrideId,
fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers,
},
// case #4:
[Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code]: {
descriptions: Diagnostics.Add_override_modifier,
fixId: fixAddOverrideId,
fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers,
},
// case #5:
[Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code]: {
descriptions: Diagnostics.Remove_override_modifier,
fixId: fixRemoveOverrideId,
fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers,
},
[Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code]: {
descriptions: Diagnostics.Remove_override_modifier,
fixId: fixRemoveOverrideId,
fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers,
}
}; };
registerCodeFix({ registerCodeFix({
errorCodes, errorCodes,
getCodeActions: context => { getCodeActions: context => {
const { errorCode, span, sourceFile } = context; const { errorCode, span } = context;
const info = errorCodeFixIdMap[errorCode]; const info = errorCodeFixIdMap[errorCode];
if (!info) return emptyArray; if (!info) return emptyArray;
const [ descriptions, fixId, fixAllDescriptions ] = info; const { descriptions, fixId, fixAllDescriptions } = info;
if (isSourceFileJS(sourceFile)) return emptyArray;
const changes = textChanges.ChangeTracker.with(context, changes => dispatchChanges(changes, context, errorCode, span.start)); const changes = textChanges.ChangeTracker.with(context, changes => dispatchChanges(changes, context, errorCode, span.start));
return [ return [
@ -57,9 +101,9 @@ namespace ts.codefix {
fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId],
getAllCodeActions: context => getAllCodeActions: context =>
codeFixAll(context, errorCodes, (changes, diag) => { codeFixAll(context, errorCodes, (changes, diag) => {
const { code, start, file } = diag; const { code, start } = diag;
const info = errorCodeFixIdMap[code]; const info = errorCodeFixIdMap[code];
if (!info || info[1] !== context.fixId || isSourceFileJS(file)) { if (!info || info.fixId !== context.fixId) {
return; return;
} }
@ -74,11 +118,15 @@ namespace ts.codefix {
pos: number) { pos: number) {
switch (errorCode) { switch (errorCode) {
case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code:
case Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code:
case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code:
case Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: case Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code:
case Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code:
return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos);
case Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: case Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code:
case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code:
case Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: case Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code:
case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code:
return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos);
default: default:
Debug.fail("Unexpected error code: " + errorCode); Debug.fail("Unexpected error code: " + errorCode);
@ -87,6 +135,10 @@ namespace ts.codefix {
function doAddOverrideModifierChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) { function doAddOverrideModifierChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) {
const classElement = findContainerClassElementLike(sourceFile, pos); const classElement = findContainerClassElementLike(sourceFile, pos);
if (isSourceFileJS(sourceFile)) {
changeTracker.addJSDocTags(sourceFile, classElement, [factory.createJSDocOverrideTag(factory.createIdentifier("override"))]);
return;
}
const modifiers = classElement.modifiers || emptyArray; const modifiers = classElement.modifiers || emptyArray;
const staticModifier = find(modifiers, isStaticModifier); const staticModifier = find(modifiers, isStaticModifier);
const abstractModifier = find(modifiers, isAbstractModifier); const abstractModifier = find(modifiers, isAbstractModifier);
@ -101,6 +153,10 @@ namespace ts.codefix {
function doRemoveOverrideModifierChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) { function doRemoveOverrideModifierChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) {
const classElement = findContainerClassElementLike(sourceFile, pos); const classElement = findContainerClassElementLike(sourceFile, pos);
if (isSourceFileJS(sourceFile)) {
changeTracker.filterJSDocTags(sourceFile, classElement, not(isJSDocOverrideTag));
return;
}
const overrideModifier = classElement.modifiers && find(classElement.modifiers, modifier => modifier.kind === SyntaxKind.OverrideKeyword); const overrideModifier = classElement.modifiers && find(classElement.modifiers, modifier => modifier.kind === SyntaxKind.OverrideKeyword);
Debug.assertIsDefined(overrideModifier); Debug.assertIsDefined(overrideModifier);

View file

@ -7,11 +7,18 @@ namespace ts.codefix {
* @param importAdder If provided, type annotations will use identifier type references instead of ImportTypeNodes, and the missing imports will be added to the importAdder. * @param importAdder If provided, type annotations will use identifier type references instead of ImportTypeNodes, and the missing imports will be added to the importAdder.
* @returns Empty string iff there are no member insertions. * @returns Empty string iff there are no member insertions.
*/ */
export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: readonly Symbol[], sourceFile: SourceFile, context: TypeConstructionContext, preferences: UserPreferences, importAdder: ImportAdder | undefined, addClassElement: (node: ClassElement) => void): void { export function createMissingMemberNodes(
classDeclaration: ClassLikeDeclaration,
possiblyMissingSymbols: readonly Symbol[],
sourceFile: SourceFile,
context: TypeConstructionContext,
preferences: UserPreferences,
importAdder: ImportAdder | undefined,
addClassElement: (node: AddNode) => void): void {
const classMembers = classDeclaration.symbol.members!; const classMembers = classDeclaration.symbol.members!;
for (const symbol of possiblyMissingSymbols) { for (const symbol of possiblyMissingSymbols) {
if (!classMembers.has(symbol.escapedName)) { if (!classMembers.has(symbol.escapedName)) {
addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement); addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement, /* body */ undefined);
} }
} }
} }
@ -28,10 +35,30 @@ namespace ts.codefix {
host: LanguageServiceHost; host: LanguageServiceHost;
} }
type AddNode = PropertyDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | MethodDeclaration | FunctionExpression | ArrowFunction;
export const enum PreserveOptionalFlags {
Method = 1 << 0,
Property = 1 << 1,
All = Method | Property
}
/** /**
* @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. * `addClassElement` will not be called if we can't figure out a representation for `symbol` in `enclosingDeclaration`.
* @param body If defined, this will be the body of the member node passed to `addClassElement`. Otherwise, the body will default to a stub.
*/ */
function addNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, sourceFile: SourceFile, context: TypeConstructionContext, preferences: UserPreferences, importAdder: ImportAdder | undefined, addClassElement: (node: Node) => void): void { export function addNewNodeForMemberSymbol(
symbol: Symbol,
enclosingDeclaration: ClassLikeDeclaration,
sourceFile: SourceFile,
context: TypeConstructionContext,
preferences: UserPreferences,
importAdder: ImportAdder | undefined,
addClassElement: (node: AddNode) => void,
body: Block | undefined,
preserveOptional = PreserveOptionalFlags.All,
isAmbient = false,
): void {
const declarations = symbol.getDeclarations(); const declarations = symbol.getDeclarations();
if (!(declarations && declarations.length)) { if (!(declarations && declarations.length)) {
return undefined; return undefined;
@ -44,7 +71,7 @@ namespace ts.codefix {
const modifiers = visibilityModifier ? factory.createNodeArray([visibilityModifier]) : undefined; const modifiers = visibilityModifier ? factory.createNodeArray([visibilityModifier]) : undefined;
const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
const optional = !!(symbol.flags & SymbolFlags.Optional); const optional = !!(symbol.flags & SymbolFlags.Optional);
const ambient = !!(enclosingDeclaration.flags & NodeFlags.Ambient); const ambient = !!(enclosingDeclaration.flags & NodeFlags.Ambient) || isAmbient;
const quotePreference = getQuotePreference(sourceFile, preferences); const quotePreference = getQuotePreference(sourceFile, preferences);
switch (declaration.kind) { switch (declaration.kind) {
@ -63,7 +90,7 @@ namespace ts.codefix {
/*decorators*/ undefined, /*decorators*/ undefined,
modifiers, modifiers,
name, name,
optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, optional && (preserveOptional & PreserveOptionalFlags.Property) ? factory.createToken(SyntaxKind.QuestionToken) : undefined,
typeNode, typeNode,
/*initializer*/ undefined)); /*initializer*/ undefined));
break; break;
@ -89,7 +116,7 @@ namespace ts.codefix {
name, name,
emptyArray, emptyArray,
typeNode, typeNode,
ambient ? undefined : createStubbedMethodBody(quotePreference))); ambient ? undefined : body || createStubbedMethodBody(quotePreference)));
} }
else { else {
Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter");
@ -100,7 +127,7 @@ namespace ts.codefix {
modifiers, modifiers,
name, name,
createDummyParameters(1, [parameterName], [typeNode], 1, /*inJs*/ false), createDummyParameters(1, [parameterName], [typeNode], 1, /*inJs*/ false),
ambient ? undefined : createStubbedMethodBody(quotePreference))); ambient ? undefined : body || createStubbedMethodBody(quotePreference)));
} }
} }
break; break;
@ -122,7 +149,7 @@ namespace ts.codefix {
if (declarations.length === 1) { if (declarations.length === 1) {
Debug.assert(signatures.length === 1, "One declaration implies one signature"); Debug.assert(signatures.length === 1, "One declaration implies one signature");
const signature = signatures[0]; const signature = signatures[0];
outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : createStubbedMethodBody(quotePreference)); outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : body || createStubbedMethodBody(quotePreference));
break; break;
} }
@ -134,18 +161,18 @@ namespace ts.codefix {
if (!ambient) { if (!ambient) {
if (declarations.length > signatures.length) { if (declarations.length > signatures.length) {
const signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1] as SignatureDeclaration)!; const signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1] as SignatureDeclaration)!;
outputMethod(quotePreference, signature, modifiers, name, createStubbedMethodBody(quotePreference)); outputMethod(quotePreference, signature, modifiers, name, body || createStubbedMethodBody(quotePreference));
} }
else { else {
Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count");
addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional && !!(preserveOptional & PreserveOptionalFlags.Method), modifiers, quotePreference, body));
} }
} }
break; break;
} }
function outputMethod(quotePreference: QuotePreference, signature: Signature, modifiers: NodeArray<Modifier> | undefined, name: PropertyName, body?: Block): void { function outputMethod(quotePreference: QuotePreference, signature: Signature, modifiers: NodeArray<Modifier> | undefined, name: PropertyName, body?: Block): void {
const method = createSignatureDeclarationFromSignature(SyntaxKind.MethodDeclaration, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder); const method = createSignatureDeclarationFromSignature(SyntaxKind.MethodDeclaration, context, quotePreference, signature, body, name, modifiers, optional && !!(preserveOptional & PreserveOptionalFlags.Method), enclosingDeclaration, importAdder);
if (method) addClassElement(method); if (method) addClassElement(method);
} }
} }
@ -348,6 +375,7 @@ namespace ts.codefix {
optional: boolean, optional: boolean,
modifiers: readonly Modifier[] | undefined, modifiers: readonly Modifier[] | undefined,
quotePreference: QuotePreference, quotePreference: QuotePreference,
body: Block | undefined,
): MethodDeclaration { ): MethodDeclaration {
/** This is *a* signature with the maximal number of arguments, /** This is *a* signature with the maximal number of arguments,
* such that if there is a "maximal" signature without rest arguments, * such that if there is a "maximal" signature without rest arguments,
@ -389,7 +417,8 @@ namespace ts.codefix {
/*typeParameters*/ undefined, /*typeParameters*/ undefined,
parameters, parameters,
getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration),
quotePreference); quotePreference,
body);
} }
function getReturnTypeFromSignatures(signatures: readonly Signature[], checker: TypeChecker, context: TypeConstructionContext, enclosingDeclaration: ClassLikeDeclaration): TypeNode | undefined { function getReturnTypeFromSignatures(signatures: readonly Signature[], checker: TypeChecker, context: TypeConstructionContext, enclosingDeclaration: ClassLikeDeclaration): TypeNode | undefined {
@ -406,7 +435,8 @@ namespace ts.codefix {
typeParameters: readonly TypeParameterDeclaration[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined,
parameters: readonly ParameterDeclaration[], parameters: readonly ParameterDeclaration[],
returnType: TypeNode | undefined, returnType: TypeNode | undefined,
quotePreference: QuotePreference quotePreference: QuotePreference,
body: Block | undefined
): MethodDeclaration { ): MethodDeclaration {
return factory.createMethodDeclaration( return factory.createMethodDeclaration(
/*decorators*/ undefined, /*decorators*/ undefined,
@ -417,7 +447,7 @@ namespace ts.codefix {
typeParameters, typeParameters,
parameters, parameters,
returnType, returnType,
createStubbedMethodBody(quotePreference)); body || createStubbedMethodBody(quotePreference));
} }
function createStubbedMethodBody(quotePreference: QuotePreference) { function createStubbedMethodBody(quotePreference: QuotePreference) {

View file

@ -33,6 +33,7 @@ namespace ts.codefix {
}); });
export interface ImportAdder { export interface ImportAdder {
hasFixes(): boolean;
addImportFromDiagnostic: (diagnostic: DiagnosticWithLocation, context: CodeFixContextBase) => void; addImportFromDiagnostic: (diagnostic: DiagnosticWithLocation, context: CodeFixContextBase) => void;
addImportFromExportedSymbol: (exportedSymbol: Symbol, isValidTypeOnlyUseSite?: boolean) => void; addImportFromExportedSymbol: (exportedSymbol: Symbol, isValidTypeOnlyUseSite?: boolean) => void;
writeFixes: (changeTracker: textChanges.ChangeTracker) => void; writeFixes: (changeTracker: textChanges.ChangeTracker) => void;
@ -59,7 +60,7 @@ namespace ts.codefix {
type NewImportsKey = `${0 | 1}|${string}`; type NewImportsKey = `${0 | 1}|${string}`;
/** Use `getNewImportEntry` for access */ /** Use `getNewImportEntry` for access */
const newImports = new Map<NewImportsKey, Mutable<ImportsCollection & { useRequire: boolean }>>(); const newImports = new Map<NewImportsKey, Mutable<ImportsCollection & { useRequire: boolean }>>();
return { addImportFromDiagnostic, addImportFromExportedSymbol, writeFixes }; return { addImportFromDiagnostic, addImportFromExportedSymbol, writeFixes, hasFixes };
function addImportFromDiagnostic(diagnostic: DiagnosticWithLocation, context: CodeFixContextBase) { function addImportFromDiagnostic(diagnostic: DiagnosticWithLocation, context: CodeFixContextBase) {
const info = getFixesInfo(context, diagnostic.code, diagnostic.start, useAutoImportProvider); const info = getFixesInfo(context, diagnostic.code, diagnostic.start, useAutoImportProvider);
@ -217,6 +218,10 @@ namespace ts.codefix {
insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true);
} }
} }
function hasFixes() {
return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0;
}
} }
// Sorted with the preferred fix coming first. // Sorted with the preferred fix coming first.

View file

@ -131,7 +131,7 @@ namespace ts.codefix {
if (typeNode) { if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
const typeTag = factory.createJSDocTypeTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); const typeTag = factory.createJSDocTypeTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined);
addJSDocTags(changes, sourceFile, cast(parent.parent.parent, isExpressionStatement), [typeTag]); changes.addJSDocTags(sourceFile, cast(parent.parent.parent, isExpressionStatement), [typeTag]);
} }
importAdder.writeFixes(changes); importAdder.writeFixes(changes);
return parent; return parent;
@ -271,7 +271,7 @@ namespace ts.codefix {
} }
function annotateJSDocThis(changes: textChanges.ChangeTracker, sourceFile: SourceFile, containingFunction: SignatureDeclaration, typeNode: TypeNode) { function annotateJSDocThis(changes: textChanges.ChangeTracker, sourceFile: SourceFile, containingFunction: SignatureDeclaration, typeNode: TypeNode) {
addJSDocTags(changes, sourceFile, containingFunction, [ changes.addJSDocTags(sourceFile, containingFunction, [
factory.createJSDocThisTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode)), factory.createJSDocThisTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode)),
]); ]);
} }
@ -311,7 +311,7 @@ namespace ts.codefix {
} }
const typeExpression = factory.createJSDocTypeExpression(typeNode); const typeExpression = factory.createJSDocTypeExpression(typeNode);
const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined);
addJSDocTags(changes, sourceFile, parent, [typeTag]); changes.addJSDocTags(sourceFile, parent, [typeTag]);
} }
else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) { else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) {
changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
@ -378,46 +378,7 @@ namespace ts.codefix {
else { else {
const paramTags = map(inferences, ({ name, typeNode, isOptional }) => const paramTags = map(inferences, ({ name, typeNode, isOptional }) =>
factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined)); factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined));
addJSDocTags(changes, sourceFile, signature, paramTags); changes.addJSDocTags(sourceFile, signature, paramTags);
}
}
export function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: readonly JSDocTag[]): void {
const comments = flatMap(parent.jsDoc, j => typeof j.comment === "string" ? factory.createJSDocText(j.comment) : j.comment) as JSDocComment[];
const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags);
const unmergedNewTags = newTags.filter(newTag => !oldTags || !oldTags.some((tag, i) => {
const merged = tryMergeJsdocTags(tag, newTag);
if (merged) oldTags[i] = merged;
return !!merged;
}));
const tag = factory.createJSDocComment(factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n"))), factory.createNodeArray([...(oldTags || emptyArray), ...unmergedNewTags]));
const jsDocNode = parent.kind === SyntaxKind.ArrowFunction ? getJsDocNodeForArrowFunction(parent) : parent;
jsDocNode.jsDoc = parent.jsDoc;
jsDocNode.jsDocCache = parent.jsDocCache;
changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
}
function getJsDocNodeForArrowFunction(signature: ArrowFunction): HasJSDoc {
if (signature.parent.kind === SyntaxKind.PropertyDeclaration) {
return signature.parent as HasJSDoc;
}
return signature.parent.parent as HasJSDoc;
}
function tryMergeJsdocTags(oldTag: JSDocTag, newTag: JSDocTag): JSDocTag | undefined {
if (oldTag.kind !== newTag.kind) {
return undefined;
}
switch (oldTag.kind) {
case SyntaxKind.JSDocParameterTag: {
const oldParam = oldTag as JSDocParameterTag;
const newParam = newTag as JSDocParameterTag;
return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment)
: undefined;
}
case SyntaxKind.JSDocReturnTag:
return factory.createJSDocReturnTag(/*tagName*/ undefined, (newTag as JSDocReturnTag).typeExpression, oldTag.comment);
} }
} }
@ -1000,13 +961,25 @@ namespace ts.codefix {
if (usage.numberIndex) { if (usage.numberIndex) {
types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); types.push(checker.createArrayType(combineFromUsage(usage.numberIndex)));
} }
if (usage.properties?.size || usage.calls?.length || usage.constructs?.length || usage.stringIndex) { if (usage.properties?.size || usage.constructs?.length || usage.stringIndex) {
types.push(inferStructuralType(usage)); types.push(inferStructuralType(usage));
} }
types.push(...(usage.candidateTypes || []).map(t => checker.getBaseTypeOfLiteralType(t))); const candidateTypes = (usage.candidateTypes || []).map(t => checker.getBaseTypeOfLiteralType(t));
types.push(...inferNamedTypesFromProperties(usage)); const callsType = usage.calls?.length ? inferStructuralType(usage) : undefined;
if (callsType && candidateTypes) {
types.push(checker.getUnionType([callsType, ...candidateTypes], UnionReduction.Subtype));
}
else {
if (callsType) {
types.push(callsType);
}
if (length(candidateTypes)) {
types.push(...candidateTypes);
}
}
types.push(...inferNamedTypesFromProperties(usage));
return types; return types;
} }

View file

@ -57,7 +57,9 @@ namespace ts.Completions {
*/ */
export enum CompletionSource { export enum CompletionSource {
/** Completions that require `this.` insertion text */ /** Completions that require `this.` insertion text */
ThisProperty = "ThisProperty/" ThisProperty = "ThisProperty/",
/** Auto-import that comes attached to a class member snippet */
ClassMemberSnippet = "ClassMemberSnippet/",
} }
const enum SymbolOriginInfoKind { const enum SymbolOriginInfoKind {
@ -244,7 +246,6 @@ namespace ts.Completions {
// If the request is a continuation of an earlier `isIncomplete` response, // If the request is a continuation of an earlier `isIncomplete` response,
// we can continue it from the cached previous response. // we can continue it from the cached previous response.
const typeChecker = program.getTypeChecker();
const compilerOptions = program.getCompilerOptions(); const compilerOptions = program.getCompilerOptions();
const incompleteCompletionsCache = preferences.allowIncompleteCompletions ? host.getIncompleteCompletionsCache?.() : undefined; const incompleteCompletionsCache = preferences.allowIncompleteCompletions ? host.getIncompleteCompletionsCache?.() : undefined;
if (incompleteCompletionsCache && completionKind === CompletionTriggerKind.TriggerForIncompleteCompletions && previousToken && isIdentifier(previousToken)) { if (incompleteCompletionsCache && completionKind === CompletionTriggerKind.TriggerForIncompleteCompletions && previousToken && isIdentifier(previousToken)) {
@ -257,7 +258,7 @@ namespace ts.Completions {
incompleteCompletionsCache?.clear(); incompleteCompletionsCache?.clear();
} }
const stringCompletions = StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, typeChecker, compilerOptions, host, log, preferences); const stringCompletions = StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences);
if (stringCompletions) { if (stringCompletions) {
return stringCompletions; return stringCompletions;
} }
@ -274,7 +275,7 @@ namespace ts.Completions {
switch (completionData.kind) { switch (completionData.kind) {
case CompletionDataKind.Data: case CompletionDataKind.Data:
const response = completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); const response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences);
if (response?.isIncomplete) { if (response?.isIncomplete) {
incompleteCompletionsCache?.set(response); incompleteCompletionsCache?.set(response);
} }
@ -403,7 +404,15 @@ namespace ts.Completions {
return location?.kind === SyntaxKind.Identifier ? createTextSpanFromNode(location) : undefined; return location?.kind === SyntaxKind.Identifier ? createTextSpanFromNode(location) : undefined;
} }
function completionInfoFromData(sourceFile: SourceFile, typeChecker: TypeChecker, compilerOptions: CompilerOptions, log: Log, completionData: CompletionData, preferences: UserPreferences): CompletionInfo | undefined { function completionInfoFromData(
sourceFile: SourceFile,
host: LanguageServiceHost,
program: Program,
compilerOptions: CompilerOptions,
log: Log,
completionData: CompletionData,
preferences: UserPreferences,
): CompletionInfo | undefined {
const { const {
symbols, symbols,
contextToken, contextToken,
@ -443,7 +452,8 @@ namespace ts.Completions {
contextToken, contextToken,
location, location,
sourceFile, sourceFile,
typeChecker, host,
program,
getEmitScriptTarget(compilerOptions), getEmitScriptTarget(compilerOptions),
log, log,
completionKind, completionKind,
@ -472,7 +482,8 @@ namespace ts.Completions {
contextToken, contextToken,
location, location,
sourceFile, sourceFile,
typeChecker, host,
program,
getEmitScriptTarget(compilerOptions), getEmitScriptTarget(compilerOptions),
log, log,
completionKind, completionKind,
@ -614,7 +625,8 @@ namespace ts.Completions {
contextToken: Node | undefined, contextToken: Node | undefined,
location: Node, location: Node,
sourceFile: SourceFile, sourceFile: SourceFile,
typeChecker: TypeChecker, host: LanguageServiceHost,
program: Program,
name: string, name: string,
needsConvertPropertyAccess: boolean, needsConvertPropertyAccess: boolean,
origin: SymbolOriginInfo | undefined, origin: SymbolOriginInfo | undefined,
@ -625,14 +637,17 @@ namespace ts.Completions {
useSemicolons: boolean, useSemicolons: boolean,
options: CompilerOptions, options: CompilerOptions,
preferences: UserPreferences, preferences: UserPreferences,
completionKind: CompletionKind,
): CompletionEntry | undefined { ): CompletionEntry | undefined {
let insertText: string | undefined; let insertText: string | undefined;
let replacementSpan = getReplacementSpanForContextToken(replacementToken); let replacementSpan = getReplacementSpanForContextToken(replacementToken);
let data: CompletionEntryData | undefined; let data: CompletionEntryData | undefined;
let isSnippet: true | undefined; let isSnippet: true | undefined;
let source = getSourceFromOrigin(origin);
let sourceDisplay; let sourceDisplay;
let hasAction; let hasAction;
const typeChecker = program.getTypeChecker();
const insertQuestionDot = origin && originIsNullableMember(origin); const insertQuestionDot = origin && originIsNullableMember(origin);
const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess;
if (origin && originIsThisType(origin)) { if (origin && originIsThisType(origin)) {
@ -686,13 +701,16 @@ namespace ts.Completions {
} }
} }
if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { if (preferences.includeCompletionsWithClassMemberSnippets &&
return undefined; preferences.includeCompletionsWithInsertText &&
} completionKind === CompletionKind.MemberLike &&
isClassLikeMemberCompletion(symbol, location)) {
if (originIsExport(origin) || originIsResolvedExport(origin)) { let importAdder;
data = originToCompletionEntryData(origin); ({ insertText, isSnippet, importAdder } = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken));
hasAction = !importCompletionNode; if (importAdder?.hasFixes()) {
hasAction = true;
source = CompletionSource.ClassMemberSnippet;
}
} }
const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, location); const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, location);
@ -720,10 +738,15 @@ namespace ts.Completions {
insertText = `${escapeSnippetText(name)}={$1}`; insertText = `${escapeSnippetText(name)}={$1}`;
isSnippet = true; isSnippet = true;
} }
}
if (isSnippet) { if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) {
replacementSpan = createTextSpanFromNode(location, sourceFile); return undefined;
} }
if (originIsExport(origin) || originIsResolvedExport(origin)) {
data = originToCompletionEntryData(origin);
hasAction = !importCompletionNode;
} }
// TODO(drosen): Right now we just permit *all* semantic meanings when calling // TODO(drosen): Right now we just permit *all* semantic meanings when calling
@ -739,7 +762,7 @@ namespace ts.Completions {
kind, kind,
kindModifiers: SymbolDisplay.getSymbolModifiers(typeChecker, symbol), kindModifiers: SymbolDisplay.getSymbolModifiers(typeChecker, symbol),
sortText, sortText,
source: getSourceFromOrigin(origin), source,
hasAction: hasAction ? true : undefined, hasAction: hasAction ? true : undefined,
isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined,
insertText, insertText,
@ -752,8 +775,232 @@ namespace ts.Completions {
}; };
} }
function escapeSnippetText(text: string): string { function isClassLikeMemberCompletion(symbol: Symbol, location: Node): boolean {
return text.replace(/\$/gm, "\\$"); // TODO: support JS files.
if (isInJSFile(location)) {
return false;
}
// Completion symbol must be for a class member.
const memberFlags =
SymbolFlags.ClassMember
& SymbolFlags.EnumMemberExcludes;
/* In
`class C {
|
}`
`location` is a class-like declaration.
In
`class C {
m|
}`
`location` is an identifier,
`location.parent` is a class element declaration,
and `location.parent.parent` is a class-like declaration.
In
`abstract class C {
abstract
abstract m|
}`
`location` is a syntax list (with modifiers as children),
and `location.parent` is a class-like declaration.
*/
return !!(symbol.flags & memberFlags) &&
(
isClassLike(location) ||
(
location.parent &&
location.parent.parent &&
isClassElement(location.parent) &&
location === location.parent.name &&
isClassLike(location.parent.parent)
) ||
(
location.parent &&
isSyntaxList(location) &&
isClassLike(location.parent)
)
);
}
function getEntryForMemberCompletion(
host: LanguageServiceHost,
program: Program,
options: CompilerOptions,
preferences: UserPreferences,
name: string,
symbol: Symbol,
location: Node,
contextToken: Node | undefined,
): { insertText: string, isSnippet?: true, importAdder?: codefix.ImportAdder } {
const classLikeDeclaration = findAncestor(location, isClassLike);
if (!classLikeDeclaration) {
return { insertText: name };
}
let isSnippet: true | undefined;
let insertText: string = name;
const checker = program.getTypeChecker();
const sourceFile = location.getSourceFile();
const printer = createSnippetPrinter({
removeComments: true,
module: options.module,
target: options.target,
omitTrailingSemicolon: false,
newLine: getNewLineKind(getNewLineCharacter(options, maybeBind(host, host.getNewLine))),
});
const importAdder = codefix.createImportAdder(sourceFile, program, preferences, host);
let body;
if (preferences.includeCompletionsWithSnippetText) {
isSnippet = true;
// We are adding a tabstop (i.e. `$0`) in the body of the suggested member,
// if it has one, so that the cursor ends up in the body once the completion is inserted.
// Note: this assumes we won't have more than one body in the completion nodes, which should be the case.
const emptyStatement = factory.createExpressionStatement(factory.createIdentifier(""));
setSnippetElement(emptyStatement, { kind: SnippetKind.TabStop, order: 0 });
body = factory.createBlock([emptyStatement], /* multiline */ true);
}
else {
body = factory.createBlock([], /* multiline */ true);
}
let modifiers = ModifierFlags.None;
// Whether the suggested member should be abstract.
// e.g. in `abstract class C { abstract | }`, we should offer abstract method signatures at position `|`.
// Note: We are relying on checking if the context token is `abstract`,
// since other visibility modifiers (e.g. `protected`) should come *before* `abstract`.
// However, that is not true for the e.g. `override` modifier, so this check has its limitations.
const isAbstract = contextToken && isModifierLike(contextToken) === SyntaxKind.AbstractKeyword;
const completionNodes: Node[] = [];
codefix.addNewNodeForMemberSymbol(
symbol,
classLikeDeclaration,
sourceFile,
{ program, host },
preferences,
importAdder,
// `addNewNodeForMemberSymbol` calls this callback function for each new member node
// it adds for the given member symbol.
// We store these member nodes in the `completionNodes` array.
// Note: there might be:
// - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member;
// - One node;
// - More than one node if the member is overloaded (e.g. a method with overload signatures).
node => {
let requiredModifiers = ModifierFlags.None;
if (isAbstract) {
requiredModifiers |= ModifierFlags.Abstract;
}
if (isClassElement(node)
&& checker.getMemberOverrideModifierStatus(classLikeDeclaration, node) === MemberOverrideStatus.NeedsOverride) {
requiredModifiers |= ModifierFlags.Override;
}
let presentModifiers = ModifierFlags.None;
if (!completionNodes.length) {
// Omit already present modifiers from the first completion node/signature.
if (contextToken) {
presentModifiers = getPresentModifiers(contextToken);
}
// Keep track of added missing required modifiers and modifiers already present.
// This is needed when we have overloaded signatures,
// so this callback will be called for multiple nodes/signatures,
// and we need to make sure the modifiers are uniform for all nodes/signatures.
modifiers = node.modifierFlagsCache | requiredModifiers | presentModifiers;
}
node = factory.updateModifiers(node, modifiers & (~presentModifiers));
completionNodes.push(node);
},
body,
codefix.PreserveOptionalFlags.Property,
isAbstract);
if (completionNodes.length) {
insertText = printer.printSnippetList(
ListFormat.MultiLine | ListFormat.NoTrailingNewLine,
factory.createNodeArray(completionNodes),
sourceFile);
}
return { insertText, isSnippet, importAdder };
}
function getPresentModifiers(contextToken: Node): ModifierFlags {
let modifiers = ModifierFlags.None;
let contextMod;
/*
Cases supported:
In
`class C {
public abstract |
}`
`contextToken` is ``abstract`` (as an identifier),
`contextToken.parent` is property declaration,
`location` is class declaration ``class C { ... }``.
In
`class C {
protected override m|
}`
`contextToken` is ``override`` (as a keyword),
`contextToken.parent` is property declaration,
`location` is identifier ``m``,
`location.parent` is property declaration ``protected override m``,
`location.parent.parent` is class declaration ``class C { ... }``.
*/
if (contextMod = isModifierLike(contextToken)) {
modifiers |= modifierToFlag(contextMod);
}
if (isPropertyDeclaration(contextToken.parent)) {
modifiers |= modifiersToFlags(contextToken.parent.modifiers);
}
return modifiers;
}
function isModifierLike(node: Node): ModifierSyntaxKind | undefined {
if (isModifier(node)) {
return node.kind;
}
if (isIdentifier(node) && node.originalKeywordKind && isModifierKind(node.originalKeywordKind)) {
return node.originalKeywordKind;
}
return undefined;
}
function createSnippetPrinter(
printerOptions: PrinterOptions,
) {
const printer = createPrinter(printerOptions);
const baseWriter = createTextWriter(getNewLineCharacter(printerOptions));
const writer: EmitTextWriter = {
...baseWriter,
write: s => baseWriter.write(escapeSnippetText(s)),
nonEscapingWrite: baseWriter.write,
writeLiteral: s => baseWriter.writeLiteral(escapeSnippetText(s)),
writeStringLiteral: s => baseWriter.writeStringLiteral(escapeSnippetText(s)),
writeSymbol: (s, symbol) => baseWriter.writeSymbol(escapeSnippetText(s), symbol),
writeParameter: s => baseWriter.writeParameter(escapeSnippetText(s)),
writeComment: s => baseWriter.writeComment(escapeSnippetText(s)),
writeProperty: s => baseWriter.writeProperty(escapeSnippetText(s)),
};
return {
printSnippetList,
};
/* Snippet-escaping version of `printer.printList`. */
function printSnippetList(
format: ListFormat,
list: NodeArray<Node>,
sourceFile: SourceFile | undefined,
): string {
writer.clear();
printer.writeList(format, list, sourceFile, writer);
return writer.getText();
}
} }
function originToCompletionEntryData(origin: SymbolOriginInfoExport | SymbolOriginInfoResolvedExport): CompletionEntryData | undefined { function originToCompletionEntryData(origin: SymbolOriginInfoExport | SymbolOriginInfoResolvedExport): CompletionEntryData | undefined {
@ -863,7 +1110,8 @@ namespace ts.Completions {
contextToken: Node | undefined, contextToken: Node | undefined,
location: Node, location: Node,
sourceFile: SourceFile, sourceFile: SourceFile,
typeChecker: TypeChecker, host: LanguageServiceHost,
program: Program,
target: ScriptTarget, target: ScriptTarget,
log: Log, log: Log,
kind: CompletionKind, kind: CompletionKind,
@ -881,6 +1129,7 @@ namespace ts.Completions {
const start = timestamp(); const start = timestamp();
const variableDeclaration = getVariableDeclaration(location); const variableDeclaration = getVariableDeclaration(location);
const useSemicolons = probablyUsesSemicolons(sourceFile); const useSemicolons = probablyUsesSemicolons(sourceFile);
const typeChecker = program.getTypeChecker();
// Tracks unique names. // Tracks unique names.
// Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // Value is set to false for global variables or completions from external module exports, because we can have multiple of those;
// true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports.
@ -904,7 +1153,8 @@ namespace ts.Completions {
contextToken, contextToken,
location, location,
sourceFile, sourceFile,
typeChecker, host,
program,
name, name,
needsConvertPropertyAccess, needsConvertPropertyAccess,
origin, origin,
@ -914,7 +1164,8 @@ namespace ts.Completions {
importCompletionNode, importCompletionNode,
useSemicolons, useSemicolons,
compilerOptions, compilerOptions,
preferences preferences,
kind,
); );
if (!entry) { if (!entry) {
continue; continue;
@ -1021,6 +1272,7 @@ namespace ts.Completions {
location: Node; location: Node;
origin: SymbolOriginInfo | SymbolOriginInfoExport | SymbolOriginInfoResolvedExport | undefined; origin: SymbolOriginInfo | SymbolOriginInfoExport | SymbolOriginInfoResolvedExport | undefined;
previousToken: Node | undefined; previousToken: Node | undefined;
contextToken: Node | undefined;
readonly isJsxInitializer: IsJsxInitializer; readonly isJsxInitializer: IsJsxInitializer;
readonly isTypeOnlyLocation: boolean; readonly isTypeOnlyLocation: boolean;
} }
@ -1036,11 +1288,13 @@ namespace ts.Completions {
if (entryId.data) { if (entryId.data) {
const autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); const autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host);
if (autoImport) { if (autoImport) {
const { contextToken, previousToken } = getRelevantTokens(position, sourceFile);
return { return {
type: "symbol", type: "symbol",
symbol: autoImport.symbol, symbol: autoImport.symbol,
location: getTouchingPropertyName(sourceFile, position), location: getTouchingPropertyName(sourceFile, position),
previousToken: findPrecedingToken(position, sourceFile, /*startNode*/ undefined)!, previousToken,
contextToken,
isJsxInitializer: false, isJsxInitializer: false,
isTypeOnlyLocation: false, isTypeOnlyLocation: false,
origin: autoImport.origin, origin: autoImport.origin,
@ -1057,7 +1311,7 @@ namespace ts.Completions {
return { type: "request", request: completionData }; return { type: "request", request: completionData };
} }
const { symbols, literals, location, completionKind, symbolToOriginInfoMap, previousToken, isJsxInitializer, isTypeOnlyLocation } = completionData; const { symbols, literals, location, completionKind, symbolToOriginInfoMap, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation } = completionData;
const literal = find(literals, l => completionNameForLiteral(sourceFile, preferences, l) === entryId.name); const literal = find(literals, l => completionNameForLiteral(sourceFile, preferences, l) === entryId.name);
if (literal !== undefined) return { type: "literal", literal }; if (literal !== undefined) return { type: "literal", literal };
@ -1069,8 +1323,8 @@ namespace ts.Completions {
return firstDefined(symbols, (symbol, index): SymbolCompletion | undefined => { return firstDefined(symbols, (symbol, index): SymbolCompletion | undefined => {
const origin = symbolToOriginInfoMap[index]; const origin = symbolToOriginInfoMap[index];
const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected);
return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source return info && info.name === entryId.name && (entryId.source === CompletionSource.ClassMemberSnippet && symbol.flags & SymbolFlags.ClassMember || getSourceFromOrigin(origin) === entryId.source)
? { type: "symbol" as const, symbol, location, origin, previousToken, isJsxInitializer, isTypeOnlyLocation } ? { type: "symbol" as const, symbol, location, origin, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation }
: undefined; : undefined;
}) || { type: "none" }; }) || { type: "none" };
} }
@ -1094,7 +1348,7 @@ namespace ts.Completions {
): CompletionEntryDetails | undefined { ): CompletionEntryDetails | undefined {
const typeChecker = program.getTypeChecker(); const typeChecker = program.getTypeChecker();
const compilerOptions = program.getCompilerOptions(); const compilerOptions = program.getCompilerOptions();
const { name } = entryId; const { name, source, data } = entryId;
const contextToken = findPrecedingToken(position, sourceFile); const contextToken = findPrecedingToken(position, sourceFile);
if (isInString(sourceFile, position, contextToken)) { if (isInString(sourceFile, position, contextToken)) {
@ -1120,8 +1374,8 @@ namespace ts.Completions {
} }
} }
case "symbol": { case "symbol": {
const { symbol, location, origin, previousToken } = symbolCompletion; const { symbol, location, contextToken, origin, previousToken } = symbolCompletion;
const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data); const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source);
return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217
} }
case "literal": { case "literal": {
@ -1157,6 +1411,9 @@ namespace ts.Completions {
readonly sourceDisplay: SymbolDisplayPart[] | undefined; readonly sourceDisplay: SymbolDisplayPart[] | undefined;
} }
function getCompletionEntryCodeActionsAndSourceDisplay( function getCompletionEntryCodeActionsAndSourceDisplay(
name: string,
location: Node,
contextToken: Node | undefined,
origin: SymbolOriginInfo | SymbolOriginInfoExport | SymbolOriginInfoResolvedExport | undefined, origin: SymbolOriginInfo | SymbolOriginInfoExport | SymbolOriginInfoResolvedExport | undefined,
symbol: Symbol, symbol: Symbol,
program: Program, program: Program,
@ -1168,6 +1425,7 @@ namespace ts.Completions {
formatContext: formatting.FormatContext, formatContext: formatting.FormatContext,
preferences: UserPreferences, preferences: UserPreferences,
data: CompletionEntryData | undefined, data: CompletionEntryData | undefined,
source: string | undefined,
): CodeActionsAndSourceDisplay { ): CodeActionsAndSourceDisplay {
if (data?.moduleSpecifier) { if (data?.moduleSpecifier) {
const { contextToken, previousToken } = getRelevantTokens(position, sourceFile); const { contextToken, previousToken } = getRelevantTokens(position, sourceFile);
@ -1177,6 +1435,30 @@ namespace ts.Completions {
} }
} }
if (source === CompletionSource.ClassMemberSnippet) {
const { importAdder } = getEntryForMemberCompletion(
host,
program,
compilerOptions,
preferences,
name,
symbol,
location,
contextToken);
if (importAdder) {
const changes = textChanges.ChangeTracker.with(
{ host, formatContext, preferences },
importAdder.writeFixes);
return {
sourceDisplay: undefined,
codeActions: [{
changes,
description: diagnosticToString([Diagnostics.Includes_imports_of_types_referenced_by_0, name]),
}],
};
}
}
if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) { if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) {
return { codeActions: undefined, sourceDisplay: undefined }; return { codeActions: undefined, sourceDisplay: undefined };
} }
@ -3243,6 +3525,7 @@ namespace ts.Completions {
// function f<T>(x: T) {} // function f<T>(x: T) {}
// f({ abc/**/: "" }) // `abc` is a member of `T` but only because it declares itself // f({ abc/**/: "" }) // `abc` is a member of `T` but only because it declares itself
function hasDeclarationOtherThanSelf(member: Symbol) { function hasDeclarationOtherThanSelf(member: Symbol) {
if (!length(member.declarations)) return true;
return some(member.declarations, decl => decl.parent !== obj); return some(member.declarations, decl => decl.parent !== obj);
} }
} }
@ -3606,5 +3889,6 @@ namespace ts.Completions {
} }
return charCode; return charCode;
} }
} }

View file

@ -1323,7 +1323,7 @@ namespace ts.FindAllReferences {
if (!symbol) return undefined; if (!symbol) return undefined;
for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer)) { for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer)) {
if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue;
const referenceSymbol: Symbol = checker.getSymbolAtLocation(token)!; // See GH#19955 for why the type annotation is necessary const referenceSymbol = checker.getSymbolAtLocation(token)!;
if (referenceSymbol === symbol if (referenceSymbol === symbol
|| checker.getShorthandAssignmentValueSymbol(token.parent) === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol
|| isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { || isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) {
@ -2021,7 +2021,8 @@ namespace ts.FindAllReferences {
} }
} }
else { else {
return nodeEntry(ref, EntryKind.StringLiteral); return isNoSubstitutionTemplateLiteral(ref) && !rangeIsOnSingleLine(ref, sourceFile) ? undefined :
nodeEntry(ref, EntryKind.StringLiteral);
} }
} }
}); });

View file

@ -198,14 +198,17 @@ namespace ts.GoToDefinition {
return undefined; return undefined;
} }
const symbol = typeChecker.getSymbolAtLocation(node); const symbol = getSymbol(node, typeChecker);
if (!symbol) return undefined; if (!symbol) return undefined;
const typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); const typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
const returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); const returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker);
const fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); const fromReturnType = returnType && definitionFromType(returnType, typeChecker, node);
// If a function returns 'void' or some other type with no definition, just return the function definition. // If a function returns 'void' or some other type with no definition, just return the function definition.
return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); const typeDefinitions = fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node);
return typeDefinitions.length ? typeDefinitions
: !(symbol.flags & SymbolFlags.Value) && symbol.flags & SymbolFlags.Type ? getDefinitionFromSymbol(typeChecker, skipAlias(symbol, typeChecker), node)
: undefined;
} }
function definitionFromType(type: Type, checker: TypeChecker, node: Node): readonly DefinitionInfo[] { function definitionFromType(type: Type, checker: TypeChecker, node: Node): readonly DefinitionInfo[] {

View file

@ -34,7 +34,7 @@ namespace ts.OutliningElementsCollector {
if (depthRemaining === 0) return; if (depthRemaining === 0) return;
cancellationToken.throwIfCancellationRequested(); cancellationToken.throwIfCancellationRequested();
if (isDeclaration(n) || isVariableStatement(n) || isReturnStatement(n) || n.kind === SyntaxKind.EndOfFileToken) { if (isDeclaration(n) || isVariableStatement(n) || isReturnStatement(n) || isCallOrNewExpression(n) || n.kind === SyntaxKind.EndOfFileToken) {
addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out);
} }

View file

@ -314,8 +314,7 @@ namespace ts.refactor.extractSymbol {
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
} }
const statements: Statement[] = []; const statements: Statement[] = [];
const start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 for (const statement of start.parent.statements) {
for (const statement of (start2.parent as BlockLike).statements) {
if (statement === start || statements.length) { if (statement === start || statements.length) {
const errors = checkNode(statement); const errors = checkNode(statement);
if (errors) { if (errors) {
@ -364,10 +363,11 @@ namespace ts.refactor.extractSymbol {
return node.expression; return node.expression;
} }
} }
else if (isVariableStatement(node)) { else if (isVariableStatement(node) || isVariableDeclarationList(node)) {
const declarations = isVariableStatement(node) ? node.declarationList.declarations : node.declarations;
let numInitializers = 0; let numInitializers = 0;
let lastInitializer: Expression | undefined; let lastInitializer: Expression | undefined;
for (const declaration of node.declarationList.declarations) { for (const declaration of declarations) {
if (declaration.initializer) { if (declaration.initializer) {
numInitializers++; numInitializers++;
lastInitializer = declaration.initializer; lastInitializer = declaration.initializer;
@ -383,7 +383,6 @@ namespace ts.refactor.extractSymbol {
return node.initializer; return node.initializer;
} }
} }
return node; return node;
} }

View file

@ -599,10 +599,11 @@ namespace ts {
} }
function findBaseOfDeclaration<T>(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined { function findBaseOfDeclaration<T>(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined {
if (hasStaticModifier(declaration)) return;
const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent; const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;
if (!classOrInterfaceDeclaration) { if (!classOrInterfaceDeclaration) return;
return;
}
return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), superTypeNode => { return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), superTypeNode => {
const symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); const symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name);
return symbol ? cb(symbol) : undefined; return symbol ? cb(symbol) : undefined;

View file

@ -1,18 +1,35 @@
/* @internal */ /* @internal */
namespace ts.Completions.StringCompletions { namespace ts.Completions.StringCompletions {
export function getStringLiteralCompletions(sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, options: CompilerOptions, host: LanguageServiceHost, log: Log, preferences: UserPreferences): CompletionInfo | undefined { export function getStringLiteralCompletions(
sourceFile: SourceFile,
position: number,
contextToken: Node | undefined,
options: CompilerOptions,
host: LanguageServiceHost,
program: Program,
log: Log,
preferences: UserPreferences): CompletionInfo | undefined {
if (isInReferenceComment(sourceFile, position)) { if (isInReferenceComment(sourceFile, position)) {
const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host);
return entries && convertPathCompletions(entries); return entries && convertPathCompletions(entries);
} }
if (isInString(sourceFile, position, contextToken)) { if (isInString(sourceFile, position, contextToken)) {
if (!contextToken || !isStringLiteralLike(contextToken)) return undefined; if (!contextToken || !isStringLiteralLike(contextToken)) return undefined;
const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences);
return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences);
} }
} }
function convertStringLiteralCompletions(completion: StringLiteralCompletion | undefined, contextToken: StringLiteralLike, sourceFile: SourceFile, checker: TypeChecker, log: Log, options: CompilerOptions, preferences: UserPreferences): CompletionInfo | undefined { function convertStringLiteralCompletions(
completion: StringLiteralCompletion | undefined,
contextToken: StringLiteralLike,
sourceFile: SourceFile,
host: LanguageServiceHost,
program: Program,
log: Log,
options: CompilerOptions,
preferences: UserPreferences,
): CompletionInfo | undefined {
if (completion === undefined) { if (completion === undefined) {
return undefined; return undefined;
} }
@ -30,7 +47,8 @@ namespace ts.Completions.StringCompletions {
contextToken, contextToken,
sourceFile, sourceFile,
sourceFile, sourceFile,
checker, host,
program,
ScriptTarget.ESNext, ScriptTarget.ESNext,
log, log,
CompletionKind.String, CompletionKind.String,

View file

@ -494,6 +494,27 @@ namespace ts.textChanges {
this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent });
} }
public addJSDocTags(sourceFile: SourceFile, parent: HasJSDoc, newTags: readonly JSDocTag[]): void {
const comments = flatMap(parent.jsDoc, j => typeof j.comment === "string" ? factory.createJSDocText(j.comment) : j.comment) as JSDocComment[];
const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags);
const unmergedNewTags = newTags.filter(newTag => !oldTags.some((tag, i) => {
const merged = tryMergeJsdocTags(tag, newTag);
if (merged) oldTags[i] = merged;
return !!merged;
}));
const tag = factory.createJSDocComment(factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n"))), factory.createNodeArray([...oldTags, ...unmergedNewTags]));
const host = updateJSDocHost(parent);
this.insertJsdocCommentBefore(sourceFile, host, tag);
}
public filterJSDocTags(sourceFile: SourceFile, parent: HasJSDoc, predicate: (tag: JSDocTag) => boolean): void {
const comments = flatMap(parent.jsDoc, j => typeof j.comment === "string" ? factory.createJSDocText(j.comment) : j.comment) as JSDocComment[];
const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags);
const tag = factory.createJSDocComment(factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n"))), factory.createNodeArray([...(filter(oldTags, predicate) || emptyArray)]));
const host = updateJSDocHost(parent);
this.insertJsdocCommentBefore(sourceFile, host, tag);
}
public replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string): void { public replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string): void {
this.changes.push({ kind: ChangeKind.Text, sourceFile, range, text }); this.changes.push({ kind: ChangeKind.Text, sourceFile, range, text });
} }
@ -920,6 +941,35 @@ namespace ts.textChanges {
} }
} }
function updateJSDocHost(parent: HasJSDoc): HasJSDoc {
if (parent.kind !== SyntaxKind.ArrowFunction) {
return parent;
}
const jsDocNode = parent.parent.kind === SyntaxKind.PropertyDeclaration ?
parent.parent as HasJSDoc :
parent.parent.parent as HasJSDoc;
jsDocNode.jsDoc = parent.jsDoc;
jsDocNode.jsDocCache = parent.jsDocCache;
return jsDocNode;
}
function tryMergeJsdocTags(oldTag: JSDocTag, newTag: JSDocTag): JSDocTag | undefined {
if (oldTag.kind !== newTag.kind) {
return undefined;
}
switch (oldTag.kind) {
case SyntaxKind.JSDocParameterTag: {
const oldParam = oldTag as JSDocParameterTag;
const newParam = newTag as JSDocParameterTag;
return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment)
: undefined;
}
case SyntaxKind.JSDocReturnTag:
return factory.createJSDocReturnTag(/*tagName*/ undefined, (newTag as JSDocReturnTag).typeExpression, oldTag.comment);
}
}
// find first non-whitespace position in the leading trivia of the node // find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile: SourceFile, node: Node): number { function startPositionToDeleteNodeInList(sourceFile: SourceFile, node: Node): number {
return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
@ -1037,7 +1087,7 @@ namespace ts.textChanges {
/** Note: output node may be mutated input node. */ /** Note: output node may be mutated input node. */
export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } { export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } {
const writer = createWriter(newLineCharacter); const writer = createWriter(newLineCharacter);
const newLine = newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed; const newLine = getNewLineKind(newLineCharacter);
createPrinter({ createPrinter({
newLine, newLine,
neverAsciiEscape: true, neverAsciiEscape: true,

View file

@ -3279,5 +3279,16 @@ namespace ts {
return decisionFromFile ?? program.usesUriStyleNodeCoreModules; return decisionFromFile ?? program.usesUriStyleNodeCoreModules;
} }
export function getNewLineKind(newLineCharacter: string): NewLineKind {
return newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed;
}
export type DiagnosticAndArguments = DiagnosticMessage | [DiagnosticMessage, string] | [DiagnosticMessage, string, string];
export function diagnosticToString(diag: DiagnosticAndArguments): string {
return isArray(diag)
? formatStringFromArgs(getLocaleSpecificMessage(diag[0]), diag.slice(1) as readonly string[])
: getLocaleSpecificMessage(diag);
}
// #endregion // #endregion
} }

View file

@ -14,7 +14,7 @@ namespace Harness.Parallel.Host {
const { statSync } = require("fs") as typeof import("fs"); const { statSync } = require("fs") as typeof import("fs");
// NOTE: paths for module and types for FailedTestReporter _do not_ line up due to our use of --outFile for run.js // NOTE: paths for module and types for FailedTestReporter _do not_ line up due to our use of --outFile for run.js
const FailedTestReporter = require(path.resolve(__dirname, "../../scripts/failed-tests")) as typeof import("../../../scripts/failed-tests"); const FailedTestReporter = require(Utils.findUpFile("scripts/failed-tests.js")) as typeof import("../../../scripts/failed-tests");
const perfdataFileNameFragment = ".parallelperf"; const perfdataFileNameFragment = ".parallelperf";
const perfData = readSavedPerfData(configOption); const perfData = readSavedPerfData(configOption);

View file

@ -211,7 +211,7 @@ namespace ts {
start: undefined, start: undefined,
length: undefined, length: undefined,
}, { }, {
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'esnext'.", messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'esnext'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,

View file

@ -182,34 +182,3 @@ describe("unittests:: Public APIs:: getChild* methods on EndOfFileToken with JSD
assert.equal(endOfFileToken.getChildCount(), 1); assert.equal(endOfFileToken.getChildCount(), 1);
assert.notEqual(endOfFileToken.getChildAt(0), /*expected*/ undefined); assert.notEqual(endOfFileToken.getChildAt(0), /*expected*/ undefined);
}); });
describe("unittests:: Public APIs:: sys", () => {
it("readDirectory", () => {
// #45990, testing passing a non-absolute path
// `sys.readDirectory` is just `matchFiles` plugged into the real FS
const read = ts.matchFiles(
/*path*/ "",
/*extensions*/ [".ts", ".tsx"],
/*excludes*/ ["node_modules", "dist"],
/*includes*/ ["**/*"],
/*useCaseSensitiveFileNames*/ true,
/*currentDirectory*/ "/",
/*depth*/ undefined,
/*getFileSystemEntries*/ path => {
switch (path) {
case "/": return { directories: [], files: ["file.ts"] };
default: return { directories: [], files: [] };
}
},
/*realpath*/ ts.identity,
/*directoryExists*/ path => {
switch (path) {
case "/": return true;
default: return false;
}
}
);
assert.deepEqual(read, ["/file.ts"]);
});
});

View file

@ -191,7 +191,7 @@ namespace ts {
testExtractRange("extractRange28", `[#|return [$|1|];|]`); testExtractRange("extractRange28", `[#|return [$|1|];|]`);
// For statements // For statements
testExtractRange("extractRange29", `for ([#|var i = 1|]; i < 2; i++) {}`); testExtractRange("extractRange29", `for ([#|var i = [$|1|]|]; i < 2; i++) {}`);
testExtractRange("extractRange30", `for (var i = [#|[$|1|]|]; i < 2; i++) {}`); testExtractRange("extractRange30", `for (var i = [#|[$|1|]|]; i < 2; i++) {}`);
}); });

View file

@ -326,7 +326,7 @@ namespace ts.projectSystem {
}; };
function updateFile(path: string, newText: string) { function updateFile(path: string, newText: string) {
Debug.assertDefined(files.find(f => f.path === path)); Debug.assertIsDefined(files.find(f => f.path === path));
session.executeCommandSeq<protocol.ApplyChangedToOpenFilesRequest>({ session.executeCommandSeq<protocol.ApplyChangedToOpenFilesRequest>({
command: protocol.CommandTypes.ApplyChangedToOpenFiles, command: protocol.CommandTypes.ApplyChangedToOpenFiles,
arguments: { arguments: {
@ -339,7 +339,7 @@ namespace ts.projectSystem {
} }
function findAllReferences(file: string, line: number, offset: number) { function findAllReferences(file: string, line: number, offset: number) {
Debug.assertDefined(files.find(f => f.path === file)); Debug.assertIsDefined(files.find(f => f.path === file));
session.executeCommandSeq<protocol.ReferencesRequest>({ session.executeCommandSeq<protocol.ReferencesRequest>({
command: protocol.CommandTypes.References, command: protocol.CommandTypes.References,
arguments: { arguments: {

View file

@ -14,7 +14,7 @@ and limitations under the License.
***************************************************************************** */ ***************************************************************************** */
declare namespace ts { declare namespace ts {
const versionMajorMinor = "4.5"; const versionMajorMinor = "4.6";
/** The version of the TypeScript compiler release */ /** The version of the TypeScript compiler release */
const version: string; const version: string;
/** /**
@ -897,7 +897,7 @@ declare namespace ts {
export interface TypePredicateNode extends TypeNode { export interface TypePredicateNode extends TypeNode {
readonly kind: SyntaxKind.TypePredicate; readonly kind: SyntaxKind.TypePredicate;
readonly parent: SignatureDeclaration | JSDocTypeExpression; readonly parent: SignatureDeclaration | JSDocTypeExpression;
readonly assertsModifier?: AssertsToken; readonly assertsModifier?: AssertsKeyword;
readonly parameterName: Identifier | ThisTypeNode; readonly parameterName: Identifier | ThisTypeNode;
readonly type?: TypeNode; readonly type?: TypeNode;
} }
@ -968,7 +968,7 @@ declare namespace ts {
} }
export interface MappedTypeNode extends TypeNode, Declaration { export interface MappedTypeNode extends TypeNode, Declaration {
readonly kind: SyntaxKind.MappedType; readonly kind: SyntaxKind.MappedType;
readonly readonlyToken?: ReadonlyToken | PlusToken | MinusToken; readonly readonlyToken?: ReadonlyKeyword | PlusToken | MinusToken;
readonly typeParameter: TypeParameterDeclaration; readonly typeParameter: TypeParameterDeclaration;
readonly nameType?: TypeNode; readonly nameType?: TypeNode;
readonly questionToken?: QuestionToken | PlusToken | MinusToken; readonly questionToken?: QuestionToken | PlusToken | MinusToken;
@ -1465,7 +1465,7 @@ declare namespace ts {
} }
export interface ForOfStatement extends IterationStatement { export interface ForOfStatement extends IterationStatement {
readonly kind: SyntaxKind.ForOfStatement; readonly kind: SyntaxKind.ForOfStatement;
readonly awaitModifier?: AwaitKeywordToken; readonly awaitModifier?: AwaitKeyword;
readonly initializer: ForInitializer; readonly initializer: ForInitializer;
readonly expression: Expression; readonly expression: Expression;
} }
@ -3078,6 +3078,7 @@ declare namespace ts {
ES2019 = 6, ES2019 = 6,
ES2020 = 7, ES2020 = 7,
ES2021 = 8, ES2021 = 8,
ES2022 = 9,
ESNext = 99, ESNext = 99,
JSON = 100, JSON = 100,
Latest = 99 Latest = 99
@ -4042,6 +4043,7 @@ declare namespace ts {
readonly includeCompletionsWithSnippetText?: boolean; readonly includeCompletionsWithSnippetText?: boolean;
readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly includeCompletionsWithInsertText?: boolean; readonly includeCompletionsWithInsertText?: boolean;
readonly includeCompletionsWithClassMemberSnippets?: boolean;
readonly allowIncompleteCompletions?: boolean; readonly allowIncompleteCompletions?: boolean;
readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
@ -9537,6 +9539,13 @@ declare namespace ts.server.protocol {
* values, with insertion text to replace preceding `.` tokens with `?.`. * values, with insertion text to replace preceding `.` tokens with `?.`.
*/ */
readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean;
/**
* If enabled, completions for class members (e.g. methods and properties) will include
* a whole declaration for the member.
* E.g., `class A { f| }` could be completed to `class A { foo(): number {} }`, instead of
* `class A { foo }`.
*/
readonly includeCompletionsWithClassMemberSnippets?: boolean;
readonly allowIncompleteCompletions?: boolean; readonly allowIncompleteCompletions?: boolean;
readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
@ -9658,6 +9667,7 @@ declare namespace ts.server.protocol {
ES2019 = "ES2019", ES2019 = "ES2019",
ES2020 = "ES2020", ES2020 = "ES2020",
ES2021 = "ES2021", ES2021 = "ES2021",
ES2022 = "ES2022",
ESNext = "ESNext" ESNext = "ESNext"
} }
enum ClassificationType { enum ClassificationType {

View file

@ -14,7 +14,7 @@ and limitations under the License.
***************************************************************************** */ ***************************************************************************** */
declare namespace ts { declare namespace ts {
const versionMajorMinor = "4.5"; const versionMajorMinor = "4.6";
/** The version of the TypeScript compiler release */ /** The version of the TypeScript compiler release */
const version: string; const version: string;
/** /**
@ -897,7 +897,7 @@ declare namespace ts {
export interface TypePredicateNode extends TypeNode { export interface TypePredicateNode extends TypeNode {
readonly kind: SyntaxKind.TypePredicate; readonly kind: SyntaxKind.TypePredicate;
readonly parent: SignatureDeclaration | JSDocTypeExpression; readonly parent: SignatureDeclaration | JSDocTypeExpression;
readonly assertsModifier?: AssertsToken; readonly assertsModifier?: AssertsKeyword;
readonly parameterName: Identifier | ThisTypeNode; readonly parameterName: Identifier | ThisTypeNode;
readonly type?: TypeNode; readonly type?: TypeNode;
} }
@ -968,7 +968,7 @@ declare namespace ts {
} }
export interface MappedTypeNode extends TypeNode, Declaration { export interface MappedTypeNode extends TypeNode, Declaration {
readonly kind: SyntaxKind.MappedType; readonly kind: SyntaxKind.MappedType;
readonly readonlyToken?: ReadonlyToken | PlusToken | MinusToken; readonly readonlyToken?: ReadonlyKeyword | PlusToken | MinusToken;
readonly typeParameter: TypeParameterDeclaration; readonly typeParameter: TypeParameterDeclaration;
readonly nameType?: TypeNode; readonly nameType?: TypeNode;
readonly questionToken?: QuestionToken | PlusToken | MinusToken; readonly questionToken?: QuestionToken | PlusToken | MinusToken;
@ -1465,7 +1465,7 @@ declare namespace ts {
} }
export interface ForOfStatement extends IterationStatement { export interface ForOfStatement extends IterationStatement {
readonly kind: SyntaxKind.ForOfStatement; readonly kind: SyntaxKind.ForOfStatement;
readonly awaitModifier?: AwaitKeywordToken; readonly awaitModifier?: AwaitKeyword;
readonly initializer: ForInitializer; readonly initializer: ForInitializer;
readonly expression: Expression; readonly expression: Expression;
} }
@ -3078,6 +3078,7 @@ declare namespace ts {
ES2019 = 6, ES2019 = 6,
ES2020 = 7, ES2020 = 7,
ES2021 = 8, ES2021 = 8,
ES2022 = 9,
ESNext = 99, ESNext = 99,
JSON = 100, JSON = 100,
Latest = 99 Latest = 99
@ -4042,6 +4043,7 @@ declare namespace ts {
readonly includeCompletionsWithSnippetText?: boolean; readonly includeCompletionsWithSnippetText?: boolean;
readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly includeCompletionsWithInsertText?: boolean; readonly includeCompletionsWithInsertText?: boolean;
readonly includeCompletionsWithClassMemberSnippets?: boolean;
readonly allowIncompleteCompletions?: boolean; readonly allowIncompleteCompletions?: boolean;
readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */

View file

@ -0,0 +1,46 @@
/a.js(18,9): error TS1210: Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of 'arguments'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.
==== /a.js (1 errors) ====
class A {
/**
* Constructor
*
* @param {object} [foo={}]
*/
constructor(foo = {}) {
const key = "bar";
/**
* @type object
*/
this.foo = foo;
/**
* @type object
*/
const arguments = this.arguments;
~~~~~~~~~
!!! error TS1210: Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of 'arguments'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.
/**
* @type object
*/
this.bar = arguments.bar;
/**
* @type object
*/
this.baz = arguments[key];
/**
* @type object
*/
this.options = arguments;
}
get arguments() {
return { bar: {} };
}
}

View file

@ -0,0 +1,44 @@
/a.js(16,9): error TS1210: Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of 'arguments'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.
==== /a.js (1 errors) ====
class A {
/**
* @param {object} [foo={}]
*/
m(foo = {}) {
const key = "bar";
/**
* @type object
*/
this.foo = foo;
/**
* @type object
*/
const arguments = this.arguments;
~~~~~~~~~
!!! error TS1210: Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of 'arguments'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.
/**
* @type object
*/
this.bar = arguments.bar;
/**
* @type object
*/
this.baz = arguments[key];
/**
* @type object
*/
this.options = arguments;
}
get arguments() {
return { bar: {} };
}
}

View file

@ -0,0 +1,18 @@
//// [callChainWithSuper.ts]
// GH#34952
class Base { method?() {} }
class Derived extends Base {
method1() { return super.method?.(); }
method2() { return super["method"]?.(); }
}
//// [callChainWithSuper.js]
"use strict";
// GH#34952
class Base {
method() { }
}
class Derived extends Base {
method1() { return super.method?.(); }
method2() { return super["method"]?.(); }
}

View file

@ -30,7 +30,7 @@ declare const pli: {
(streams: ReadonlyArray<R | W | RW>): Promise<void>; (streams: ReadonlyArray<R | W | RW>): Promise<void>;
>streams : Symbol(streams, Decl(callWithSpread4.ts, 5, 5)) >streams : Symbol(streams, Decl(callWithSpread4.ts, 5, 5))
>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.es2019.array.d.ts, --, --)) >ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.es2019.array.d.ts, --, --) ... and 1 more)
>R : Symbol(R, Decl(callWithSpread4.ts, 0, 0)) >R : Symbol(R, Decl(callWithSpread4.ts, 0, 0))
>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) >W : Symbol(W, Decl(callWithSpread4.ts, 0, 22))
>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) >RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22))
@ -43,7 +43,7 @@ declare const pli: {
>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) >RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22))
>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) >W : Symbol(W, Decl(callWithSpread4.ts, 0, 22))
>streams : Symbol(streams, Decl(callWithSpread4.ts, 6, 23)) >streams : Symbol(streams, Decl(callWithSpread4.ts, 6, 23))
>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 2 more) >Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 3 more)
>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) >RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22))
>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) >W : Symbol(W, Decl(callWithSpread4.ts, 0, 22))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) >Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --))

View file

@ -9,16 +9,14 @@ tests/cases/compiler/complicatedIndexedAccessKeyofReliesOnKeyofNeverUpperBound.t
Type '"text" | "email"' is not assignable to type 'ChannelOfType<T, TextChannel>["type"]'. Type '"text" | "email"' is not assignable to type 'ChannelOfType<T, TextChannel>["type"]'.
Type '"text"' is not assignable to type 'ChannelOfType<T, TextChannel>["type"]'. Type '"text"' is not assignable to type 'ChannelOfType<T, TextChannel>["type"]'.
Type '"text"' is not assignable to type 'T & "text"'. Type '"text"' is not assignable to type 'T & "text"'.
Type '"text"' is not assignable to type 'T'. Type 'T' is not assignable to type 'T & "text"'.
'"text"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '"text" | "email"'. Type '"text" | "email"' is not assignable to type 'T & "text"'.
Type 'T' is not assignable to type 'T & "text"'. Type '"text"' is not assignable to type 'T & "text"'.
Type '"text" | "email"' is not assignable to type 'T & "text"'. Type '"text"' is not assignable to type 'T'.
Type '"text"' is not assignable to type 'T & "text"'. '"text"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '"text" | "email"'.
Type '"text"' is not assignable to type 'T'. Type 'T' is not assignable to type '"text"'.
'"text"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '"text" | "email"'. Type '"text" | "email"' is not assignable to type '"text"'.
Type 'T' is not assignable to type '"text"'. Type '"email"' is not assignable to type '"text"'.
Type '"text" | "email"' is not assignable to type '"text"'.
Type '"email"' is not assignable to type '"text"'.
==== tests/cases/compiler/complicatedIndexedAccessKeyofReliesOnKeyofNeverUpperBound.ts (1 errors) ==== ==== tests/cases/compiler/complicatedIndexedAccessKeyofReliesOnKeyofNeverUpperBound.ts (1 errors) ====
@ -67,16 +65,14 @@ tests/cases/compiler/complicatedIndexedAccessKeyofReliesOnKeyofNeverUpperBound.t
!!! error TS2322: Type '"text" | "email"' is not assignable to type 'ChannelOfType<T, TextChannel>["type"]'. !!! error TS2322: Type '"text" | "email"' is not assignable to type 'ChannelOfType<T, TextChannel>["type"]'.
!!! error TS2322: Type '"text"' is not assignable to type 'ChannelOfType<T, TextChannel>["type"]'. !!! error TS2322: Type '"text"' is not assignable to type 'ChannelOfType<T, TextChannel>["type"]'.
!!! error TS2322: Type '"text"' is not assignable to type 'T & "text"'. !!! error TS2322: Type '"text"' is not assignable to type 'T & "text"'.
!!! error TS2322: Type '"text"' is not assignable to type 'T'. !!! error TS2322: Type 'T' is not assignable to type 'T & "text"'.
!!! error TS2322: '"text"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '"text" | "email"'. !!! error TS2322: Type '"text" | "email"' is not assignable to type 'T & "text"'.
!!! error TS2322: Type 'T' is not assignable to type 'T & "text"'. !!! error TS2322: Type '"text"' is not assignable to type 'T & "text"'.
!!! error TS2322: Type '"text" | "email"' is not assignable to type 'T & "text"'. !!! error TS2322: Type '"text"' is not assignable to type 'T'.
!!! error TS2322: Type '"text"' is not assignable to type 'T & "text"'. !!! error TS2322: '"text"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '"text" | "email"'.
!!! error TS2322: Type '"text"' is not assignable to type 'T'. !!! error TS2322: Type 'T' is not assignable to type '"text"'.
!!! error TS2322: '"text"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '"text" | "email"'. !!! error TS2322: Type '"text" | "email"' is not assignable to type '"text"'.
!!! error TS2322: Type 'T' is not assignable to type '"text"'. !!! error TS2322: Type '"email"' is not assignable to type '"text"'.
!!! error TS2322: Type '"text" | "email"' is not assignable to type '"text"'.
!!! error TS2322: Type '"email"' is not assignable to type '"text"'.
} }
const newTextChannel = makeNewChannel('text'); const newTextChannel = makeNewChannel('text');

View file

@ -0,0 +1,53 @@
//// [contextuallyTypedSymbolNamedProperties.ts]
// Repros from #43628
const A = Symbol("A");
const B = Symbol("B");
type Action =
| {type: typeof A, data: string}
| {type: typeof B, data: number}
declare const ab: Action;
declare function f<T extends { type: string | symbol }>(action: T, blah: { [K in T['type']]: (p: K) => void }): any;
f(ab, {
[A]: ap => { ap.description },
[B]: bp => { bp.description },
})
const x: { [sym: symbol]: (p: string) => void } = { [A]: s => s.length };
//// [contextuallyTypedSymbolNamedProperties.js]
"use strict";
// Repros from #43628
const A = Symbol("A");
const B = Symbol("B");
f(ab, {
[A]: ap => { ap.description; },
[B]: bp => { bp.description; },
});
const x = { [A]: s => s.length };
//// [contextuallyTypedSymbolNamedProperties.d.ts]
declare const A: unique symbol;
declare const B: unique symbol;
declare type Action = {
type: typeof A;
data: string;
} | {
type: typeof B;
data: number;
};
declare const ab: Action;
declare function f<T extends {
type: string | symbol;
}>(action: T, blah: {
[K in T['type']]: (p: K) => void;
}): any;
declare const x: {
[sym: symbol]: (p: string) => void;
};

View file

@ -0,0 +1,73 @@
=== tests/cases/compiler/contextuallyTypedSymbolNamedProperties.ts ===
// Repros from #43628
const A = Symbol("A");
>A : Symbol(A, Decl(contextuallyTypedSymbolNamedProperties.ts, 2, 5))
>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --))
const B = Symbol("B");
>B : Symbol(B, Decl(contextuallyTypedSymbolNamedProperties.ts, 3, 5))
>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --))
type Action =
>Action : Symbol(Action, Decl(contextuallyTypedSymbolNamedProperties.ts, 3, 22))
| {type: typeof A, data: string}
>type : Symbol(type, Decl(contextuallyTypedSymbolNamedProperties.ts, 6, 7))
>A : Symbol(A, Decl(contextuallyTypedSymbolNamedProperties.ts, 2, 5))
>data : Symbol(data, Decl(contextuallyTypedSymbolNamedProperties.ts, 6, 22))
| {type: typeof B, data: number}
>type : Symbol(type, Decl(contextuallyTypedSymbolNamedProperties.ts, 7, 7))
>B : Symbol(B, Decl(contextuallyTypedSymbolNamedProperties.ts, 3, 5))
>data : Symbol(data, Decl(contextuallyTypedSymbolNamedProperties.ts, 7, 22))
declare const ab: Action;
>ab : Symbol(ab, Decl(contextuallyTypedSymbolNamedProperties.ts, 9, 13))
>Action : Symbol(Action, Decl(contextuallyTypedSymbolNamedProperties.ts, 3, 22))
declare function f<T extends { type: string | symbol }>(action: T, blah: { [K in T['type']]: (p: K) => void }): any;
>f : Symbol(f, Decl(contextuallyTypedSymbolNamedProperties.ts, 9, 25))
>T : Symbol(T, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 19))
>type : Symbol(type, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 30))
>action : Symbol(action, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 56))
>T : Symbol(T, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 19))
>blah : Symbol(blah, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 66))
>K : Symbol(K, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 76))
>T : Symbol(T, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 19))
>p : Symbol(p, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 94))
>K : Symbol(K, Decl(contextuallyTypedSymbolNamedProperties.ts, 11, 76))
f(ab, {
>f : Symbol(f, Decl(contextuallyTypedSymbolNamedProperties.ts, 9, 25))
>ab : Symbol(ab, Decl(contextuallyTypedSymbolNamedProperties.ts, 9, 13))
[A]: ap => { ap.description },
>[A] : Symbol([A], Decl(contextuallyTypedSymbolNamedProperties.ts, 13, 7))
>A : Symbol(A, Decl(contextuallyTypedSymbolNamedProperties.ts, 2, 5))
>ap : Symbol(ap, Decl(contextuallyTypedSymbolNamedProperties.ts, 14, 8))
>ap.description : Symbol(Symbol.description, Decl(lib.es2019.symbol.d.ts, --, --))
>ap : Symbol(ap, Decl(contextuallyTypedSymbolNamedProperties.ts, 14, 8))
>description : Symbol(Symbol.description, Decl(lib.es2019.symbol.d.ts, --, --))
[B]: bp => { bp.description },
>[B] : Symbol([B], Decl(contextuallyTypedSymbolNamedProperties.ts, 14, 34))
>B : Symbol(B, Decl(contextuallyTypedSymbolNamedProperties.ts, 3, 5))
>bp : Symbol(bp, Decl(contextuallyTypedSymbolNamedProperties.ts, 15, 8))
>bp.description : Symbol(Symbol.description, Decl(lib.es2019.symbol.d.ts, --, --))
>bp : Symbol(bp, Decl(contextuallyTypedSymbolNamedProperties.ts, 15, 8))
>description : Symbol(Symbol.description, Decl(lib.es2019.symbol.d.ts, --, --))
})
const x: { [sym: symbol]: (p: string) => void } = { [A]: s => s.length };
>x : Symbol(x, Decl(contextuallyTypedSymbolNamedProperties.ts, 18, 5))
>sym : Symbol(sym, Decl(contextuallyTypedSymbolNamedProperties.ts, 18, 12))
>p : Symbol(p, Decl(contextuallyTypedSymbolNamedProperties.ts, 18, 27))
>[A] : Symbol([A], Decl(contextuallyTypedSymbolNamedProperties.ts, 18, 51))
>A : Symbol(A, Decl(contextuallyTypedSymbolNamedProperties.ts, 2, 5))
>s : Symbol(s, Decl(contextuallyTypedSymbolNamedProperties.ts, 18, 56))
>s.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --))
>s : Symbol(s, Decl(contextuallyTypedSymbolNamedProperties.ts, 18, 56))
>length : Symbol(String.length, Decl(lib.es5.d.ts, --, --))

View file

@ -0,0 +1,77 @@
=== tests/cases/compiler/contextuallyTypedSymbolNamedProperties.ts ===
// Repros from #43628
const A = Symbol("A");
>A : unique symbol
>Symbol("A") : unique symbol
>Symbol : SymbolConstructor
>"A" : "A"
const B = Symbol("B");
>B : unique symbol
>Symbol("B") : unique symbol
>Symbol : SymbolConstructor
>"B" : "B"
type Action =
>Action : Action
| {type: typeof A, data: string}
>type : unique symbol
>A : unique symbol
>data : string
| {type: typeof B, data: number}
>type : unique symbol
>B : unique symbol
>data : number
declare const ab: Action;
>ab : Action
declare function f<T extends { type: string | symbol }>(action: T, blah: { [K in T['type']]: (p: K) => void }): any;
>f : <T extends { type: string | symbol; }>(action: T, blah: { [K in T["type"]]: (p: K) => void; }) => any
>type : string | symbol
>action : T
>blah : { [K in T["type"]]: (p: K) => void; }
>p : K
f(ab, {
>f(ab, { [A]: ap => { ap.description }, [B]: bp => { bp.description },}) : any
>f : <T extends { type: string | symbol; }>(action: T, blah: { [K in T["type"]]: (p: K) => void; }) => any
>ab : Action
>{ [A]: ap => { ap.description }, [B]: bp => { bp.description },} : { [A]: (ap: unique symbol) => void; [B]: (bp: unique symbol) => void; }
[A]: ap => { ap.description },
>[A] : (ap: unique symbol) => void
>A : unique symbol
>ap => { ap.description } : (ap: unique symbol) => void
>ap : unique symbol
>ap.description : string | undefined
>ap : unique symbol
>description : string | undefined
[B]: bp => { bp.description },
>[B] : (bp: unique symbol) => void
>B : unique symbol
>bp => { bp.description } : (bp: unique symbol) => void
>bp : unique symbol
>bp.description : string | undefined
>bp : unique symbol
>description : string | undefined
})
const x: { [sym: symbol]: (p: string) => void } = { [A]: s => s.length };
>x : { [sym: symbol]: (p: string) => void; }
>sym : symbol
>p : string
>{ [A]: s => s.length } : { [A]: (s: string) => number; }
>[A] : (s: string) => number
>A : unique symbol
>s => s.length : (s: string) => number
>s : string
>s.length : number
>s : string
>length : number

View file

@ -28,15 +28,11 @@ tests/cases/conformance/controlFlow/controlFlowAliasing.ts(232,13): error TS2322
Type 'number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.
tests/cases/conformance/controlFlow/controlFlowAliasing.ts(233,13): error TS2322: Type 'string | number' is not assignable to type 'string'. tests/cases/conformance/controlFlow/controlFlowAliasing.ts(233,13): error TS2322: Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.
tests/cases/conformance/controlFlow/controlFlowAliasing.ts(267,13): error TS2322: Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
tests/cases/conformance/controlFlow/controlFlowAliasing.ts(270,13): error TS2322: Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/controlFlow/controlFlowAliasing.ts(280,5): error TS2448: Block-scoped variable 'a' used before its declaration. tests/cases/conformance/controlFlow/controlFlowAliasing.ts(280,5): error TS2448: Block-scoped variable 'a' used before its declaration.
tests/cases/conformance/controlFlow/controlFlowAliasing.ts(280,5): error TS2454: Variable 'a' is used before being assigned. tests/cases/conformance/controlFlow/controlFlowAliasing.ts(280,5): error TS2454: Variable 'a' is used before being assigned.
==== tests/cases/conformance/controlFlow/controlFlowAliasing.ts (19 errors) ==== ==== tests/cases/conformance/controlFlow/controlFlowAliasing.ts (17 errors) ====
// Narrowing by aliased conditional expressions // Narrowing by aliased conditional expressions
function f10(x: string | number) { function f10(x: string | number) {
@ -349,15 +345,9 @@ tests/cases/conformance/controlFlow/controlFlowAliasing.ts(280,5): error TS2454:
function foo({ kind, payload }: Data) { function foo({ kind, payload }: Data) {
if (kind === 'str') { if (kind === 'str') {
let t: string = payload; let t: string = payload;
~
!!! error TS2322: Type 'string | number' is not assignable to type 'string'.
!!! error TS2322: Type 'number' is not assignable to type 'string'.
} }
else { else {
let t: number = payload; let t: number = payload;
~
!!! error TS2322: Type 'string | number' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
} }
} }

View file

@ -888,12 +888,12 @@ function foo({ kind, payload }: Data) {
let t: string = payload; let t: string = payload;
>t : string >t : string
>payload : string | number >payload : string
} }
else { else {
let t: number = payload; let t: number = payload;
>t : number >t : number
>payload : string | number >payload : number
} }
} }

View file

@ -220,4 +220,24 @@ tests/cases/conformance/controlFlow/controlFlowGenericTypes.ts(168,9): error TS2
this.validateRow(row); this.validateRow(row);
} }
} }
// Repro from #46495
interface Button {
type: "button";
text: string;
}
interface Checkbox {
type: "checkbox";
isChecked: boolean;
}
type Control = Button | Checkbox;
function update<T extends Control, K extends keyof T>(control : T | undefined, key: K, value: T[K]): void {
if (control !== undefined) {
control[key] = value;
}
}

View file

@ -190,6 +190,26 @@ class SqlTable<T> {
this.validateRow(row); this.validateRow(row);
} }
} }
// Repro from #46495
interface Button {
type: "button";
text: string;
}
interface Checkbox {
type: "checkbox";
isChecked: boolean;
}
type Control = Button | Checkbox;
function update<T extends Control, K extends keyof T>(control : T | undefined, key: K, value: T[K]): void {
if (control !== undefined) {
control[key] = value;
}
}
//// [controlFlowGenericTypes.js] //// [controlFlowGenericTypes.js]
@ -343,3 +363,8 @@ var SqlTable = /** @class */ (function () {
}; };
return SqlTable; return SqlTable;
}()); }());
function update(control, key, value) {
if (control !== undefined) {
control[key] = value;
}
}

View file

@ -574,3 +574,55 @@ class SqlTable<T> {
} }
} }
// Repro from #46495
interface Button {
>Button : Symbol(Button, Decl(controlFlowGenericTypes.ts, 190, 1))
type: "button";
>type : Symbol(Button.type, Decl(controlFlowGenericTypes.ts, 194, 18))
text: string;
>text : Symbol(Button.text, Decl(controlFlowGenericTypes.ts, 195, 19))
}
interface Checkbox {
>Checkbox : Symbol(Checkbox, Decl(controlFlowGenericTypes.ts, 197, 1))
type: "checkbox";
>type : Symbol(Checkbox.type, Decl(controlFlowGenericTypes.ts, 199, 20))
isChecked: boolean;
>isChecked : Symbol(Checkbox.isChecked, Decl(controlFlowGenericTypes.ts, 200, 21))
}
type Control = Button | Checkbox;
>Control : Symbol(Control, Decl(controlFlowGenericTypes.ts, 202, 1))
>Button : Symbol(Button, Decl(controlFlowGenericTypes.ts, 190, 1))
>Checkbox : Symbol(Checkbox, Decl(controlFlowGenericTypes.ts, 197, 1))
function update<T extends Control, K extends keyof T>(control : T | undefined, key: K, value: T[K]): void {
>update : Symbol(update, Decl(controlFlowGenericTypes.ts, 204, 33))
>T : Symbol(T, Decl(controlFlowGenericTypes.ts, 206, 16))
>Control : Symbol(Control, Decl(controlFlowGenericTypes.ts, 202, 1))
>K : Symbol(K, Decl(controlFlowGenericTypes.ts, 206, 34))
>T : Symbol(T, Decl(controlFlowGenericTypes.ts, 206, 16))
>control : Symbol(control, Decl(controlFlowGenericTypes.ts, 206, 54))
>T : Symbol(T, Decl(controlFlowGenericTypes.ts, 206, 16))
>key : Symbol(key, Decl(controlFlowGenericTypes.ts, 206, 78))
>K : Symbol(K, Decl(controlFlowGenericTypes.ts, 206, 34))
>value : Symbol(value, Decl(controlFlowGenericTypes.ts, 206, 86))
>T : Symbol(T, Decl(controlFlowGenericTypes.ts, 206, 16))
>K : Symbol(K, Decl(controlFlowGenericTypes.ts, 206, 34))
if (control !== undefined) {
>control : Symbol(control, Decl(controlFlowGenericTypes.ts, 206, 54))
>undefined : Symbol(undefined)
control[key] = value;
>control : Symbol(control, Decl(controlFlowGenericTypes.ts, 206, 54))
>key : Symbol(key, Decl(controlFlowGenericTypes.ts, 206, 78))
>value : Symbol(value, Decl(controlFlowGenericTypes.ts, 206, 86))
}
}

Some files were not shown because too many files have changed in this diff Show more